<?php
$pageTitle = 'Card Generator';
require_once __DIR__ . '/includes/header.php';
$storeName = getSetting('store_name', 'Rewards');

// Safe injection of PHP values into JS — no heredoc needed for the JS block
// We write the entire <script> as a PHP string so there is zero ambiguity.
?>

<div class="row g-4">

  <!-- Left: Controls -->
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">
        <i class="bi bi-credit-card-2-front me-2"></i>Generate Reward Card
      </div>
      <div class="card-body">
        <p class="text-muted small mb-3">
          Click <strong>Generate</strong> to create a new ATM-style loyalty card.
          Format: <code>YYYY-MM-DD-####</code> (counter resets each day).
        </p>

        <div class="mb-3">
          <label class="form-label fw-semibold">Card Code Preview</label>
          <input type="text" id="cardCodeDisplay" class="form-control font-monospace"
                 readonly placeholder="Click Generate…">
        </div>

        <div class="d-grid gap-2">
          <button class="btn btn-primary btn-lg" id="btnGenerate">
            <i class="bi bi-lightning-charge me-2"></i>Generate New Card
          </button>
          <button class="btn btn-success" id="btnSaveCard" disabled>
            <i class="bi bi-cloud-upload me-2"></i>Save to Database
          </button>
          <button class="btn btn-outline-secondary" id="btnPrintCard" disabled>
            <i class="bi bi-printer me-2"></i>Print Card
          </button>
        </div>

        <hr>
        <div id="saveResult" class="alert d-none"></div>

        <div class="card bg-light mt-3">
          <div class="card-body p-3">
            <h6 class="fw-bold"><i class="bi bi-info-circle me-1 text-primary"></i>Card Info</h6>
            <ul class="small mb-0 text-muted">
              <li>QR code encodes the card number</li>
              <li>Barcode replaces the magnetic stripe</li>
              <li>Member registers via webcam scan</li>
              <li>Print on CR80 card stock (credit card size)</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Right: Card Preview -->
  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-header bg-white">
        <i class="bi bi-eye me-2 text-secondary"></i>Card Preview
      </div>
      <div class="card-body text-center py-5 bg-light-subtle" id="cardPreviewArea">
        <i class="bi bi-credit-card text-muted" style="font-size:3rem;opacity:.3"></i>
        <p class="text-muted mt-2 mb-0 small">Generate a card to see the preview.</p>
      </div>
    </div>

    <!-- Recent Cards -->
    <div class="card shadow-sm mt-3">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <span><i class="bi bi-clock-history me-2 text-secondary"></i>Recently Generated</span>
        <button class="btn btn-sm btn-outline-secondary" id="btnRefreshRecent">
          <i class="bi bi-arrow-clockwise"></i>
        </button>
      </div>
      <div class="table-responsive">
        <table class="table table-sm table-hover mb-0 align-middle">
          <thead class="table-light">
            <tr><th>Card Code</th><th>Status</th><th>Created</th><th></th></tr>
          </thead>
          <tbody id="recentCardsList">
            <tr><td colspan="4" class="text-center text-muted py-3">
              <span class="spinner-border spinner-border-sm me-2"></span>Loading…
            </td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</div>

<!-- Print-only area -->
<div id="printArea" style="display:none"></div>

<?php
// ── Inject all JS as a plain PHP string — ZERO heredoc/nowdoc — zero escaping ambiguity ──
// This is the only reliable way to mix PHP constants + JS template literals + jQuery $ sign.
$baseUrl   = BASE_URL;
$storeJs   = addslashes($storeName); // safe for JS single-quoted string

$extraJS = '
<script>
/* ── Constants from PHP ───────────────────────────── */
var BASE_URL = ' . json_encode($baseUrl) . ';
var STORE    = ' . json_encode($storeName) . ';
var currentCardCode = null;
var CARD_DESIGN     = null; // loaded from server on init

