<?php
$mobileTitle = 'Card Generator';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
$storeName = getSetting('store_name', 'Rewards');
include __DIR__ . '/includes/m_header.php';
?>

<div class="m-section-title">Generate Reward Card</div>

<!-- Card Preview Area -->
<div class="m-card mb-3" style="background:#1e293b">
  <div class="m-card-body text-center py-4" id="mCardPreview">
    <i class="bi bi-credit-card text-muted opacity-25" style="font-size:3rem"></i>
    <div class="text-muted small mt-2">Tap Generate to preview</div>
  </div>
</div>

<!-- Card Code Display -->
<div class="m-input-group mb-3" id="cardCodeBox" style="display:none">
  <i class="bi bi-upc text-primary"></i>
  <input type="text" id="mCardCode" readonly style="font-family:monospace;font-weight:700">
</div>

<!-- Actions -->
<button class="m-btn m-btn-primary mb-2" id="mBtnGenerate">
  <i class="bi bi-lightning-charge me-2"></i>Generate New Card
</button>
<button class="m-btn m-btn-success mb-2 d-none" id="mBtnSave">
  <i class="bi bi-cloud-upload me-2"></i>Save to Database
</button>
<button class="m-btn m-btn-outline mb-2 d-none" id="mBtnPrint">
  <i class="bi bi-printer me-2"></i>Print Card
</button>

<div id="mCardMsg" style="display:none;margin-top:.75rem"></div>

<hr style="border-color:#e2e8f0;margin:1.25rem 0">

<!-- Recent Cards -->
<div class="m-section-title">Recently Generated</div>
<div id="mRecentCards">
  <div class="text-muted text-center small py-3">Loading…</div>
</div>

<!-- Print Area -->
<div id="m-printArea"></div>

<?php
$jsBaseUrl   = json_encode(BASE_URL);
$jsStoreName = json_encode($storeName);
$mExtraJS = '<script>var BASE_URL=' . $jsBaseUrl . ';var STORE=' . $jsStoreName . ';var CARD_DESIGN=null;var currentCode=null;</script>' . <<<'ENDJS'
<script>
/* Load design settings */
$.ajax({ url: BASE_URL + '/ajax/get_card_design.php', type: 'GET', dataType: 'json',
    success: function (r) { if (r.success) CARD_DESIGN = r.design; }
});

function buildCardBg() {
    var d = CARD_DESIGN;
    if (d && d.bg_type === 'image' && d.bg_image)
        return 'background:url(' + d.bg_image + ') center/cover no-repeat;';
    var dir = (d && d.gradient_dir)   || '135deg';
    var c1  = (d && d.color1)         || '#1e3a8a';
    var c2  = (d && d.color2)         || '#1d4ed8';
    var c3  = (d && d.color3)         || '#0ea5e9';
    return 'background:linear-gradient(' + dir + ',' + c1 + ' 0%,' + c2 + ' 45%,' + c3 + ' 100%);';
}

function buildMobileCard(code, scope) {
    scope = scope || 'mc-preview';
    var d         = CARD_DESIGN || {};
    var bgStyle   = buildCardBg();
    var textColor = d.text_color   || '#ffffff';
    var accent    = d.accent_color || '#facc15';
    var icon      = d.logo_icon    || 'star-fill';
    var shimmer   = (d.show_shimmer === '1' || d.show_shimmer === undefined);
    var label     = d.label_text    || 'MEMBER CARD';
    var subtitle  = d.subtitle_text || 'REWARDS MEMBER';
    var storeName = (d.store_name || STORE || 'Rewards').toUpperCase();

    var html = '<div class="m-reward-card" id="' + scope + '-card"'
             + ' style="' + bgStyle + '--card-text:' + textColor + ';--card-accent:' + accent + ';">';
    if (shimmer) html += '<div class="card-shimmer-overlay"></div>';
    html += '<div class="card-circle-deco"></div>';
    html += '<div class="card-top">';
    html += '  <div class="chip"><div class="chip-inner"></div></div>';
    html += '  <div class="card-store-name" style="color:' + textColor + ';opacity:.85;">' + storeName + '</div>';
    html += '  <div class="card-logo"><i class="bi bi-' + icon + '" style="color:' + accent + ';font-size:1.1rem;"></i></div>';
    html += '</div>';
    html += '<div class="card-stripe"><svg id="' + scope + '-barcode"></svg></div>';
    html += '<div class="card-bottom">';
    html += '  <div class="card-info">';
    html += '    <div class="card-label" style="color:' + textColor + ';opacity:.6;">' + label + '</div>';
    html += '    <div class="card-number" style="color:' + textColor + ';">' + code + '</div>';
    html += '    <div class="card-validity" style="color:' + textColor + ';opacity:.6;">' + subtitle + '</div>';
    html += '  </div>';
    html += '  <div class="card-qr-wrap" id="' + scope + '-qr"></div>';
    html += '</div>';
    html += '</div>';
    return html;
}

function renderCardCodes(code, scope) {
    scope = scope || 'mc-preview';
    var d         = CARD_DESIGN || {};
    var lineColor = d.text_color || '#ffffff';
    var qrDark    = d.accent_color || '#1e3a8a';

    JsBarcode('#' + scope + '-barcode', code, {
        format: 'CODE128', lineColor: lineColor,
        background: 'transparent', width: 1.4, height: 34, displayValue: false
    });
    var qrEl = document.getElementById(scope + '-qr');
    if (qrEl) {
        qrEl.innerHTML = '';
        new QRCode(qrEl, {
            text: code, width: 68, height: 68,
            colorDark: qrDark, colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.M
        });
    }
}

