<?php

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json; charset=utf-8');

function schoolLookupResponse(
    bool $success,
    string $message,
    ?array $school = null
): void {
    echo json_encode(
        [
            'success' => $success,
            'message' => $message,
            'school'  => $school
        ],
        JSON_UNESCAPED_UNICODE
    );

    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    schoolLookupResponse(false, 'Invalid request method.');
}

$censusNo = trim((string)($_POST['census_no'] ?? ''));

if ($censusNo === '' || mb_strlen($censusNo) > 50) {
    schoolLookupResponse(false, 'Please enter a valid census number.');
}

$stmt = mysqli_prepare(
    $conn,
    'SELECT
        census_no,
        district,
        zone_name,
        division_name,
        school_name,
        school_category,
        school_type
     FROM schools
     WHERE census_no = ?
     LIMIT 1'
);

if (!$stmt) {
    schoolLookupResponse(false, 'Unable to search for the school.');
}

mysqli_stmt_bind_param($stmt, 's', $censusNo);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);
$school = mysqli_fetch_assoc($result);

mysqli_stmt_close($stmt);

if (!$school) {
    schoolLookupResponse(false, 'School not found.');
}

$surveyStatement = mysqli_prepare(
    $conn,
    'SELECT id, survey_date
     FROM surveys
     WHERE census_no = ?
     LIMIT 1'
);

mysqli_stmt_bind_param(
    $surveyStatement,
    's',
    $censusNo
);

mysqli_stmt_execute($surveyStatement);

$surveyResult =
    mysqli_stmt_get_result($surveyStatement);

$existingSurvey =
    mysqli_fetch_assoc($surveyResult);

mysqli_stmt_close($surveyStatement);

echo json_encode(
    [
        'success' => true,
        'message' => 'School found.',
        'school' => $school,
        'survey_exists' => (bool)$existingSurvey,
        'survey_id' => $existingSurvey
            ? (int)$existingSurvey['id']
            : null,
        'survey_date' => $existingSurvey['survey_date'] ?? null
    ],
    JSON_UNESCAPED_UNICODE
);

exit();