<?php
$pageTitle = 'Bulk Print Cards';
require_once __DIR__ . '/includes/header.php';
$storeName = getSetting('store_name', 'Rewards');
?>

<style>
#tblCards th, #tblCards td { vertical-align: middle; }
#tblCards tr.selected td   { background: #eff6ff; }
.status-badge { font-size: .72rem; }
#selectionBar {
    position: sticky; bottom: 0;
    background: #1e293b; color: #fff;
    padding: .85rem 1.25rem;
    display: flex; align-items: center; gap: 1rem;
    box-shadow: 0 -4px 20px rgba(0,0,0,.2);
    z-index: 50;
}
</style>

<!-- Header & filters -->
<div class="d-flex align-items-center gap-3 flex-wrap mb-3">
    <h4 class="mb-0">
        <i class="bi bi-printer me-2 text-primary"></i>Bulk Print Cards
    </h4>
    <span class="badge bg-light text-dark border fs-6" id="totalCount">Loading…</span>
    <div class="ms-auto d-flex gap-2 flex-wrap">
        <button class="btn btn-outline-secondary btn-sm" id="btnSelectAll">
            <i class="bi bi-check2-all me-1"></i>Select All
        </button>
        <button class="btn btn-outline-secondary btn-sm" id="btnSelectUnreg">
            <i class="bi bi-person-x me-1"></i>Unregistered Only
        </button>
        <button class="btn btn-outline-secondary btn-sm" id="btnClearSel">
            <i class="bi bi-x-lg me-1"></i>Clear
        </button>
    </div>
</div>

<div class="alert alert-info d-flex gap-2 align-items-start py-2 mb-3">
    <i class="bi bi-info-circle-fill mt-1 flex-shrink-0"></i>
    <span>
        <strong>8 cards per A4 page</strong> — 2 columns × 4 rows (CR80 85.6 × 54 mm).
        Tick the cards you want, then click <strong>Print Selected</strong>.
        A new window will open ready to print.
    </span>
</div>

<!-- Card list table -->
<div class="card shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0" id="tblCards">
            <thead class="table-light">
                <tr>
                    <th style="width:40px">
                        <input type="checkbox" id="chkAll" class="form-check-input">
                    </th>
                    <th>#</th>
                    <th>Card Code</th>
                    <th>Member Name</th>
                    <th>Status</th>
                    <th>Created</th>
                </tr>
            </thead>
            <tbody id="cardListBody">
                <tr>
                    <td colspan="6" class="text-center text-muted py-4">
                        <span class="spinner-border spinner-border-sm me-2"></span>Loading…
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- Sticky print bar -->
<div id="selectionBar" style="display:none">
    <i class="bi bi-check2-square fs-5"></i>
    <span id="selCount" class="fw-bold">0 selected</span>
    <span class="text-white-50 small" id="pageCount"></span>
    <button class="btn btn-primary ms-auto px-4" id="btnPrint">
        <i class="bi bi-printer me-2"></i>Print Selected
    </button>
</div>

<?php
$jsBase  = json_encode(BASE_URL);
$jsStore = json_encode($storeName);
$extraJS = '<script>var BASE_URL=' . $jsBase . ';var STORE=' . $jsStore . ';</script>' . <<<'ENDJS'
<script>
var allCards    = [];
var selected    = {};
var CARD_DESIGN = null;

/* ── Boot: load design then cards ──────────────────── */
$.getJSON(BASE_URL + '/ajax/get_card_design.php', function(res) {
    if (res.success) { CARD_DESIGN = res.design; STORE = res.design.store_name || STORE; }
    loadAllCards();
});

