<?php
session_start();
include('includes/config.php');

// Only logged-in admin
if (strlen($_SESSION['alogin']) == 0) {
    http_response_code(403);
    echo json_encode([]);
    exit;
}

$type = isset($_GET['type']) ? $_GET['type'] : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$results = [];

if ($type === 'Student') {
    $sql = "SELECT StudentID AS BorrowerID, FullName, id
            FROM tblstudents 
            WHERE (StudentID LIKE :search OR FullName LIKE :search) 
            AND status = 1
            LIMIT 20";
} elseif ($type === 'Staff') {
    $sql = "SELECT StaffID AS BorrowerID, FullName, id
            FROM tblstaff 
            WHERE (StaffID LIKE :search OR FullName LIKE :search) 
            AND status = 1
            LIMIT 20";
} else {
    echo json_encode([]);
    exit;
}

$query = $dbh->prepare($sql);
$search = "%$q%";
$query->bindParam(':search', $search, PDO::PARAM_STR);
$query->execute();
$data = $query->fetchAll(PDO::FETCH_ASSOC);

// Ensure correct keys are returned
foreach ($data as $row) {
    $results[] = [
        'BorrowerID' => $row['BorrowerID'],
        'PrimaryID' => $row['id'],
        'FullName' => $row['FullName']
    ];
}

header('Content-Type: application/json');
echo json_encode($results);
?>