<?php
/**
 * Student search for canteen biometric enrollment pages.
 * POST: q (search string), limit (optional, default 10)
 * Auth: admin / headteacher
 * Returns: { success, students: [{ id, name, class_name, student_code, photo_url, has_fingerprint, has_facial }] }
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');
header('Cache-Control: no-store');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_active();
canteen_require_role(['admin', 'headteacher'], true);

$q     = trim($_POST['q']     ?? '');
$limit = min(20, max(1, (int)($_POST['limit'] ?? 10)));

if (strlen($q) < 1) {
    echo json_encode(['success' => false, 'message' => 'Query too short.']);
    exit;
}

$conn = getDBConnection();

$like = '%' . $q . '%';
$stmt = $conn->prepare(
    "SELECT s.id, s.first_name, s.last_name, s.class, s.student_id AS student_code, s.photo_path,
            (bc.student_id IS NOT NULL AND bc.credential_id IS NOT NULL) AS has_fingerprint,
            (bc.student_id IS NOT NULL AND bc.facial_descriptor IS NOT NULL) AS has_facial
     FROM students s
     LEFT JOIN canteen_biometric_credentials bc ON bc.student_id = s.id
     WHERE s.status = 'active'
       AND (s.first_name LIKE ? OR s.last_name LIKE ?
            OR CONCAT(s.first_name,' ',s.last_name) LIKE ?
            OR s.student_id LIKE ?)
     ORDER BY s.last_name ASC, s.first_name ASC
     LIMIT ?"
);
$stmt->bind_param('ssssi', $like, $like, $like, $like, $limit);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$conn->close();

$students = array_map(function ($r) {
    $photoUrl = '';
    if (!empty($r['photo_path'])) {
        $photoUrl = BASE_URL . 'uploads/students/' . basename($r['photo_path']);
    }
    return [
        'id'             => (int)$r['id'],
        'name'           => trim($r['first_name'] . ' ' . $r['last_name']),
        'class_name'     => $r['class'],
        'student_code'   => $r['student_code'],
        'photo_url'      => $photoUrl,
        'has_fingerprint'=> (bool)$r['has_fingerprint'],
        'has_facial'     => (bool)$r['has_facial'],
    ];
}, $rows);

echo json_encode(['success' => true, 'students' => $students]);
