<?php
// admin/ajax/student_search.php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['admin'])) { http_response_code(403); exit; }

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost","root","","edencamp_eden_exam");
$mysqli->set_charset("utf8mb4");

$q = trim($_GET['q'] ?? '');
header('Content-Type: application/json');

if ($q === '' || strlen($q) < 2) { echo json_encode([]); exit; }

// Try studentss first
$rows = [];
$st = $mysqli->prepare("SELECT id, full_name AS name FROM studentss WHERE full_name LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%') ORDER BY id DESC LIMIT 10");
$st->bind_param("ss", $q, $q);
$st->execute(); $res = $st->get_result();
while ($r = $res->fetch_assoc()) $rows[] = ['id'=>$r['id'], 'name'=>$r['name']];

// Fallback to students table if nothing found
if (count($rows)===0) {
  $st = $mysqli->prepare("SELECT id, name FROM students WHERE name LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%') ORDER BY id DESC LIMIT 10");
  $st->bind_param("ss", $q, $q);
  $st->execute(); $res = $st->get_result();
  while ($r = $res->fetch_assoc()) $rows[] = ['id'=>$r['id'], 'name'=>$r['name']];
}

echo json_encode($rows);