function loadAllCards() {
    $.getJSON(BASE_URL + '/ajax/get_all_cards.php', function(res) {
        var tbody = document.getElementById('cardListBody');
        if (!res.success || !res.cards.length) {
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-4">' +
                'No saved cards found. Generate and save cards first.</td></tr>';
            return;
        }
        allCards = res.cards;
        document.getElementById('totalCount').textContent = res.cards.length + ' cards total';

        var rows = '';
        res.cards.forEach(function(c, i) {
            var isReg  = !!c.name;
            var badge  = isReg
                ? '<span class="badge bg-success status-badge">Registered</span>'
                : '<span class="badge bg-secondary status-badge">Unregistered</span>';
            var date   = c.created_at ? c.created_at.substring(0, 10) : '—';
            rows += '<tr data-code="' + c.card_code + '">' +
                '<td><input type="checkbox" class="form-check-input row-chk" data-code="' + c.card_code + '"></td>' +
                '<td class="text-muted small">' + (i + 1) + '</td>' +
                '<td><code class="small">' + c.card_code + '</code></td>' +
                '<td>' + (c.name ? '<span>' + c.name + '</span>' : '<span class="text-muted fst-italic">—</span>') + '</td>' +
                '<td>' + badge + '</td>' +
                '<td class="text-muted small">' + date + '</td>' +
                '</tr>';
        });
        tbody.innerHTML = rows;

        // Row click toggles checkbox
        tbody.querySelectorAll('tr').forEach(function(row) {
            row.addEventListener('click', function(e) {
                if (e.target.type === 'checkbox') return;
                var chk = row.querySelector('.row-chk');
                if (chk) { chk.checked = !chk.checked; handleChk(chk); }
            });
        });
        tbody.querySelectorAll('.row-chk').forEach(function(chk) {
            chk.addEventListener('change', function() { handleChk(chk); });
        });
    }).fail(function() {
        document.getElementById('cardListBody').innerHTML =
            '<tr><td colspan="6" class="text-danger text-center py-3">Failed to load. Please refresh.</td></tr>';
    });
}

function handleChk(chk) {
    var code = chk.dataset.code;
    var row  = chk.closest('tr');
    if (chk.checked) { selected[code] = true;  row.classList.add('selected'); }
    else             { delete selected[code];   row.classList.remove('selected'); }
    updateBar();
}

function updateBar() {
    var count = Object.keys(selected).length;
    var bar   = document.getElementById('selectionBar');
    bar.style.display = count > 0 ? 'flex' : 'none';
    document.getElementById('selCount').textContent = count + ' selected';
    var pages = Math.ceil(count / 8);
    document.getElementById('pageCount').textContent =
        '→ ' + pages + ' A4 page' + (pages !== 1 ? 's' : '');

    // Sync header checkbox
    var total = allCards.length;
    var hdr   = document.getElementById('chkAll');
    hdr.indeterminate = count > 0 && count < total;
    hdr.checked       = count === total && total > 0;
}

/* Select All header checkbox */
document.getElementById('chkAll').addEventListener('change', function() {
    var on = this.checked;
    document.querySelectorAll('.row-chk').forEach(function(chk) {
        chk.checked = on;
        var code = chk.dataset.code;
        var row  = chk.closest('tr');
        if (on) { selected[code] = true;  row.classList.add('selected'); }
        else    { delete selected[code];   row.classList.remove('selected'); }
    });
    updateBar();
});

document.getElementById('btnSelectAll').addEventListener('click', function() {
    document.querySelectorAll('.row-chk').forEach(function(chk) {
        chk.checked = true; selected[chk.dataset.code] = true;
        chk.closest('tr').classList.add('selected');
    });
    updateBar();
});

document.getElementById('btnSelectUnreg').addEventListener('click', function() {
    selected = {};
    document.querySelectorAll('.row-chk').forEach(function(chk) {
        chk.checked = false;
        chk.closest('tr').classList.remove('selected');
    });
    allCards.forEach(function(c) {
        if (!c.name) {
            selected[c.card_code] = true;
            var row = document.querySelector('tr[data-code="' + c.card_code + '"]');
            var chk = row && row.querySelector('.row-chk');
            if (chk) { chk.checked = true; row.classList.add('selected'); }
        }
    });
    updateBar();
});

document.getElementById('btnClearSel').addEventListener('click', function() {
    selected = {};
    document.querySelectorAll('.row-chk').forEach(function(chk) {
        chk.checked = false;
        chk.closest('tr').classList.remove('selected');
    });
    updateBar();
});

