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

$qrPath = $_POST['bookCode'] ?? '';

if (empty($qrPath)) {
    echo '<tr><td colspan="10" class="text-center text-danger">❌ No QR code provided.</td></tr>';
    exit;
}

// ✅ Step 1: Fetch book copy details using QRCode OR book_no
$sqlCopy = "SELECT id, book_no FROM tblbookcopies 
            WHERE QRCode = :qr OR book_no = :qr";
$queryCopy = $dbh->prepare($sqlCopy);
$queryCopy->bindParam(':qr', $qrPath, PDO::PARAM_STR);
$queryCopy->execute();
$copy = $queryCopy->fetch(PDO::FETCH_OBJ);

if (!$copy) {
    echo '<tr><td colspan="10" class="text-center text-danger">❌ No book copy found for this QR code.</td></tr>';
    exit;
}

// ✅ Step 2: Get issued book details where ReturnDate IS NULL or RetrunStatus = 0
$sql = "SELECT * FROM tblissuedbookdetails 
        WHERE CopyId = :copyId 
        AND (ReturnDate IS NULL OR RetrunStatus = 0)";
$query = $dbh->prepare($sql);
$query->bindParam(':copyId', $copy->id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);

// ✅ Step 3: Display results
if (count($results) > 0) {
    foreach ($results as $row) {
        echo "<tr>
            <td>{$row->id}</td>
            <td>{$row->BorrowerID}</td>
            <td>{$row->BorrowerType}</td>
            <td>{$row->BookId}</td>
            <td>{$row->CopyId}</td>
            <td>{$row->IssuesDate}</td>
            <td>{$row->DueDate}</td>
            <td>" . ($row->ReturnDate ? $row->ReturnDate : '-') . "</td>
            <td>" . ($row->fine ?? 0) . "</td>
            <td>
                <button class='btn btn-success btn-sm return-btn' data-id='{$row->id}'>Return</button>
            </td>
        </tr>";
    }
} else {
    echo '<tr><td colspan="10" class="text-center text-warning">⚠️ No unreturned books found for this QR code.</td></tr>';
}
?>