/* ── Load card design from server ──────────────────── */
function loadCardDesign(callback) {
    $.ajax({
        url: BASE_URL + "/ajax/get_card_design.php",
        type: "GET",
        dataType: "json",
        success: function(res) {
            if (res.success) {
                CARD_DESIGN = res.design;
                // Update STORE from design (may differ if settings changed)
                STORE = res.design.store_name || STORE;
            }
            if (callback) callback();
        },
        error: function() { if (callback) callback(); }
    });
}

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

/* ── Build ATM card HTML (string concat — no template literals) ── */
function buildCardHTML(code, scope) {
    scope = scope || "preview";
    var d         = CARD_DESIGN || {};
    var bgStyle   = buildCardBgStyle();
    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 labelTxt  = d.label_text    || "MEMBER CARD";
    var subTxt    = d.subtitle_text || "REWARDS MEMBER";
    var storeName = (d.store_name   || STORE || "Rewards").toUpperCase();

    var html = "";
    html += "<div class=\"reward-card\" id=\"" + scope + "-rewardCard\"";
    html +=   " 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=\"card-top-qr\" id=\"" + scope + "-top-qr\"></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.25rem;\"></i></div>";
    html +=   "</div>";
    html +=   "<div class=\"card-stripe\">";
    html +=     "<svg id=\"" + scope + "-barcode\"></svg>";
    html +=   "</div>";
    html +=   "<div class=\"card-bottom\">";
    html +=     "<div class=\"card-info\">";
    html +=       "<div class=\"card-label\" style=\"color:" + textColor + ";opacity:.6;\">" + labelTxt + "</div>";
    html +=       "<div class=\"card-number\" style=\"color:" + textColor + ";\">" + code + "</div>";
    html +=       "<div class=\"card-validity\" style=\"color:" + textColor + ";opacity:.6;\">" + subTxt + "</div>";
    html +=     "</div>";
    html +=     "<div class=\"card-qr-wrap\" id=\"" + scope + "-qr\"></div>";
    html +=   "</div>";
    html += "</div>";
    return html;
}

/* ── Render barcode + QR into scoped container ─────── */
function renderCodes(code, scope) {
    scope = scope || "preview";

    var lineColor = (CARD_DESIGN && CARD_DESIGN.text_color)   ? CARD_DESIGN.text_color   : "#ffffff";
    var qrDark    = (CARD_DESIGN && CARD_DESIGN.accent_color) ? CARD_DESIGN.accent_color : "#1e3a8a";

    // Top-left QR — uses card_qr_text setting; falls back to card code if blank
    var topQrText = (CARD_DESIGN && CARD_DESIGN.card_qr_text && CARD_DESIGN.card_qr_text.trim())
        ? CARD_DESIGN.card_qr_text.trim()
        : code;
    var topQrEl = document.getElementById(scope + "-top-qr");
    if (topQrEl) {
        topQrEl.innerHTML = "";
        new QRCode(topQrEl, {
            text:         topQrText,
            width:        48,
            height:       48,
            colorDark:    qrDark,
            colorLight:   "rgba(255,255,255,0.85)",
            correctLevel: QRCode.CorrectLevel.M
        });
    }

    // Middle barcode — always the card code
    JsBarcode("#" + scope + "-barcode", code, {
        format:       "CODE128",
        lineColor:    lineColor,
        background:   "transparent",
        width:        1.6,
        height:       38,
        displayValue: false
    });

    // Bottom-right QR — always the card code
    var qrEl = document.getElementById(scope + "-qr");
    if (qrEl) {
        qrEl.innerHTML = "";
        new QRCode(qrEl, {
            text:         code,
            width:        76,
            height:       76,
            colorDark:    qrDark,
            colorLight:   "#ffffff",
            correctLevel: QRCode.CorrectLevel.M
        });
    }
}