/* ── Build card bg style ───────────────────────────── */
function buildBgStyle() {
    var d = CARD_DESIGN;
    if (!d) return 'background:linear-gradient(135deg,#1e3a8a 0%,#1d4ed8 45%,#0ea5e9 100%);';
    if (d.bg_type === 'image' && d.bg_image)
        return 'background:url(' + d.bg_image + ') center/cover no-repeat;';
    return 'background:linear-gradient(' + (d.gradient_dir||'135deg') + ',' +
        (d.color1||'#1e3a8a') + ' 0%,' + (d.color2||'#1d4ed8') + ' 45%,' +
        (d.color3||'#0ea5e9') + ' 100%);';
}

/* ── Build card HTML ───────────────────────────────── */
function buildCardHTML(code, scope) {
    var d  = CARD_DESIGN || {};
    var tc = d.text_color    || '#ffffff';
    var ac = d.accent_color  || '#facc15';
    var ic = d.logo_icon     || 'star-fill';
    var sn = (d.store_name   || STORE || 'Rewards').toUpperCase();
    var lb = d.label_text    || 'MEMBER CARD';
    var sb = d.subtitle_text || 'REWARDS MEMBER';
    var bg = buildBgStyle();

    return '<div class="reward-card" style="' + bg + '--card-text:' + tc + ';--card-accent:' + ac + ';">' +
        '<div class="card-circle-deco"></div>' +
        '<div class="card-top">' +
          '<div class="card-top-qr" id="tqr-' + scope + '"></div>' +
          '<div class="card-store-name" style="color:' + tc + ';opacity:.85">' + sn + '</div>' +
          '<i class="bi bi-' + ic + '" style="color:' + ac + ';font-size:1rem;flex:0 0 auto"></i>' +
        '</div>' +
        '<div class="card-stripe"><svg id="bc-' + scope + '"></svg></div>' +
        '<div class="card-bottom">' +
          '<div class="card-info">' +
            '<div class="card-label" style="color:' + tc + ';opacity:.6">' + lb + '</div>' +
            '<div class="card-number" style="color:' + tc + '">' + code + '</div>' +
            '<div class="card-validity" style="color:' + tc + ';opacity:.6">' + sb + '</div>' +
          '</div>' +
          '<div id="qr-' + scope + '" class="card-qr-wrap"></div>' +
        '</div>' +
      '</div>';
}

