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

if (!empty($_POST['qrcode'])) {
    $qrcode = trim($_POST['qrcode']); // scanned QR text

    // Extract book_no from URL if it's present
    if (strpos($qrcode, 'bookcopy=') !== false) {
        parse_str(parse_url($qrcode, PHP_URL_QUERY), $params);
        $qrcode = $params['bookcopy'] ?? $qrcode;
    }

    // Query by book_no instead of QRCode path
    $sql = "SELECT 
                c.id AS CopyId,
                c.book_no,
                b.BookName,
                c.accession_no,
                b.ISBNNumber,
                a.AuthorName
            FROM tblbookcopies c
            JOIN tblbooks b ON c.book_id = b.id
            LEFT JOIN tblauthors a ON b.AuthorIds = a.id
            WHERE c.book_no = :qrcode
            AND c.book_status = 'available'";

    $query = $dbh->prepare($sql);
    $query->bindParam(':qrcode', $qrcode, PDO::PARAM_STR);
    $query->execute();
    $book = $query->fetch(PDO::FETCH_ASSOC);

    if ($book) {
        echo json_encode(['status' => 'success'] + $book);
    } else {
        echo json_encode([
            'status' => 'error',
            'msg' => 'Book not found or not available',
            'debug_qr' => $qrcode
        ]);
    }
    exit;
}

echo json_encode(['status' => 'error', 'msg' => 'Invalid QR code']);
?>