<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(0); // Avoid breaking JSON with warnings

include('includes/config.php');

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

    // Fetch matching book copies that are available
    $sql = "SELECT 
                c.id AS CopyId,
                c.book_no,
                b.BookName,
                c.accession_no,
                b.AuthorIds
            FROM tblbookcopies c
            JOIN tblbooks b ON c.book_id = b.id
            WHERE (b.BookName LIKE :query 
                   OR c.accession_no LIKE :query 
                   OR c.book_no LIKE :query)
              AND c.book_status = 'available'
            LIMIT 15";

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

    $results = [];

    foreach ($books as $book) {
        $authorNames = '';

        // Fetch author names (excluding deleted authors)
        if (!empty($book['AuthorIds'])) {
            $ids = explode(',', $book['AuthorIds']);
            $placeholders = implode(',', array_fill(0, count($ids), '?'));

            $authorQuery = $dbh->prepare("
                SELECT AuthorName 
                FROM tblauthors 
                WHERE id IN ($placeholders) AND is_deleted = 0
            ");
            $authorQuery->execute($ids);
            $names = $authorQuery->fetchAll(PDO::FETCH_COLUMN);
            $authorNames = !empty($names) ? implode(', ', $names) : 'No Active Authors';
        } else {
            $authorNames = 'No Authors';
        }

        $results[] = [
            "id" => $book['CopyId'],
            "text" => "{$book['book_no']} | {$book['accession_no']} | {$book['BookName']} | Author(s): {$authorNames}"
        ];
    }

    echo json_encode($results);

} catch (PDOException $e) {
    echo json_encode(["error" => $e->getMessage()]);
}
?>