/* ── Print in new window ───────────────────────────── */
document.getElementById('btnPrint').addEventListener('click', function() {
    var codes = Object.keys(selected);
    if (!codes.length) return;

    // Build pages HTML
    var pagesHTML = '';
    for (var p = 0; p < codes.length; p += 8) {
        var batch = codes.slice(p, p + 8);
        pagesHTML += '<div class="print-page">';
        batch.forEach(function(code, idx) {
            pagesHTML += '<div class="print-card-wrap">' + buildCardHTML(code, 'p' + p + 'i' + idx) + '</div>';
        });
        pagesHTML += '</div>';
    }

    // Card design data to pass into new window
    var designJSON = JSON.stringify(CARD_DESIGN);
    var codesJSON  = JSON.stringify(codes);

    var html = '<!DOCTYPE html><html><head><meta charset="UTF-8">' +
        '<title>Print Cards</title>' +
        '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.css">' +
        '<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"><\/script>' +
        '<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"><\/script>' +
        '<style>' +
        '* { margin:0; padding:0; box-sizing:border-box; -webkit-print-color-adjust:exact !important; print-color-adjust:exact !important; }' +
        'body { background:#fff; }' +
        '.print-page {' +
            'width:210mm; height:297mm;' +
            'padding:10mm 17.9mm;' +
            'display:grid;' +
            'grid-template-columns:85.6mm 85.6mm;' +
            'grid-template-rows:repeat(4,54mm);' +
            'gap:3mm;' +
            'break-after:page; page-break-after:always;' +
        '}' +
        '.print-page:last-child { break-after:auto; page-break-after:auto; }' +
        '.print-card-wrap { width:85.6mm; height:54mm; overflow:hidden; border-radius:3mm; }' +
        '.reward-card { width:85.6mm; height:54mm; border-radius:3mm; position:relative; overflow:hidden; display:flex; flex-direction:column; font-family:Segoe UI,sans-serif; color:var(--card-text,#fff); }' +
        '.card-circle-deco { position:absolute; top:-30%; right:-15%; width:70%; padding-bottom:70%; border-radius:50%; background:rgba(255,255,255,.06); pointer-events:none; }' +
        '.card-top { display:flex; align-items:center; padding:7px 10px 4px; gap:6px; flex:0 0 auto; }' +
        '.card-top-qr { width:13mm; height:13mm; flex-shrink:0; border-radius:2px; overflow:hidden; }' +
        '.card-top-qr img, .card-top-qr canvas { width:13mm !important; height:13mm !important; display:block; border-radius:2px; }' +
        '.card-store-name { flex:1; font-size:.5rem; font-weight:700; letter-spacing:.12em; text-transform:uppercase; }' +
        '.card-stripe { background:rgba(0,0,0,.35); padding:3px 0; flex:0 0 auto; }' +
        '.card-stripe svg { width:100%; height:10mm; display:block; }' +
        '.card-bottom { display:flex; align-items:flex-end; padding:4px 10px 7px; gap:6px; flex:1; }' +
        '.card-info { flex:1; min-width:0; }' +
        '.card-label { font-size:.38rem; letter-spacing:.1em; text-transform:uppercase; opacity:.65; }' +
        '.card-number { font-size:.55rem; font-weight:700; font-family:Courier New,monospace; letter-spacing:.06em; }' +
        '.card-validity { font-size:.38rem; opacity:.6; margin-top:1px; }' +
        '.card-qr-wrap img, .card-qr-wrap canvas { width:14mm !important; height:14mm !important; }' +
        '<\/style>' +
        '<\/head><body>' +
        pagesHTML +
        '<script>' +
        'var DESIGN = ' + designJSON + ';' +
        'var CODES  = ' + codesJSON + ';' +
        'var tc = (DESIGN && DESIGN.text_color)   ? DESIGN.text_color   : "#ffffff";' +
        'var ac = (DESIGN && DESIGN.accent_color) ? DESIGN.accent_color : "#1e3a8a";' +
        'var qrText = (DESIGN && DESIGN.card_qr_text && DESIGN.card_qr_text.trim()) ? DESIGN.card_qr_text.trim() : null;' +
        'CODES.forEach(function(code, i) {' +
            'var p     = Math.floor(i / 8) * 8;' +
            'var idx   = i % 8;' +
            'var scope = "p" + p + "i" + idx;' +
            'try { JsBarcode("#bc-" + scope, code, { format:"CODE128", lineColor:tc, background:"transparent", width:1.8, height:36, displayValue:false }); } catch(e) {}' +
            'var tqEl = document.getElementById("tqr-" + scope);' +
            'if (tqEl) { tqEl.innerHTML = ""; try { new QRCode(tqEl, { text:(qrText || code), width:52, height:52, colorDark:ac, colorLight:"rgba(255,255,255,0.85)", correctLevel:QRCode.CorrectLevel.M }); } catch(e) {} }' +
            'var qEl = document.getElementById("qr-" + scope);' +
            'if (qEl) { qEl.innerHTML = ""; try { new QRCode(qEl, { text:code, width:80, height:80, colorDark:ac, colorLight:"#ffffff", correctLevel:QRCode.CorrectLevel.M }); } catch(e) {} }' +
        '});' +
        'requestAnimationFrame(function(){ requestAnimationFrame(function(){ setTimeout(function(){ window.print(); setTimeout(function(){ window.close(); }, 1000); }, 400); }); });' +
        '<\/script>' +
        '<\/body><\/html>';

    var win = window.open('', '_blank', 'width=900,height=700');
    if (!win) {
        alert('Pop-up blocked! Please allow pop-ups for this site and try again.');
        return;
    }
    win.document.open();
    win.document.write(html);
    win.document.close();
});
</script>
ENDJS;
require_once __DIR__ . '/includes/footer.php';
