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

$returnBook = trim($_POST['bookQrId'] ?? $_GET['bookQrId'] ?? '');

if ($returnBook === '') {
    echo json_encode(['status' => 'error', 'message' => 'No book QR ID provided']);
    exit;
}

try {
    $stmt = $dbh->prepare("SELECT 
            td.id as tableId,
            BookId,
            BookName,
            ISBNNumber,
            td.CopyId as CopyId,
            book_no,
            BorrowerId,
            fine,
            RetrunStatus,
            tsd.FullName AS student,
            ts.FullName AS staff,
            BorrowerType,
            IssuesDate,
            DueDate,
            ReturnDate,
            tsd.StudentId,
            ts.StaffId,
            te.approved_due_date,
            (CASE 
                WHEN tsd.StudentId IS NOT NULL AND tsd.StudentId != '' THEN tsd.FullName 
                WHEN ts.StaffId IS NOT NULL AND ts.StaffId != '' THEN ts.FullName 
                ELSE '' 
            END) AS fullname
        FROM tblissuedbookdetails AS td
        INNER JOIN tblbooks AS tb ON tb.id = td.BookId
        LEFT JOIN tblbookcopies AS tbc ON tbc.id = td.CopyId
        LEFT JOIN tblstudents AS tsd ON tsd.StudentId = td.BorrowerID
        LEFT JOIN tblstaff AS ts ON ts.StaffId = td.BorrowerID
        LEFT JOIN tblbook_extensions AS te ON te.issue_id = td.id
        WHERE tbc.book_no = :q AND tbc.book_status = 'issued' 
        AND (td.RetrunStatus = 0 OR td.RetrunStatus IS NULL) AND td.ReturnDate IS NULL
        GROUP BY td.id
    ");
    $stmt->bindValue(':q', $returnBook, PDO::PARAM_STR);
    $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()]);
}
