<?php
header("Content-Type: application/json");
require_once "../config.php";

$search = $_GET['search'] ?? $_POST['search'] ?? '';

try {
    if ($search != '') {
        $stmt = $dbh->prepare("
            SELECT 
                c.id            AS copy_id,
                c.book_id,
                c.book_no,
                c.book_status,
                c.QRCode,
                b.BookName,
                b.AuthorIds,
                b.ISBNNumber
            FROM tblbookcopies AS c
            LEFT JOIN tblbooks AS b ON c.book_id = b.id
            WHERE c.book_status = 'available' 
            AND (c.book_no LIKE :q OR CAST(c.book_id AS CHAR) LIKE :q)
        ");
        $stmt->bindValue(':q', "%$search%", PDO::PARAM_STR);
    } else {
        $stmt = $dbh->prepare("
            SELECT 
                c.id            AS copy_id,
                c.book_id,
                c.book_no,
                c.book_status,
                c.QRCode,
                b.BookName,
                b.AuthorIds,
                b.ISBNNumber
            FROM tblbookcopies AS c
            LEFT JOIN tblbooks AS b ON c.book_id = b.id
            WHERE c.book_status = 'available' 
        ");
    }

    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status' => 'success', 'data' => $rows]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
