<?php
include('includes/dbconnection.php');

// Search students by registration no. or name — used by Select2 AJAX in pay.php
// Uses studentRegNo (pre-admission registration number, not studentno)
if (isset($_GET['q'])) {
    $search = '%' . $_GET['q'] . '%';

$stmt = $con->prepare(
    "SELECT studentRegNo, studentName, class, stream, email, academic_session, admission_term
     FROM students
     WHERE (studentRegNo LIKE ? OR studentName LIKE ?)
     AND status = 2
     ORDER BY studentName ASC"
);
    $stmt->bind_param("ss", $search, $search);
    $stmt->execute();
    $stmt->bind_result($studentRegNo, $studentName, $class, $stream, $email, $academic_session, $admission_term);

    $results = [];
    while ($stmt->fetch()) {
        $results[] = [
            'id'               => $studentRegNo,
            'text'             => $studentRegNo . ' | ' . $studentName,
            'studentName'      => $studentName,
            'class'            => $class,
            'stream'           => $stream,
            'email'            => $email,
            'academic_session' => $academic_session,
            'admission_term'   => $admission_term,
        ];
    }
    $stmt->close();

    header('Content-Type: application/json');
    echo json_encode(['results' => $results]);
}

$con->close();
