<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kartu QR Siswa — MTs Zumratul Muttaqin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;700;800&display=swap" rel="stylesheet">

    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: #f1f5f9;
            padding: 28px 20px 60px;
            min-height: 100vh;
        }

        /* ── Toolbar ── */
        .toolbar {
            max-width: 960px;
            margin: 0 auto 22px;
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 14px;
            padding: 14px 18px;
        }
        .toolbar-top {
            display: flex; align-items: center;
            justify-content: space-between;
            gap: 12px; flex-wrap: wrap; margin-bottom: 12px;
        }
        .toolbar-left { display: flex; align-items: center; gap: 10px; }
        .toolbar-title { font-size: 14px; font-weight: 700; color: #0f172a; }
        .toolbar-sub   { font-size: 11px; color: #94a3b8; margin-top: 2px; }

        .btn-t {
            display: inline-flex; align-items: center; justify-content: center; gap: 6px;
            padding: 8px 16px; border-radius: 9px;
            font-size: 13px; font-weight: 700; cursor: pointer; border: none;
            transition: all .15s; text-decoration: none; white-space: nowrap;
        }
        .btn-back  { background: #f8fafc; color: #1e293b; border: 1px solid #e2e8f0; }
        .btn-back:hover  { background: #f1f5f9; }
        .btn-print { background: #0f172a; color: #fff; }
        .btn-print:hover { background: #1e293b; }
        .btn-pdf   { background: #dc2626; color: #fff; }
        .btn-pdf:hover   { background: #b91c1c; }
        .btn-apply { background: #312e81; color: #fff; }
        .btn-apply:hover { background: #3730a3; }
        .btn-reset { background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; font-size: 12px; padding: 7px 13px; }
        .btn-reset:hover { background: #f1f5f9; }

        .spinner-sm {
            display: inline-block; width: 13px; height: 13px;
            border: 2px solid #fff; border-top-color: transparent;
            border-radius: 50%; animation: spin .6s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* ── Filter ── */
        .filter-bar {
            border-top: 1px solid #f1f5f9; padding-top: 12px;
            display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
        }
        .filter-bar label { font-size: 12px; font-weight: 700; color: #64748b; white-space: nowrap; }
        .filter-input { display: flex; align-items: center; gap: 8px; }
        .filter-input input[type="number"] {
            width: 62px; padding: 7px 10px;
            border: 1px solid #e2e8f0; border-radius: 8px;
            font-size: 13px; font-weight: 700; color: #0f172a;
            text-align: center; outline: none; transition: border-color .15s;
        }
        .filter-input input[type="number"]:focus { border-color: #312e81; }
        .filter-sep { font-size: 13px; color: #94a3b8; font-weight: 600; }
        .filter-info { font-size: 12px; color: #94a3b8; margin-left: auto; }

        .quick-ranges { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
        .quick-label  { font-size: 11px; font-weight: 700; color: #94a3b8; white-space: nowrap; }
        .pill {
            padding: 4px 11px; border-radius: 20px;
            font-size: 11px; font-weight: 700; cursor: pointer;
            border: 1px solid #e2e8f0; background: #f8fafc; color: #475569;
            transition: .15s;
        }
        .pill:hover, .pill.active { background: #312e81; color: #fff; border-color: #312e81; }

        /* ── Screen grid ── */
        .print-grid {
            display: flex; flex-wrap: wrap;
            gap: 18px; justify-content: center;
            max-width: 960px; margin: 0 auto;
        }
        .card-wrap { display: flex; flex-direction: column; align-items: center; gap: 7px; }
        .card-wrap.hidden { display: none; }

        /* ── ID Card ── */
        .id-card {
            width: 58mm; height: 58mm;
            background: #fff;
            border: 0.8px solid #cbd5e1;
            border-radius: 5mm;
            display: flex; flex-direction: column;
            align-items: center; justify-content: space-between;
            padding: 3.5mm 4mm 3mm;
            position: relative; overflow: hidden;
            box-shadow: 0 2px 12px rgba(0,0,0,.07);
        }
        .id-card::before {
            content: '';
            position: absolute; top: 0; left: 0; right: 0;
            height: 2.2mm; background: #312e81;
            border-radius: 5mm 5mm 0 0;
        }
        .absen-badge {
            position: absolute; top: 3.5mm; left: 2.5mm;
            font-size: 5pt; font-weight: 800; color: #fff;
            background: #312e81; border-radius: 2px;
            padding: 0 3px; line-height: 1.7;
        }
        .card-school {
            font-size: 5.5pt; font-weight: 800; color: #312e81;
            text-transform: uppercase; text-align: center;
            letter-spacing: .4px; width: 100%; padding-top: 1.5mm;
        }
        .card-qr {
            display: flex; align-items: center; justify-content: center;
            flex: 1; padding: 1mm 0;
        }
        .card-qr svg, .card-qr img {
            display: block;
            width: 33mm !important; height: 33mm !important;
            max-width: 33mm; max-height: 33mm;
            shape-rendering: crispEdges; image-rendering: pixelated;
        }
        .card-footer-area { width: 100%; text-align: center; }
        .card-name {
            font-size: 7pt; font-weight: 800; color: #0f172a;
            text-transform: uppercase; letter-spacing: .3px;
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
            width: 100%; display: block;
        }
        .card-kelas { font-size: 5.5pt; color: #64748b; font-weight: 600; margin-top: .5mm; display: block; }

        .card-actions { display: flex; gap: 5px; width: 58mm; }
        .btn-dl {
            background: #fff; border: 1px solid #e2e8f0;
            padding: 5px 11px; border-radius: 6px; flex: 1;
            font-size: 11px; font-weight: 700; cursor: pointer; color: #475569;
            display: flex; align-items: center; justify-content: center; gap: 5px; transition: .15s;
        }
        .btn-dl:hover { background: #f8fafc; }

        .empty-filter {
            display: none; text-align: center; padding: 60px 20px;
            color: #94a3b8; font-size: 13px; font-weight: 600;
            max-width: 960px; margin: 0 auto;
        }

        /* ── Mobile Styles ── */
        @media (max-width: 600px) {
            body { padding: 16px 12px 60px; }
            .toolbar { padding: 12px 14px; border-radius: 12px; }
            .toolbar-top { flex-direction: column; align-items: flex-start; gap: 10px; }
            .toolbar-top > div:last-child { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; width: 100%; }
            #btnPdf { grid-column: 1 / -1; }
            .filter-bar { flex-direction: column; align-items: flex-start; gap: 8px; }
            .filter-input { width: 100%; }
            .filter-input input[type="number"] { width: 72px; }
            .filter-info { margin-left: 0; font-size: 11px; }
            .quick-ranges { width: 100%; }
            /* Memaksa ukuran grid agar muat bersebelahan jika cukup, jika tidak akan rata tengah */
            .print-grid { gap: 12px; }
        }

        /* ── PRINT STYLES ── */
        @media print {
            @page { size: A4 portrait; margin: 10mm 8mm; }
            body { background: #fff !important; padding: 0; }
            .toolbar, .btn-dl, .card-actions { display: none !important; }
            .card-wrap.hidden { display: none !important; }
            .empty-filter { display: none !important; }
            .print-grid {
                display: grid; grid-template-columns: repeat(3, 58mm);
                gap: 5mm 8mm; justify-content: center;
                max-width: none; width: 100%;
            }
            .card-wrap { break-inside: avoid !important; }
            .id-card { box-shadow: none !important; border: 0.5px solid #000 !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        }
    </style>
</head>
<body>

    <div class="toolbar">
        <div class="toolbar-top">
            <div class="toolbar-left">
                <button onclick="tutupHalaman()" class="btn-t btn-back">
                    <i class="bi bi-arrow-left"></i> Kembali
                </button>
                <div>
                    <div class="toolbar-title">Kartu QR Siswa</div>
                    <div class="toolbar-sub" id="info-total">
                        MTs KH Zumratul Muttaqin &mdash; <?php echo e(count($siswas)); ?> kartu
                    </div>
                </div>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <button class="btn-t btn-reset" onclick="resetFilter()">
                    <i class="bi bi-x-circle"></i> Reset
                </button>
                <button onclick="window.print()" class="btn-t btn-print">
                    <i class="bi bi-printer-fill"></i> Cetak A4
                </button>
                <button id="btnPdf" class="btn-t btn-pdf" onclick="downloadPDF()">
                    <i class="bi bi-file-earmark-pdf-fill" id="iconPdf"></i>
                    <span id="labelPdf">Download PDF</span>
                </button>
            </div>
        </div>

        <div class="filter-bar">
            <label><i class="bi bi-funnel-fill" style="margin-right:4px;"></i>Tampilkan absen:</label>
            <div class="filter-input">
                <input type="number" id="from" min="1" max="<?php echo e(count($siswas)); ?>" value="1">
                <span class="filter-sep">—</span>
                <input type="number" id="to" min="1" max="<?php echo e(count($siswas)); ?>" value="<?php echo e(count($siswas)); ?>">
                <button class="btn-t btn-apply" onclick="applyFilter()" style="padding:7px 14px;font-size:12px;">
                    <i class="bi bi-check2"></i> Terapkan
                </button>
            </div>

            <div class="quick-ranges">
                <span class="quick-label">Cepat:</span>
                <?php
                    $total = count($siswas);
                    $chunk = 10;
                ?>
                <?php for($i = 1; $i <= $total; $i += $chunk): ?>
                    <?php $end = min($i + $chunk - 1, $total); ?>
                    <button class="pill" onclick="quickRange(<?php echo e($i); ?>, <?php echo e($end); ?>, this)">
                        <?php echo e($i); ?>–<?php echo e($end); ?>

                    </button>
                <?php endfor; ?>
                <button class="pill active" onclick="quickRange(1, <?php echo e($total); ?>, this)">Semua</button>
            </div>

            <span class="filter-info" id="filter-info">Menampilkan semua <?php echo e($total); ?> kartu</span>
        </div>
    </div>

    <div class="empty-filter" id="empty-msg">
        <i class="bi bi-search"></i>
        Tidak ada kartu dalam rentang tersebut.
    </div>

    <div class="print-grid" id="print-grid">
        <?php $__currentLoopData = $siswas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $siswa): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <div class="card-wrap" data-absen="<?php echo e($loop->iteration); ?>">
            <div class="id-card" id="card-<?php echo e($index); ?>">
                <span class="absen-badge"><?php echo e($loop->iteration); ?></span>
                <div class="card-school">MTs KH Zumratul Muttaqin</div>
                <div class="card-qr">
                    <?php echo QrCode::size(256)->margin(1)->errorCorrection('H')->style('square')->generate($siswa->qr_code); ?>

                </div>
                <div class="card-footer-area">
                    <span class="card-name"><?php echo e($siswa->nama); ?></span>
                    <span class="card-kelas">Kelas <?php echo e($siswa->kelas); ?></span>
                </div>
            </div>

            <div class="card-actions">
                <button class="btn-dl" onclick="downloadCardPng('card-<?php echo e($index); ?>', '<?php echo e(Str::slug($siswa->nama)); ?>')">
                    <i class="bi bi-image"></i> PNG
                </button>
            </div>
        </div>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>

    <script>
        const totalCards = <?php echo e(count($siswas)); ?>;

        function tutupHalaman() {
            if (window.opener || window.history.length <= 1) {
                window.close();
            } else {
                window.history.back();
            }
        }

        /* ── Filter ── */
        function applyFilter() {
            const f = Math.max(1, Math.min(parseInt(document.getElementById('from').value) || 1, totalCards));
            const t = Math.max(f, Math.min(parseInt(document.getElementById('to').value) || totalCards, totalCards));

            document.getElementById('from').value = f;
            document.getElementById('to').value   = t;

            let visible = 0;
            document.querySelectorAll('.card-wrap').forEach(el => {
                const n    = parseInt(el.dataset.absen);
                const show = n >= f && n <= t;
                el.classList.toggle('hidden', !show);
                if (show) visible++;
            });

            const info  = document.getElementById('filter-info');
            const empty = document.getElementById('empty-msg');
            const grid  = document.getElementById('print-grid');

            if (visible === 0) {
                info.textContent    = 'Tidak ada kartu ditampilkan';
                empty.style.display = 'block';
                grid.style.display  = 'none';
            } else {
                info.textContent    = `Menampilkan ${visible} kartu (absen ${f}–${t})`;
                empty.style.display = 'none';
                grid.style.display  = 'flex';
            }

            document.querySelectorAll('.pill').forEach(p => p.classList.remove('active'));
        }

        function quickRange(from, to, btn) {
            document.getElementById('from').value = from;
            document.getElementById('to').value   = to;
            applyFilter();
            document.querySelectorAll('.pill').forEach(p => p.classList.remove('active'));
            btn.classList.add('active');
        }

        function resetFilter() {
            document.getElementById('from').value = 1;
            document.getElementById('to').value   = totalCards;
            applyFilter();
            const pills = document.querySelectorAll('.pill');
            pills[pills.length - 1].classList.add('active');
        }

        /* ── Download PNG per kartu ── */
        function downloadCardPng(id, name) {
            const card = document.getElementById(id);
            const btn  = card.closest('.card-wrap').querySelector('.btn-dl');
            const orig = btn.innerHTML;

            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Proses...';
            btn.disabled  = true;

            html2canvas(card, {
                scale: 6, /* Disamakan skalanya */
                useCORS: true,
                backgroundColor: '#ffffff',
                logging: false,
                imageTimeout: 0,
            }).then(canvas => {
                const a = document.createElement('a');
                a.download = `QR-${name}.png`;
                a.href = canvas.toDataURL('image/png', 1.0);
                a.click();
                btn.innerHTML = '<i class="bi bi-check-circle-fill" style="color:#10b981"></i> Tersimpan';
                setTimeout(() => { btn.innerHTML = orig; btn.disabled = false; }, 2000);
            });
        }

        /* ── Download PDF (semua kartu yang terlihat) ── */
        async function downloadPDF() {
            const btn   = document.getElementById('btnPdf');
            const icon  = document.getElementById('iconPdf');
            const label = document.getElementById('labelPdf');

            btn.disabled   = true;
            icon.className = '';
            icon.innerHTML = '<span class="spinner-sm"></span>';
            label.textContent = 'Memproses...';

            try {
                const { jsPDF } = window.jspdf;
                const pdf     = new jsPDF('portrait', 'mm', 'a4');
                const pageW   = pdf.internal.pageSize.getWidth();
                const pageH   = pdf.internal.pageSize.getHeight();
                const cols    = 3;
                const marginX = 8;
                const marginY = 10;
                const gapX    = 6;
                const gapY    = 5;
                const cardW   = (pageW - (marginX * 2) - (gapX * (cols - 1))) / cols;
                const cardH   = cardW; 

                const cards = [...document.querySelectorAll('.card-wrap:not(.hidden) .id-card')];
                if (cards.length === 0) {
                    alert('Tidak ada kartu yang ditampilkan.');
                    return;
                }

                let col = 0; let row = 0;

                for (let i = 0; i < cards.length; i++) {
                    const card = cards[i];
                    const canvas = await html2canvas(card, {
                        scale: 6,
                        useCORS: true,
                        backgroundColor: '#ffffff',
                        logging: false,
                        imageTimeout: 0,
                    });

                    const imgData = canvas.toDataURL('image/png', 1.0);
                    const x = marginX + col * (cardW + gapX);
                    const y = marginY + row * (cardH + gapY);
                    const maxRows = Math.floor((pageH - marginY * 2) / (cardH + gapY));

                    if (row >= maxRows) {
                        pdf.addPage();
                        row = 0; col = 0;
                        const xNew = marginX + col * (cardW + gapX);
                        const yNew = marginY + row * (cardH + gapY);
                        pdf.addImage(imgData, 'PNG', xNew, yNew, cardW, cardH,'', 'FAST');
                    } else {
                        pdf.addImage(imgData, 'PNG', x, y, cardW, cardH, '', 'FAST');
                    }

                    col++;
                    if (col >= cols) { col = 0; row++; }
                }

                const tgl = new Date().toISOString().slice(0, 10);
                pdf.save(`QR-Siswa-MTs-${tgl}.pdf`);

            } catch (e) {
                console.error(e);
                alert('Gagal membuat PDF. Coba lagi.');
            } finally {
                btn.disabled      = false;
                icon.className    = 'bi bi-file-earmark-pdf-fill';
                icon.innerHTML    = '';
                label.textContent = 'Download PDF';
            }
        }

        applyFilter();
        const pills = document.querySelectorAll('.pill');
        pills[pills.length - 1].classList.add('active');
    </script>

</body>
</html><?php /**PATH C:\laragon\www\absensi_muttaqin_v2\resources\views/siswa/siswa_cetak.blade.php ENDPATH**/ ?>