<?php // app/Views/qr/manage.php — content fragment
$jsTables = [];
foreach ($tables as $t) {
    if (!empty($restaurant['slug'])) {
        $qrUrl = $baseUrl . '/' . $restaurant['slug'];
    } else {
        $qrUrl = $baseUrl . '/menu';
    }
    $jsTables[] = [
        'id' => $t['id'],
        'name' => $t['name'],
        'table_code' => $t['table_code'] ?? '—',
        'qr_url' => $qrUrl
    ];
}
?>

<div class="space-y-6">

    <?php if (isset($_SESSION['selected_cashier_id_qr'])): ?>
    <!-- Active Cashier Override Banner -->
    <div class="rounded-2xl p-4 flex items-center justify-between gap-4"
         style="background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.25)">
        <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-xl flex items-center justify-center bg-emerald-500/20 text-emerald-400">
                <i class="fas fa-filter"></i>
            </div>
            <div>
                <h4 class="text-sm font-bold text-white">
                    Showing tables for: 
                    <span class="text-emerald-400 font-semibold">
                        <?php 
                        if ($_SESSION['selected_cashier_id_qr'] === 'all') {
                            echo 'All Cashiers / All Tables';
                        } else {
                            echo htmlspecialchars($_SESSION['selected_cashier_name_qr'] ?? 'Selected Cashier');
                        }
                        ?>
                    </span>
                </h4>
                <p class="text-xs text-slate-400">Filtered view based on cashier floor/table assignment.</p>
            </div>
        </div>
        <a href="?cashier_id=change" class="text-xs font-bold text-slate-300 hover:text-white px-3 py-1.5 rounded-lg border border-white/10 hover:bg-white/5 transition flex items-center gap-1.5">
            <i class="fas fa-arrows-rotate"></i> Switch Cashier
        </a>
    </div>
    <?php endif; ?>

    <!-- Info Banner + Actions -->
    <div class="rounded-2xl p-5 flex flex-wrap items-start gap-4"
         style="background:rgba(139,92,246,0.08); border:1px solid rgba(139,92,246,0.2)">
        <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
             style="background:rgba(139,92,246,0.25)">
            <i class="fas fa-qrcode text-purple-400 text-lg"></i>
        </div>
        <div class="flex-1 min-w-0">
            <h3 class="font-semibold text-white mb-1">QR Ordering — How It Works</h3>
            <ol class="text-xs text-slate-400 space-y-0.5 list-decimal list-inside">
                <li>Print and place the QR code on each table.</li>
                <li>Customer scans with phone camera — no app needed.</li>
                <li>They browse the full menu and place their order.</li>
                <li>Order appears instantly in the Cashier POS as <em>pending</em>.</li>
            </ol>
        </div>
        <div class="flex gap-3 flex-shrink-0 flex-wrap">
            <button onclick="printAllCards()"
                    class="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold transition"
                    style="background:rgba(139,92,246,0.2); color:#c4b5fd; border:1px solid rgba(139,92,246,0.3)">
                <i class="fas fa-print"></i> Print All
            </button>
            <button onclick="downloadAllCards()"
                    class="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold transition"
                    style="background:rgba(245,158,11,0.2); color:#fde68a; border:1px solid rgba(245,158,11,0.3)">
                <i class="fas fa-download"></i> Download All
            </button>
        </div>
    </div>

    <!-- QR Cards per Floor -->
    <?php
    $hasAny = false;
    foreach ($floors as $floor):
        $floorTables = array_filter($tables, fn($t) => $t['floor_id'] == $floor['id']);
        if(empty($floorTables)) continue;
        $hasAny = true;
    ?>
    <div class="rounded-2xl overflow-hidden"
         style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">

        <!-- Floor Header -->
        <div class="px-5 py-3 border-b border-white/5 flex items-center justify-between">
            <h3 class="font-semibold text-white flex items-center gap-2">
                <i class="fas fa-layer-group text-emerald-400 text-sm"></i>
                <?php echo htmlspecialchars($floor['name']); ?>
            </h3>
            <span class="text-xs text-slate-500"><?php echo count($floorTables); ?> table<?php echo count($floorTables)!==1?'s':''; ?></span>
        </div>

        <!-- Cards Grid -->
        <div class="p-5 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            <?php foreach ($floorTables as $table):
                if (!empty($restaurant['slug'])) {
                    $qrUrl   = $baseUrl . '/' . $restaurant['slug'];
                    $viewUrl = $baseUrl . '/' . $restaurant['slug'] . '/' . $table['table_code'];
                } else {
                    $qrUrl   = $baseUrl . '/menu';
                    $viewUrl = $baseUrl . '/menu?t=' . $table['qr_code'];
                }
                $occupied = $table['status'] === 'occupied';
                $cardBg   = $occupied ? 'rgba(239,68,68,0.08)'      : 'rgba(255,255,255,0.04)';
                $cardBdr  = $occupied ? 'rgba(239,68,68,0.2)'       : 'rgba(255,255,255,0.08)';
                $badgeBg  = $occupied ? 'rgba(239,68,68,0.15)'      : 'rgba(16,185,129,0.15)';
                $badgeTxt = $occupied ? '#f87171'                   : '#6ee7b7';
            ?>
            <div class="rounded-2xl p-3.5 flex flex-col items-center gap-3"
                 style="background:<?php echo $cardBg; ?>; border:1px solid <?php echo $cardBdr; ?>">

                <!-- QR Display Box -->
                <div class="w-full rounded-xl overflow-hidden flex items-center justify-center p-2"
                     style="background:#ffffff; min-height:130px">
                    <div id="qr-<?php echo $table['id']; ?>"
                         data-url="<?php echo htmlspecialchars($qrUrl, ENT_QUOTES); ?>"
                         class="qr-target">
                    </div>
                </div>

                <!-- Table Info -->
                <div class="text-center w-full">
                    <div class="font-bold text-white text-sm leading-tight">
                        <?php echo htmlspecialchars($table['name']); ?>
                    </div>
                    <div class="text-xs text-slate-500 mt-0.5">
                        <?php echo htmlspecialchars($floor['name']); ?> &middot; <?php echo $table['capacity']; ?> seats
                    </div>
                    <span class="inline-block mt-2 text-xs px-2.5 py-0.5 rounded-full font-medium"
                          style="background:<?php echo $badgeBg; ?>; color:<?php echo $badgeTxt; ?>">
                        <?php echo $occupied ? 'Occupied' : 'Available'; ?>
                    </span>
                </div>

                <!-- Action Buttons -->
                <div class="flex gap-2 w-full">
                    <a href="<?php echo $viewUrl; ?>" target="_blank"
                       class="flex-1 py-1.5 rounded-lg text-xs font-medium text-center transition hover:opacity-80"
                       style="background:rgba(255,255,255,0.06); color:#94a3b8; border:1px solid rgba(255,255,255,0.1)">
                        <i class="fas fa-eye mr-1"></i>View
                    </a>
                    <button onclick="openQRModal(<?php echo htmlspecialchars(json_encode([
                        'id' => $table['id'],
                        'name' => $table['name'],
                        'table_code' => $table['table_code'],
                        'qr_url' => $qrUrl
                    ]), ENT_QUOTES); ?>)"
                            class="flex-1 py-1.5 rounded-lg text-xs font-semibold transition hover:opacity-80 flex items-center justify-center gap-1"
                            style="background:rgba(139,92,246,0.2); color:#c4b5fd; border:1px solid rgba(139,92,246,0.3)">
                        <i class="fas fa-qrcode"></i>Card
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>

    <?php if(!$hasAny): ?>
    <div class="rounded-2xl p-12 text-center"
         style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <i class="fas fa-qrcode text-5xl text-slate-700 mb-4"></i>
        <p class="text-slate-400 font-medium mb-1">No tables found</p>
        <p class="text-slate-600 text-sm mb-4">Add floors and tables first, then come back to manage QR codes.</p>
        <a href="/admin/floors"
           class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold text-white transition"
           style="background:linear-gradient(135deg,#10b981,#059669)">
            <i class="fas fa-layer-group"></i> Go to Floors &amp; Tables
        </a>
    </div>
    <?php endif; ?>
