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

// Ensure only logged-in admins can access
if (strlen($_SESSION['alogin']) == 0) {
    http_response_code(403);
    echo json_encode([]);
    exit;
}

// Search term from Select2
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$sql = "SELECT id, BookName, ISBNNumber, current_count
        FROM tblbooks
        WHERE (BookName LIKE :search OR ISBNNumber LIKE :search)
        AND current_count > 0
        LIMIT 20";

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

$books = $query->fetchAll(PDO::FETCH_ASSOC);

// Format results for Select2
$results = [];
foreach ($books as $b) {
    $results[] = [
        'id'   => $b['id'],
        'text' => "{$b['BookName']} (ISBN: {$b['ISBNNumber']}) (Available: {$b['current_count']})"
    ];
}

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