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

$copyId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$row = isset($_GET['row']) ? (int) $_GET['row'] : 1;  // 1–8
$col = isset($_GET['col']) ? (int) $_GET['col'] : 1;  // 1–3

if ($copyId <= 0 || $row < 1 || $row > 8 || $col < 1 || $col > 3) {
    die('Invalid input');
}

// Fetch QR code and book details
$sql = "SELECT c.book_no, c.QRCode, b.BookName, b.ISBNNumber ,c.accession_no
        FROM tblbookcopies c 
        JOIN tblbooks b ON b.id = c.book_id 
        WHERE c.id = :id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':id', $copyId, PDO::PARAM_INT);
$stmt->execute();
$copy = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$copy) {
    die('Copy not found');
}
?>
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Print QR - <?= htmlentities($copy['book_no']) ?></title>
    <style>
        @page {
            size: A4;
            margin: 8mm;
        }

        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }

        .sheet {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(8, 1fr);
            column-gap: 12px;
            row-gap: 10px;
            height: 100vh;
            padding: 10px;
            box-sizing: border-box;
        }

        .label {
            border: 1px dashed #ccc;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px;
            font-size: 15px;
        }

        .label-text {
            text-align: left;
            max-width: 55%;
        }

        .label img {
            width: 90px;
            height: 90px;
        }

        .label strong {
            display: block;
        }
    </style>
</head>

<body onload="window.print()">

    <div class="sheet">
        <?php
        // Loop through 8 rows × 3 cols = 24 slots
        for ($r = 1; $r <= 8; $r++) {
            for ($c = 1; $c <= 3; $c++) {
                echo '<div>';
                if ($r == $row && $c == $col) { ?>
                    <div class="label">
                        <div class="label-text">
                            <strong>ACC No:</strong> <?= htmlentities($copy['accession_no'] ?? '') ?><br>
                            <strong>Book No:</strong> <?= htmlentities($copy['book_no']) ?>
                        </div>
                        <?php if (!empty($copy['QRCode'])): ?>
                            <img src="../<?= htmlentities($copy['QRCode']) ?>" alt="QR Code">
                        <?php else: ?>
                            <span>No QR</span>
                        <?php endif; ?>
                    </div>
                <?php }
                echo '</div>';
            }
        }
        ?>
    </div>

</body>

</html>