</div>

<!-- Load QRCode.js FIRST, then generate all QRs -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
const allTables = <?php echo json_encode($jsTables); ?>;

document.addEventListener('DOMContentLoaded', function () {
    // Generate QR for every target div
    document.querySelectorAll('.qr-target').forEach(function (el) {
        const url = el.getAttribute('data-url');
        if (!url) return;
        new QRCode(el, {
            text: url,
            width: 120,
            height: 120,
            colorDark: '#1e1b4b',   // dark purple
            colorLight: '#ffffff',  // white background
            correctLevel: QRCode.CorrectLevel.H
        });
    });
});

let currentOpenTable = null;

function openQRModal(table) {
    currentOpenTable = table;
    
    // Set table details in modal
    document.getElementById('modalTableLabel').innerText = table.name;
    document.getElementById('modalTableCode').innerText = table.table_code || '—';

    // Format beautiful URL
    const cleanUrl = table.qr_url.replace(/^https?:\/\//, '');
    const urlParts = cleanUrl.split('/');
    const lastPart = urlParts.pop();
    const basePath = urlParts.join('/') + '/';
    
    document.getElementById('modalMenuLink').innerHTML = 
        `<span style="color:#d4af37; margin-right:3px; font-size:10px;">🔗</span>` +
        `<span style="color: #94a3b8; font-weight: 500;">${basePath}</span>` +
        `<span style="color: #d4af37; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px;">${lastPart}</span>`;

    // Clone QR Code element
    const qrContainer = document.getElementById('qr-' + table.id);
    const modalQrContainer = document.getElementById('modalQrCodeImgContainer');
    modalQrContainer.innerHTML = '';
    
    if (qrContainer) {
        const qrCanvas = qrContainer.querySelector('canvas');
        const qrImg = qrContainer.querySelector('img');
        if (qrCanvas) {
            const tempImg = document.createElement('img');
            tempImg.src = qrCanvas.toDataURL('image/png');
            tempImg.style.width = '110px';
            tempImg.style.height = '110px';
            modalQrContainer.appendChild(tempImg);
        } else if (qrImg) {
            const tempImg = document.createElement('img');
            tempImg.src = qrImg.src;
            tempImg.style.width = '110px';
            tempImg.style.height = '110px';
            modalQrContainer.appendChild(tempImg);
        }
    }

    // Show modal
    document.getElementById('qrCardModal').style.display = 'flex';
}

function closeQRModal() {
    document.getElementById('qrCardModal').style.display = 'none';
    currentOpenTable = null;
}

function printCard() {
    const printableContent = document.getElementById('qrCardPrintable').outerHTML;
    const win = window.open('', '_blank');
    win.document.write(`
        <!DOCTYPE html><html><head><title>Print QR Card</title>
        <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;800;900&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
        <style>
            body { 
                margin: 0; 
                padding: 0; 
                display: flex; 
                justify-content: center; 
                align-items: center; 
                min-height: 100vh; 
                background: #ffffff; 
            }
            .qr-card {
                box-shadow: none !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            @media print {
                body { background: none; }
            }
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        </style></head>
        <body>
            ${printableContent}
            <script>
                window.onload = () => {
                    setTimeout(() => {
                        window.print();
                        window.close();
                    }, 500);
                }
            <\/script>
        </body></html>
    `);
    win.document.close();
}

function downloadCardPNG() {
    if (currentOpenTable) {
        downloadCardPNGForTable(currentOpenTable);
    }
}

function downloadCardPNGForTable(table) {
    const canvas = document.createElement('canvas');
    canvas.width = 800;
    canvas.height = 1730;
    const ctx = canvas.getContext('2d');

    ctx.imageSmoothingEnabled = true;
    ctx.imageSmoothingQuality = 'high';

    // Helper rounded rect
    function drawRoundedRect(c, x, y, w, h, r, fill = false, stroke = true) {
        c.beginPath();
        c.moveTo(x + r, y);
        c.lineTo(x + w - r, y);
        c.quadraticCurveTo(x + w, y, x + w, y + r);
        c.lineTo(x + w, y + h - r);
        c.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
        c.lineTo(x + r, y + h);
        c.quadraticCurveTo(x, y + h, x, y + h - r);
        c.lineTo(x, y + r);
        c.quadraticCurveTo(x, y, x + r, y);
        c.closePath();
        if (fill) c.fill();
        if (stroke) c.stroke();
    }

    // Outer bezel boundary
    ctx.fillStyle = '#090a0f';
    ctx.strokeStyle = '#2d2f39';
    ctx.lineWidth = 20;
    drawRoundedRect(ctx, 10, 10, 780, 1710, 100, true, true);

    ctx.save();
    ctx.beginPath();
    const rx = 25, ry = 25, rw = 750, rh = 1680, rr = 85;
    ctx.moveTo(rx + rr, ry);
    ctx.lineTo(rx + rw - rr, ry);
    ctx.quadraticCurveTo(rx + rw, ry, rx + rw, ry + rr);
    ctx.lineTo(rx + rw, ry + rh - rr);
    ctx.quadraticCurveTo(rx + rw, ry + rh, rx + rw - rr, ry + rh);
    ctx.lineTo(rx + rr, ry + rh);
    ctx.quadraticCurveTo(rx, ry + rh, rx, ry + rh - rr);
    ctx.lineTo(rx, ry + rr);
    ctx.quadraticCurveTo(rx, ry, rx + rr, ry);
    ctx.closePath();
    ctx.clip();

    const scrGrad = ctx.createRadialGradient(400, 865, 100, 400, 865, 800);
    scrGrad.addColorStop(0, '#1c2238');
    scrGrad.addColorStop(1, '#07090c');
    ctx.fillStyle = scrGrad;
    ctx.fillRect(25, 25, 750, 1680);

    // Dynamic Island
    ctx.fillStyle = '#000000';
    ctx.strokeStyle = '#1c1c1e';
    ctx.lineWidth = 3;
    drawRoundedRect(ctx, 290, 45, 220, 52, 26, true, true);

    // Status Time
    ctx.fillStyle = '#a1a1aa';
    ctx.font = 'bold 22px "Inter", sans-serif';
    ctx.textAlign = 'left';
    ctx.fillText('9:41', 75, 80);

    // Status Icons
    ctx.fillStyle = '#a1a1aa';
    ctx.fillRect(660, 68, 4, 12);
    ctx.fillRect(667, 63, 4, 17);
    ctx.fillRect(674, 58, 4, 22);
    ctx.fillRect(681, 53, 4, 27);

    ctx.beginPath();
    ctx.arc(710, 78, 2, 0, Math.PI * 2);
    ctx.fill();
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#a1a1aa';
    ctx.beginPath();
    ctx.arc(710, 78, 7, -Math.PI*0.75, -Math.PI*0.25);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(710, 78, 14, -Math.PI*0.75, -Math.PI*0.25);
    ctx.stroke();

    ctx.font = '24px "Inter", sans-serif';
    ctx.fillText('🔋', 740, 81);

    // Home Indicator
    ctx.fillStyle = 'rgba(255,255,255,0.35)';
    drawRoundedRect(ctx, 280, 1675, 240, 8, 4, true, false);

    const logoUrl = '<?php echo !empty($restaurant['logo']) ? "/" . htmlspecialchars($restaurant['logo']) : ""; ?>';
    const restName = '<?php echo addslashes($restaurant['name'] ?? 'Restaurant'); ?>';
    const restAddress = '<?php echo addslashes($restaurant['address'] ?? ''); ?>';
    const restPhone = '<?php echo addslashes($restaurant['phone'] ?? ''); ?>';

    const logoImg = new Image();

    function drawLogoAndTexts() {
        if (logoUrl) {
            try {
                ctx.save();
                ctx.beginPath();
                ctx.arc(400, 220, 75, 0, Math.PI * 2);
                ctx.clip();
                ctx.drawImage(logoImg, 325, 145, 150, 150);
                ctx.restore();

                ctx.strokeStyle = '#d4af37';
                ctx.lineWidth = 5;
                ctx.beginPath();
                ctx.arc(400, 220, 75, 0, Math.PI * 2);
                ctx.stroke();
            } catch (err) {
                drawFallbackLogo();
            }
        } else {
            drawFallbackLogo();
        }

        function drawFallbackLogo() {
            ctx.fillStyle = 'rgba(212,175,55,0.1)';
            ctx.strokeStyle = '#d4af37';
            ctx.lineWidth = 5;
            ctx.beginPath();
            ctx.arc(400, 220, 75, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();

            ctx.fillStyle = '#d4af37';
            ctx.font = 'bold 64px "Outfit", "Inter", sans-serif';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(restName.charAt(0).toUpperCase(), 400, 220);
            ctx.textBaseline = 'alphabetic';
        }

        ctx.fillStyle = '#d4af37';
        ctx.font = 'bold 44px "Outfit", "Inter", sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText(restName.toUpperCase(), 400, 360);

        // 3. Restaurant Address & Phone (Cleaned and wrapped to avoid overflows)
        ctx.fillStyle = '#8a99ad';
        ctx.font = '500 22px "Inter", sans-serif';
        
        let addr1 = restAddress;
        let addr2 = '';
        if (restAddress.length > 35) {
            let splitIdx = restAddress.lastIndexOf(' ', 35);
            if (splitIdx !== -1) {
                addr1 = restAddress.substring(0, splitIdx);
                addr2 = restAddress.substring(splitIdx + 1);
            }
        }
        
        ctx.fillText(addr1, 400, 415);
        let nextY = 415;
        if (addr2) {
            nextY += 32;
            ctx.fillText(addr2, 400, nextY);
        }
        
        nextY += 35;
        ctx.fillStyle = '#cbd5e1';
        ctx.font = 'bold 22px "Inter", sans-serif';
        ctx.fillText(restPhone, 400, nextY);

        // 4. SCAN TO ORDER Banner
        const yBanner = nextY + 35;
        ctx.fillStyle = 'rgba(212,175,55,0.08)';
        ctx.strokeStyle = 'rgba(212,175,55,0.3)';
        ctx.lineWidth = 3;
        drawRoundedRect(ctx, 220, yBanner, 360, 64, 16, true, true);

        ctx.fillStyle = '#d4af37';
        ctx.font = 'bold 24px "Inter", sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('SCAN TO ORDER', 400, yBanner + 41);

        // 5. QR Code Box
        const yQrBox = yBanner + 95;
        ctx.fillStyle = '#ffffff';
        ctx.strokeStyle = '#d4af37';
        ctx.lineWidth = 6;
        drawRoundedRect(ctx, 230, yQrBox, 340, 340, 40, true, true);

        const qrContainer = document.getElementById('qr-' + table.id);
        if (qrContainer) {
            const qrCanvas = qrContainer.querySelector('canvas');
            const qrImg = qrContainer.querySelector('img');
            if (qrCanvas) {
                ctx.drawImage(qrCanvas, 260, yQrBox + 30, 280, 280);
                drawBottomSection(yQrBox);
            } else if (qrImg) {
                const tempImg = new Image();
                tempImg.onload = function() {
                    ctx.drawImage(tempImg, 260, yQrBox + 30, 280, 280);
                    drawBottomSection(yQrBox);
                };
                tempImg.src = qrImg.src;
            } else {
                drawBottomSection(yQrBox);
            }
        } else {
            drawBottomSection(yQrBox);
        }

        function drawBottomSection(yQrBox) {
            const yTableLabel = yQrBox + 410;
            const yTableCode = yQrBox + 480;
            const yUrlPill = yQrBox + 540;
            
            // Lock footer to the actual bottom of the phone screen mockup
            const yDivider = 1480;
            const yContactYours = 1535;
            const yContactInfo = 1585;

            ctx.fillStyle = '#ffffff';
            ctx.font = 'extrabold 52px "Outfit", "Inter", sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText(table.name.toUpperCase(), 400, yTableLabel);

            // Table Code label & value
            ctx.fillStyle = '#8a99ad';
            ctx.font = 'bold 24px "Inter", sans-serif';
            ctx.textAlign = 'right';
            ctx.fillText('Code: ', 390, yTableCode);

            // Gold pill badge
            ctx.fillStyle = '#d4af37';
            drawRoundedRect(ctx, 405, yTableCode - 32, 160, 44, 22, true, false);

            ctx.fillStyle = '#000000';
            ctx.font = 'black 26px "Inter", sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText(table.table_code || '—', 485, yTableCode);

            // Clean and split URL for styling
            const cleanUrl = table.qr_url.replace(/^https?:\/\//, '');
            const urlParts = cleanUrl.split('/');
            const lastPart = urlParts.pop();
            const basePath = urlParts.join('/') + '/';

            // Measure widths
            ctx.font = '500 22px "Inter", sans-serif';
            const w1 = ctx.measureText(basePath).width;
            ctx.font = 'bold 22px "Inter", sans-serif';
            const w2 = ctx.measureText(lastPart.toUpperCase()).width;
            
            // Total text width + spacing for icon
            const iconSpace = 30; // space for link icon
            const totalW = w1 + w2 + iconSpace;
            const pillW = totalW + 40;
            const pillH = 50;
            const pillX = 400 - (pillW / 2);

            // Draw glassmorphic pill background
            ctx.fillStyle = 'rgba(212, 175, 55, 0.08)';
            ctx.strokeStyle = 'rgba(212, 175, 55, 0.35)';
            ctx.lineWidth = 3;
            drawRoundedRect(ctx, pillX, yUrlPill - 32, pillW, pillH, 25, true, true);

            // Draw link icon
            ctx.fillStyle = '#d4af37';
            ctx.font = 'bold 18px "Inter", sans-serif';
            ctx.textAlign = 'left';
            ctx.fillText('🔗', pillX + 22, yUrlPill - 1);

            // Draw basePath
            ctx.fillStyle = '#94a3b8';
            ctx.font = '500 22px "Inter", sans-serif';
            ctx.fillText(basePath, pillX + 22 + iconSpace, yUrlPill);

            // Draw lastPart
            ctx.fillStyle = '#d4af37';
            ctx.font = 'bold 22px "Inter", sans-serif';
            ctx.fillText(lastPart.toUpperCase(), pillX + 22 + iconSpace + w1, yUrlPill);

            // Dashed Divider line
            ctx.strokeStyle = 'rgba(212,175,55,0.25)';
            ctx.lineWidth = 3;
            ctx.setLineDash([15, 15]);
            ctx.beginPath();
            ctx.moveTo(100, yDivider);
            ctx.lineTo(700, yDivider);
            ctx.stroke();
            ctx.setLineDash([]);

            // Restipo details
            ctx.fillStyle = '#64748b';
            ctx.font = 'bold 18px "Inter", sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText('CONTACT TO MAKE YOURS', 400, yContactYours);

            ctx.fillStyle = '#d4af37';
            ctx.font = 'bold 26px "Inter", sans-serif';
            ctx.fillText('Restipo • phone-01850211813', 400, yContactInfo);

            ctx.restore();

            const link = document.createElement('a');
            link.download = `${table.name.replace(/\s+/g, '_')}_QR_Card.png`;
            link.href = canvas.toDataURL('image/png', 1.0);
            link.click();
        }
    }

    if (logoUrl) {
        logoImg.onload = drawLogoAndTexts;
        logoImg.onerror = drawLogoAndTexts;
        logoImg.src = logoUrl;
    } else {
        drawLogoAndTexts();
    }
}

function printAllCards() {
    let htmlContent = '';
    
    for (let i = 0; i < allTables.length; i++) {
        const table = allTables[i];
        
        const qrContainer = document.getElementById('qr-' + table.id);
        let qrImgSrc = '';
        if (qrContainer) {
            const qrCanvas = qrContainer.querySelector('canvas');
            const qrImg = qrContainer.querySelector('img');
            if (qrCanvas) {
                qrImgSrc = qrCanvas.toDataURL('image/png');
            } else if (qrImg) {
                qrImgSrc = qrImg.src;
            }
        }

        const cleanUrl = table.qr_url.replace(/^https?:\/\//, '');
        const urlParts = cleanUrl.split('/');
        const lastPart = urlParts.pop();
        const basePath = urlParts.join('/') + '/';
        
        htmlContent += `
        <div class="print-card-wrapper">
            <div class="qr-card" style="box-sizing: border-box; background: #090a0f; border: 8px solid #2d2f39; border-radius: 46px; width: 330px; height: 720px; position: relative; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; padding: 16px 14px 18px; font-family: 'Inter', system-ui, sans-serif; box-shadow: none !important;">
                
                <!-- Screen Inner Gradient Container -->
                <div style="position: absolute; inset: 0; background: radial-gradient(circle at center, #1c2238 0%, #07090c 100%); z-index: 1;"></div>
                
                <!-- Home Indicator -->
                <div style="position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%); width: 110px; height: 4px; background: rgba(255, 255, 255, 0.35); border-radius: 2px; z-index: 5;"></div>

                <!-- Content Wrapper -->
                <div style="position: relative; z-index: 2; display: flex; flex-direction: column; justify-content: space-between; height: 100%; width: 100%;">
                    
                    <!-- Status Bar -->
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 10px; height: 24px; color: #a1a1aa; font-size: 10px; font-weight: 700; font-family: system-ui, sans-serif;">
                        <span>9:41</span>
                        <!-- Dynamic Island -->
                        <div style="position: absolute; left: 50%; transform: translateX(-50%); top: 0px; background: #000; width: 85px; height: 22px; border-radius: 11px; border: 1px solid #1c1c1e; z-index: 10;"></div>
                        <div style="display: flex; align-items: center; gap: 4px;">
                            <svg width="11" height="9" viewBox="0 0 10 8" fill="currentColor"><rect x="0" y="6" width="1.5" height="2" rx="0.5"/><rect x="2.5" y="4" width="1.5" height="4" rx="0.5"/><rect x="5" y="2" width="1.5" height="6" rx="0.5"/><rect x="7.5" y="0" width="1.5" height="8" rx="0.5"/></svg>
                            <svg width="11" height="9" viewBox="0 0 12 10" fill="currentColor"><path d="M6 10a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm-3.535-5.035a1 1 0 011.414 0c1.172 1.172 3.07 1.172 4.242 0a1 1 0 011.414 1.414c-1.953 1.953-5.118 1.953-7.07 0a1 1 0 010-1.414zm-2.122-2.122a1 1 0 011.414 0c2.343 2.343 6.142 2.343 8.485 0a1 1 0 111.414 1.414c-3.125 3.125-8.188 3.125-11.313 0a1 1 0 010-1.414z"/></svg>
                            <span style="font-size:11px; line-height:1; margin-left:1px;">🔋</span>
                        </div>
                    </div>

                    <!-- Main Screen Area -->
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; flex: 1; margin: 10px 0;">
                        
                        <!-- Rest Logo (Centered) -->
                        <div style="margin-bottom: 8px; display: flex; justify-content: center;">
                            <?php if(!empty($restaurant['logo'])): ?>
                                <img src="/<?php echo htmlspecialchars($restaurant['logo']); ?>" style="height:64px; width:64px; object-fit:cover; border-radius:50%; border:2px solid #d4af37; display:block; box-shadow: 0 4px 10px rgba(0,0,0,0.5);" />
                            <?php else: ?>
                                <div style="width:64px; height:64px; border-radius:50%; border:2px solid #d4af37; display:flex; align-items:center; justify-content:center; background:rgba(212,175,55,0.1); color:#d4af37; font-weight:800; font-size:26px; box-shadow: 0 4px 10px rgba(0,0,0,0.5);">
                                    <?php echo strtoupper(substr($restaurant['name'] ?? 'R', 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Rest Name -->
                        <h1 style="color:#d4af37; font-size:19px; font-weight:800; margin:0 0 3px; text-transform:uppercase; letter-spacing:1.5px; line-height:1.2; font-family:'Outfit', sans-serif; text-align:center;"><?php echo htmlspecialchars($restaurant['name'] ?? 'Restaurant'); ?></h1>
                        <!-- Address & Phone -->
                        <p style="color:#8a99ad; font-size:10.5px; margin:0 0 12px; font-weight:500; text-align:center;"><?php echo htmlspecialchars($restaurant['address'] ?? ''); ?> &middot; <?php echo htmlspecialchars($restaurant['phone'] ?? ''); ?></p>

                        <!-- SCAN TO ORDER Banner -->
                        <div style="background: rgba(212,175,55,0.08); border: 1px solid rgba(212,175,55,0.3); border-radius: 12px; padding: 6px 20px; margin-bottom: 14px; box-shadow: 0 0 10px rgba(212,175,55,0.1);">
                            <h2 style="color:#d4af37; font-size:10.5px; font-weight:800; margin:0; letter-spacing:1px; text-transform:uppercase;">SCAN TO ORDER</h2>
                        </div>

                        <!-- QR Wrapper -->
                        <div style="background:#ffffff; border-radius:20px; padding:10px; width:135px; height:135px; margin:0 auto 12px; display:flex; align-items:center; justify-content:center; border:3px solid #d4af37; box-shadow: 0 8px 20px rgba(0,0,0,0.5);">
                            <img src="${qrImgSrc}" style="width: 110px; height: 110px; display: block;" />
                        </div>

                        <!-- Table Label (e.g. VIP-01) -->
                        <div style="font-size:22px; font-weight:900; color:white; text-transform:uppercase; margin: 4px 0 6px; letter-spacing:1.5px; text-shadow: 0 2px 4px rgba(0,0,0,0.6); font-family:'Outfit', sans-serif; text-align:center;">${table.name}</div>

                        <!-- Link & Code -->
                        <div style="display: flex; flex-direction: column; align-items: center; gap: 4px; margin-bottom: 10px;">
                            <div>
                                <span style="color:#8a99ad; font-size:10px; font-weight:700;">Code: </span>
                                <span style="color:#000000; font-weight:900; font-size:13px; background: linear-gradient(135deg, #d4af37, #f3e5ab); padding: 2px 10px; border-radius:20px; box-shadow: 0 2px 5px rgba(0,0,0,0.3);">${table.table_code}</span>
                            </div>
                            <!-- Beautifully Designed URL Badge -->
                            <div style="margin-top: 8px; margin-bottom: 4px;">
                                <div style="background: rgba(212, 175, 55, 0.08); border: 1.5px solid rgba(212, 175, 55, 0.35); border-radius: 20px; padding: 6px 18px; display: inline-flex; align-items: center; justify-content: center; max-width: 260px; box-shadow: none; font-size: 11px;">
                                    <span style="word-break: break-all; text-align: center; font-family: 'Inter', sans-serif; display: flex; align-items: center; gap: 6px;">
                                        <span style="color:#d4af37; font-size:10px;">🔗</span>
                                        <span style="color: #94a3b8; font-weight: 500;">${basePath}</span><span style="color: #d4af37; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px;">${lastPart}</span>
                                    </span>
                                </div>
                            </div>
                        </div>

                    </div>

                    <!-- Restipo Footer Branding -->
                    <div style="border-top: 1px dashed rgba(212,175,55,0.25); padding-top: 10px; margin-top: 5px; text-align: center; margin-bottom: 8px;">
                        <span style="color:#64748b; font-size:8px; display:block; font-weight:700; text-transform:uppercase; letter-spacing:1px; margin-bottom:2px;">Contact to make yours</span>
                        <span style="color:#d4af37; font-size:11px; font-weight:800; letter-spacing:0.5px;">Restipo &bull; phone-01850211813</span>
                    </div>

                </div>

            </div>
        </div>
        `;
    }

    const win = window.open('', '_blank');
    win.document.write(`
        <!DOCTYPE html><html><head><title>Print Table QRs</title>
        <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;800;900&family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
        <style>
            body { 
                margin: 0; 
                padding: 0; 
                background: #ffffff; 
            }
            .print-card-wrapper {
                page-break-after: always;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                width: 100vw;
                box-sizing: border-box;
            }
            @media print {
                body { background: none; }
                .print-card-wrapper {
                    page-break-after: always !important;
                }
            }
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        </style></head>
        <body>
            ${htmlContent}
            <script>
                window.onload = () => {
                    setTimeout(() => {
                        window.print();
                        window.close();
                    }, 800);
                }
            <\/script>
        </body></html>
    `);
    win.document.close();
}

async function downloadAllCards() {
    for (let i = 0; i < allTables.length; i++) {
        downloadCardPNGForTable(allTables[i]);
        await new Promise(resolve => setTimeout(resolve, 350));
    }
}
</script>

<!-- QR Card Modal -->
<div id="qrCardModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in" style="display:none; background: rgba(0,0,0,0.85); backdrop-filter: blur(10px);">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;800;900&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <div class="w-full max-w-md rounded-2xl overflow-hidden glass shadow-2xl flex flex-col" style="background: #0f111a; border: 1px solid rgba(212,175,55,0.25); max-height: 90vh;">
        <!-- Header -->
        <div class="px-5 py-4 flex justify-between items-center border-b border-white/5 flex-shrink-0">
            <h3 class="text-base font-bold text-amber-400 flex items-center gap-2">
                <i class="fas fa-qrcode"></i>
                <span>Table QR Card</span>
            </h3>
            <button onclick="closeQRModal()" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <!-- Body / Preview Area -->
        <div class="p-6 flex flex-col items-center justify-start space-y-4 overflow-y-auto flex-1">
            
            <div id="qrCardPrintable" class="qr-card" style="box-sizing: border-box; background: #090a0f; border: 8px solid #2d2f39; border-radius: 46px; width: 330px; height: 720px; position: relative; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; padding: 16px 14px 18px; font-family: 'Inter', system-ui, sans-serif; box-shadow: 0 20px 45px rgba(0,0,0,0.8); -webkit-print-color-adjust: exact; print-color-adjust: exact; margin: 0 auto;">
                
                <!-- Screen Inner Gradient Container -->
                <div style="position: absolute; inset: 0; background: radial-gradient(circle at center, #1c2238 0%, #07090c 100%); z-index: 1;"></div>
                
                <!-- Home Indicator -->
                <div style="position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%); width: 110px; height: 4px; background: rgba(255, 255, 255, 0.35); border-radius: 2px; z-index: 5;"></div>

                <!-- Content Wrapper -->
                <div style="position: relative; z-index: 2; display: flex; flex-direction: column; justify-content: space-between; height: 100%; width: 100%;">
                    
                    <!-- Status Bar -->
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 10px; height: 24px; color: #a1a1aa; font-size: 10px; font-weight: 700; font-family: system-ui, sans-serif;">
                        <span>9:41</span>
                        <!-- Dynamic Island -->
                        <div style="position: absolute; left: 50%; transform: translateX(-50%); top: 0px; background: #000; width: 85px; height: 22px; border-radius: 11px; border: 1px solid #1c1c1e; z-index: 10;"></div>
                        <div style="display: flex; align-items: center; gap: 4px;">
                            <svg width="11" height="9" viewBox="0 0 10 8" fill="currentColor"><rect x="0" y="6" width="1.5" height="2" rx="0.5"/><rect x="2.5" y="4" width="1.5" height="4" rx="0.5"/><rect x="5" y="2" width="1.5" height="6" rx="0.5"/><rect x="7.5" y="0" width="1.5" height="8" rx="0.5"/></svg>
                            <svg width="11" height="9" viewBox="0 0 12 10" fill="currentColor"><path d="M6 10a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm-3.535-5.035a1 1 0 011.414 0c1.172 1.172 3.07 1.172 4.242 0a1 1 0 011.414 1.414c-1.953 1.953-5.118 1.953-7.07 0a1 1 0 010-1.414zm-2.122-2.122a1 1 0 011.414 0c2.343 2.343 6.142 2.343 8.485 0a1 1 0 111.414 1.414c-3.125 3.125-8.188 3.125-11.313 0a1 1 0 010-1.414z"/></svg>
                            <span style="font-size:11px; line-height:1; margin-left:1px;">🔋</span>
                        </div>
                    </div>

                    <!-- Main Screen Area -->
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; flex: 1; margin: 10px 0;">
                        
                        <!-- Rest Logo (Centered) -->
                        <div style="margin-bottom: 8px; display: flex; justify-content: center;">
                            <?php if(!empty($restaurant['logo'])): ?>
                                <img src="/<?php echo htmlspecialchars($restaurant['logo']); ?>" style="height:64px; width:64px; object-fit:cover; border-radius:50%; border:2px solid #d4af37; display:block; box-shadow: 0 4px 10px rgba(0,0,0,0.5);" />
                            <?php else: ?>
                                <div style="width:64px; height:64px; border-radius:50%; border:2px solid #d4af37; display:flex; align-items:center; justify-content:center; background:rgba(212,175,55,0.1); color:#d4af37; font-weight:800; font-size:26px; box-shadow: 0 4px 10px rgba(0,0,0,0.5);">
                                    <?php echo strtoupper(substr($restaurant['name'] ?? 'R', 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Rest Name -->
                        <h1 style="color:#d4af37; font-size:19px; font-weight:800; margin:0 0 3px; text-transform:uppercase; letter-spacing:1.5px; line-height:1.2; font-family:'Outfit', sans-serif; text-align:center;"><?php echo htmlspecialchars($restaurant['name'] ?? 'Restaurant'); ?></h1>
                        <!-- Address & Phone -->
                        <p style="color:#8a99ad; font-size:10.5px; margin:0 0 12px; font-weight:500; text-align:center;"><?php echo htmlspecialchars($restaurant['address'] ?? ''); ?> &middot; <?php echo htmlspecialchars($restaurant['phone'] ?? ''); ?></p>

                        <!-- SCAN TO ORDER Banner -->
                        <div style="background: rgba(212,175,55,0.08); border: 1px solid rgba(212,175,55,0.3); border-radius: 12px; padding: 6px 20px; margin-bottom: 14px; box-shadow: 0 0 10px rgba(212,175,55,0.1);">
                            <h2 style="color:#d4af37; font-size:10.5px; font-weight:800; margin:0; letter-spacing:1px; text-transform:uppercase;">SCAN TO ORDER</h2>
                        </div>

                        <!-- QR Wrapper -->
                        <div id="modalQrCodeImgContainer" style="background:#ffffff; border-radius:20px; padding:10px; width:135px; height:135px; margin:0 auto 12px; display:flex; align-items:center; justify-content:center; border:3px solid #d4af37; box-shadow: 0 8px 20px rgba(0,0,0,0.5);">
                        </div>

                        <!-- Table Label (e.g. VIP-01) -->
                        <div id="modalTableLabel" style="font-size:22px; font-weight:900; color:white; text-transform:uppercase; margin: 4px 0 6px; letter-spacing:1.5px; text-shadow: 0 2px 4px rgba(0,0,0,0.6); font-family:'Outfit', sans-serif; text-align:center;"></div>

                        <!-- Link & Code -->
                        <div style="display: flex; flex-direction: column; align-items: center; gap: 4px; margin-bottom: 10px;">
                            <div>
                                <span style="color:#8a99ad; font-size:10px; font-weight:700;">Code: </span>
                                <span id="modalTableCode" style="color:#000000; font-weight:900; font-size:13px; background: linear-gradient(135deg, #d4af37, #f3e5ab); padding: 2px 10px; border-radius:20px; box-shadow: 0 2px 5px rgba(0,0,0,0.3);"></span>
                            </div>
                            <!-- Beautifully Designed URL Badge -->
                            <div style="margin-top: 8px; margin-bottom: 4px;">
                                <div style="background: rgba(212, 175, 55, 0.08); border: 1.5px solid rgba(212, 175, 55, 0.35); border-radius: 20px; padding: 6px 18px; display: inline-flex; align-items: center; justify-content: center; max-width: 260px; box-shadow: 0 6px 15px rgba(0,0,0,0.4); font-size: 11px;">
                                    <div id="modalMenuLink" style="word-break: break-all; text-align: center; font-family: 'Inter', sans-serif; font-size: 11px; display: flex; align-items: center; gap: 6px;"></div>
                                </div>
                            </div>
                        </div>

                    </div>

                    <!-- Restipo Footer Branding -->
                    <div style="border-top: 1px dashed rgba(212,175,55,0.25); padding-top: 10px; margin-top: 5px; text-align: center; margin-bottom: 8px;">
                        <span style="color:#64748b; font-size:8px; display:block; font-weight:700; text-transform:uppercase; letter-spacing:1px; margin-bottom:2px;">Contact to make yours</span>
                        <span style="color:#d4af37; font-size:11px; font-weight:800; letter-spacing:0.5px;">Restipo &bull; phone-01850211813</span>
                    </div>

                </div>

            </div>
            
        </div>
        <!-- Actions footer -->
        <div class="px-5 py-4 bg-slate-900/50 border-t border-white/5 grid grid-cols-2 gap-3 flex-shrink-0">
            <button onclick="printCard()" class="py-2 rounded-xl text-xs font-bold text-white bg-slate-800 border border-white/10 hover:bg-slate-700 transition flex items-center justify-center gap-1.5">
                <i class="fas fa-print"></i> Print Card
            </button>
            <button onclick="downloadCardPNG()" class="py-2 rounded-xl text-xs font-bold text-white bg-gradient-to-r from-amber-600 to-amber-500 hover:from-amber-500 hover:to-amber-400 transition flex items-center justify-center gap-1.5 shadow-lg">
                <i class="fas fa-download"></i> Download PNG
            </button>
        </div>
    </div>
</div> </div>
</div>
