<?php
// ../ajax/search_students.php
header('Content-Type: application/json; charset=utf-8');

mysqli_report(MYSQLI_REPORT_OFF);

// 1) Connect
try {
    if (@include_once __DIR__ . '/../includes/db.php') {
        if (!isset($conn) || !($conn instanceof mysqli)) {
            $conn = new mysqli("localhost", "root", "", "edencamp_eden_exam");
        }
    } else {
        $conn = new mysqli("localhost", "root", "", "edencamp_eden_exam");
    }

    if ($conn->connect_error) {
        throw new Exception($conn->connect_error);
    }

    $conn->set_charset("utf8mb4");
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["error" => "DB error", "detail" => $e->getMessage()]);
    exit;
}

// 2) Read query text
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($q === '' || mb_strlen($q) < 2) {
    echo json_encode([]);
    exit;
}

// 3) Search students with all fields needed for auto-fill
$sql = "
    SELECT
        id,
        full_name,
        title,
        gender,
        dob,
        nationality,
        nic_passport,
        mobile,
        email,
        address1,
        address2,
        city,
        country,
        guardian_name,
        guardian_relationship,
        guardian_contact,
        reference_no,
        center_reg_no,
        created_at
    FROM studentss
    WHERE (
           full_name     LIKE ?
        OR nic_passport  LIKE ?
        OR reference_no  LIKE ?
        OR center_reg_no LIKE ?
        OR mobile        LIKE ?
    )
    ORDER BY created_at DESC, id DESC
    LIMIT 20
";

$like = '%' . $q . '%';

$stmt = $conn->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(["error" => "Prepare failed", "detail" => $conn->error]);
    exit;
}

$stmt->bind_param('sssss', $like, $like, $like, $like, $like);

if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(["error" => "Execute failed", "detail" => $stmt->error]);
    exit;
}

$res = $stmt->get_result();

// 4) Shape results for frontend auto-fill
$out = [];
while ($row = $res->fetch_assoc()) {
    $out[] = [
        "id"                    => (int)($row["id"] ?? 0),
        "full_name"             => (string)($row["full_name"] ?? ''),
        "title"                 => (string)($row["title"] ?? ''),
        "gender"                => (string)($row["gender"] ?? ''),
        "dob"                   => (string)($row["dob"] ?? ''),
        "nationality"           => (string)($row["nationality"] ?? ''),

        "reg_no"                => (string)($row["reference_no"] ?: ($row["center_reg_no"] ?? '')),
        "reference_no"          => (string)($row["reference_no"] ?? ''),
        "center_reg_no"         => (string)($row["center_reg_no"] ?? ''),

        "nic"                   => (string)($row["nic_passport"] ?? ''),
        "nic_passport"          => (string)($row["nic_passport"] ?? ''),
        "mobile"                => (string)($row["mobile"] ?? ''),
        "email"                 => (string)($row["email"] ?? ''),

        "address1"              => (string)($row["address1"] ?? ''),
        "address2"              => (string)($row["address2"] ?? ''),
        "city"                  => (string)($row["city"] ?? ''),
        "country"               => (string)($row["country"] ?? ''),

        "guardian_name"         => (string)($row["guardian_name"] ?? ''),
        "guardian_relationship" => (string)($row["guardian_relationship"] ?? ''),
        "guardian_contact"      => (string)($row["guardian_contact"] ?? '')
    ];
}

echo json_encode($out, JSON_UNESCAPED_UNICODE);
exit;