/* ── Init: load design on page load ────────────────── */
loadCardDesign(function() {
    // Design loaded — ready to generate
    document.getElementById("btnGenerate").disabled = false;
});

/* ── Generate ──────────────────────────────────────── */
document.getElementById("btnGenerate").addEventListener("click", function () {
    var btn = this;
    btn.disabled = true;
    btn.innerHTML = "<span class=\"spinner-border spinner-border-sm me-2\"></span>Generating\u2026";

    $.ajax({
        url:      BASE_URL + "/ajax/generate_card.php",
        type:     "POST",
        dataType: "json",
        success: function (res) {
            if (res && res.success) {
                currentCardCode = res.card_code;
                document.getElementById("cardCodeDisplay").value = currentCardCode;

                var previewArea = document.getElementById("cardPreviewArea");
                previewArea.innerHTML = buildCardHTML(currentCardCode, "preview");
                renderCodes(currentCardCode, "preview");

                document.getElementById("btnSaveCard").disabled  = false;
                document.getElementById("btnPrintCard").disabled = false;
                document.getElementById("saveResult").className  = "alert d-none";
            } else {
                showSaveResult("danger", "\u274C " + (res ? res.error : "Unknown error"));
            }
        },
        error: function (xhr) {
            var msg = "Server error";
            try { var j = JSON.parse(xhr.responseText); msg = j.error || msg; } catch(e){}
            showSaveResult("danger", "\u274C " + msg + " (HTTP " + xhr.status + ")");
        },
        complete: function () {
            btn.disabled = false;
            btn.innerHTML = "<i class=\"bi bi-lightning-charge me-2\"></i>Generate New Card";
        }
    });
});

/* ── Save ──────────────────────────────────────────── */
document.getElementById("btnSaveCard").addEventListener("click", function () {
    if (!currentCardCode) return;
    var btn = this;
    btn.disabled = true;
    btn.innerHTML = "<span class=\"spinner-border spinner-border-sm me-2\"></span>Saving\u2026";

    $.ajax({
        url:      BASE_URL + "/ajax/save_card.php",
        type:     "POST",
        data:     { card_code: currentCardCode },
        dataType: "json",
        success: function (res) {
            if (res && res.success) {
                showSaveResult("success", "\u2705 " + res.message);
                btn.innerHTML = "<i class=\"bi bi-check-lg me-2\"></i>Saved";
                loadRecentCards();
            } else {
                showSaveResult("danger", "\u274C " + (res ? res.error : "Save failed"));
                btn.disabled = false;
                btn.innerHTML = "<i class=\"bi bi-cloud-upload me-2\"></i>Save to Database";
            }
        },
        error: function () {
            showSaveResult("danger", "\u274C Server error. Please try again.");
            btn.disabled = false;
            btn.innerHTML = "<i class=\"bi bi-cloud-upload me-2\"></i>Save to Database";
        }
    });
});

/* ── Print ─────────────────────────────────────────── */
document.getElementById("btnPrintCard").addEventListener("click", function () {
    if (!currentCardCode) return;
    doPrintCard(currentCardCode);
});