/* ── Generate ─────────────────────────────────────────── */
document.getElementById('mBtnGenerate').addEventListener('click', function () {
    var btn = this;
    mBtnLoading(btn, true);
    $.ajax({ url: BASE_URL + '/ajax/generate_card.php', type: 'POST', dataType: 'json',
        success: function (res) {
            mBtnLoading(btn, false);
            if (res && res.success) {
                currentCode = res.card_code;
                document.getElementById('mCardCode').value     = currentCode;
                document.getElementById('cardCodeBox').style.display = 'flex';
                document.getElementById('mBtnSave').classList.remove('d-none');
                document.getElementById('mBtnPrint').classList.remove('d-none');
                document.getElementById('mCardMsg').style.display = 'none';
                var preview = document.getElementById('mCardPreview');
                preview.innerHTML = buildMobileCard(currentCode, 'mc-preview');
                renderCardCodes(currentCode, 'mc-preview');
            } else {
                mShowAlert('mCardMsg', 'danger', (res && res.error) || 'Generation failed.');
            }
        },
        error: function () { mBtnLoading(btn, false); mShowAlert('mCardMsg', 'danger', 'Server error.'); }
    });
});

/* ── Save ─────────────────────────────────────────────── */
document.getElementById('mBtnSave').addEventListener('click', function () {
    if (!currentCode) return;
    var btn = this;
    mBtnLoading(btn, true);
    $.ajax({ url: BASE_URL + '/ajax/save_card.php', type: 'POST',
             data: { card_code: currentCode }, dataType: 'json',
        success: function (res) {
            mBtnLoading(btn, false);
            if (res && res.success) {
                mShowAlert('mCardMsg', 'success', '\u2705 Card saved!');
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-check-lg me-2"></i>Saved';
                loadRecentCards();
            } else {
                mShowAlert('mCardMsg', 'danger', (res && res.error) || 'Save failed.');
            }
        },
        error: function () { mBtnLoading(btn, false); mShowAlert('mCardMsg', 'danger', 'Server error.'); }
    });
});

/* ── Print ────────────────────────────────────────────── */
document.getElementById('mBtnPrint').addEventListener('click', function () {
    if (!currentCode) return;
    var pa = document.getElementById('m-printArea');
    pa.innerHTML = buildMobileCard(currentCode, 'mc-print');
    document.body.appendChild(pa);
    pa.style.cssText = 'display:flex;position:fixed;top:0;left:0;width:100vw;height:100vh;background:#fff;align-items:center;justify-content:center;z-index:99999;';

    JsBarcode('#mc-print-barcode', currentCode, {
        format: 'CODE128', lineColor: (CARD_DESIGN && CARD_DESIGN.text_color) || '#ffffff',
        background: 'transparent', width: 1.8, height: 42, displayValue: false
    });
    var pqr = document.getElementById('mc-print-qr');
    if (pqr) {
        pqr.innerHTML = '';
        new QRCode(pqr, { text: currentCode, width: 80, height: 80,
            colorDark: (CARD_DESIGN && CARD_DESIGN.accent_color) || '#1e3a8a',
            colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M });
    }

    requestAnimationFrame(function () {
        setTimeout(function () {
            window.print();
            setTimeout(function () {
                pa.style.display = 'none';
                document.querySelector('.m-content').appendChild(pa);
            }, 800);
        }, 250);
    });
});

/* ── Recent Cards ─────────────────────────────────────── */
function loadRecentCards() {
    $.ajax({ url: BASE_URL + '/ajax/recent_cards.php', type: 'GET', dataType: 'json',
        success: function (res) {
            var el = document.getElementById('mRecentCards');
            if (!res.success || !res.cards.length) {
                el.innerHTML = '<div class="text-muted text-center small py-3">No cards yet.</div>';
                return;
            }
            var html = '';
            res.cards.forEach(function (c) {
                var regUrl = BASE_URL + '/mobile/register.php?card=' + encodeURIComponent(c.card_code);
                var badge  = c.name
                    ? '<span class="badge bg-success" style="font-size:.65rem">Registered</span>'
                    : '<span class="badge bg-secondary" style="font-size:.65rem">Unregistered</span>';
                html += '<div class="m-card mb-2"><div class="m-card-body" style="padding:.75rem 1rem">'
                      + '<div class="d-flex align-items-center gap-2">'
                      + '<code style="font-size:.75rem;flex-grow:1">' + c.card_code + '</code>'
                      + badge
                      + '<a href="' + regUrl + '" class="btn btn-sm btn-outline-primary" style="font-size:.7rem;padding:2px 8px">Register</a>'
                      + '</div>'
                      + '<div class="text-muted mt-1" style="font-size:.65rem">' + c.created_at + '</div>'
                      + '</div></div>';
            });
            el.innerHTML = html;
        }
    });
}
loadRecentCards();

function mShowAlert(elId, type, html) {
    var el = document.getElementById(elId);
    if (!el) return;
    el.className = 'm-alert m-alert-' + type;
    el.innerHTML = '<i class="bi bi-' + {success:'check-circle-fill',danger:'x-circle-fill',info:'info-circle-fill',warning:'exclamation-triangle-fill'}[type] + '"></i><span>' + html + '</span>';
    el.style.display = 'flex';
}
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