function doPrintCard(code) {
    // 1. Build card markup
    var printArea = document.getElementById("printArea");
    printArea.innerHTML = buildCardHTML(code, "print");

    // 2. Make printArea visible FIRST so JsBarcode can read element dimensions
    //    Move it to <body> directly so @media print CSS can target it cleanly
    //    (it is normally nested inside #app-wrapper which gets display:none on print)
    document.body.appendChild(printArea);
    printArea.style.cssText = "display:block;position:fixed;top:0;left:0;width:100vw;height:100vh;" +
        "background:#fff;display:flex;align-items:center;justify-content:center;z-index:99999;";

    // 3. Render barcode now that the element is visible (offsetWidth > 0)
    var printLineColor = (CARD_DESIGN && CARD_DESIGN.text_color)   ? CARD_DESIGN.text_color   : "#ffffff";
    var printQrDark    = (CARD_DESIGN && CARD_DESIGN.accent_color) ? CARD_DESIGN.accent_color : "#1e3a8a";

    JsBarcode("#print-barcode", code, {
        format:       "CODE128",
        lineColor:    printLineColor,
        background:   "transparent",
        width:        1.8,
        height:       42,
        displayValue: false
    });

    // 4. Top-left QR (from card_qr_text setting, falls back to card code)
    var printTopQrText = (CARD_DESIGN && CARD_DESIGN.card_qr_text && CARD_DESIGN.card_qr_text.trim())
        ? CARD_DESIGN.card_qr_text.trim()
        : code;
    var printTopQrEl = document.getElementById("print-top-qr");
    if (printTopQrEl) {
        printTopQrEl.innerHTML = "";
        new QRCode(printTopQrEl, {
            text:         printTopQrText,
            width:        48,
            height:       48,
            colorDark:    printQrDark,
            colorLight:   "rgba(255,255,255,0.85)",
            correctLevel: QRCode.CorrectLevel.M
        });
    }

    // 5. Bottom-right QR — always the card code
    var printQrEl = document.getElementById("print-qr");
    if (printQrEl) {
        printQrEl.innerHTML = "";
        new QRCode(printQrEl, {
            text:         code,
            width:        80,
            height:       80,
            colorDark:    printQrDark,
            colorLight:   "#ffffff",
            correctLevel: QRCode.CorrectLevel.M
        });
    }

    // 5. Wait one animation frame + small buffer for canvas to finish painting,
    //    then open print dialog
    requestAnimationFrame(function () {
        setTimeout(function () {
            window.print();
            // 6. After print dialog closes (or is cancelled), restore DOM
            setTimeout(function () {
                printArea.style.cssText = "display:none;";
                // Move printArea back to its original position inside page-body
                var pageBody = document.querySelector(".page-body");
                if (pageBody) pageBody.appendChild(printArea);
            }, 800);
        }, 200);
    });
}

/* ── Recent Cards ──────────────────────────────────── */
function loadRecentCards() {
    $.ajax({
        url:      BASE_URL + "/ajax/recent_cards.php",
        type:     "GET",
        dataType: "json",
        success: function (res) {
            var tbody = document.getElementById("recentCardsList");
            if (!res || !res.success || !res.cards.length) {
                tbody.innerHTML = "<tr><td colspan=\"4\" class=\"text-center text-muted py-3\">No cards yet.</td></tr>";
                return;
            }
            var rows = "";
            for (var i = 0; i < res.cards.length; i++) {
                var c   = res.cards[i];
                var url = BASE_URL + "/member-registration.php?card=" + encodeURIComponent(c.card_code);
                var badge = c.name
                    ? "<span class=\"badge bg-success\">Registered</span>"
                    : "<span class=\"badge bg-secondary\">Unregistered</span>";
                rows += "<tr>"
                      + "<td><code class=\"small\">" + c.card_code + "</code></td>"
                      + "<td>" + badge + "</td>"
                      + "<td class=\"text-muted small\">" + c.created_at + "</td>"
                      + "<td><a href=\"" + url + "\" class=\"btn btn-outline-primary btn-xs\">Register</a></td>"
                      + "</tr>";
            }
            tbody.innerHTML = rows;
        },
        error: function () {
            document.getElementById("recentCardsList").innerHTML =
                "<tr><td colspan=\"4\" class=\"text-danger text-center small py-2\">Failed to load.</td></tr>";
        }
    });
}

document.getElementById("btnRefreshRecent").addEventListener("click", loadRecentCards);
loadRecentCards();

function showSaveResult(type, html) {
    var el = document.getElementById("saveResult");
    el.className = "alert alert-" + type;
    el.innerHTML = html;
    el.classList.remove("d-none");
}
</script>';

require_once __DIR__ . '/includes/footer.php';
