<?php
/**
 * Customer Portal — Public-facing loyalty points viewer.
 * No login required. Customer scans or enters their card code to see:
 *   - Points balance & redemption value
 *   - Their digital ATM-style card
 *   - Recent transaction history
 *   - Lifetime stats
 *
 * Flow mirrors mobile/scan.php:
 *   Step 1 → Scan / manual entry
 *   Step 2 → Rewards dashboard (read-only, customer-only)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$storeName = getSetting('store_name', 'Rewards');
$prefill   = htmlspecialchars(trim($_GET['card'] ?? ''), ENT_QUOTES);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#0f172a">
<title>My Rewards — <?= htmlspecialchars($storeName) ?></title>

<!-- Bootstrap 5 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.css" rel="stylesheet">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<!-- JsBarcode + QRCode for card preview -->
<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>
/* ════════════════════════════════════════════
   Customer Rewards Portal
════════════════════════════════════════════ */
:root {
  --primary:  #0d6efd;
  --dark:     #0f172a;
  --font:     'Inter', system-ui, sans-serif;
}
*, *::before, *::after { box-sizing: border-box; }
html { scroll-behavior: smooth; }

body {
  font-family: var(--font);
  background: #f1f5f9;
  color: #1e293b;
  min-height: 100vh;
  font-size: .9rem;
}

/* ── Header ─────────────────────────────── */
.c-header {
  background: var(--dark);
  padding: 1rem 1.25rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 50;
  box-shadow: 0 2px 12px rgba(0,0,0,.3);
}
.c-store-name  { color:#fff; font-weight:700; font-size:1rem; display:flex; align-items:center; gap:.5rem; }
.c-header-badge { background:rgba(255,255,255,.12); color:rgba(255,255,255,.8); font-size:.65rem; padding:2px 8px; border-radius:99px; }

/* ── Page wrapper ─────────────────────── */
.c-wrap {
  max-width: 480px;
  margin: 0 auto;
  padding: 1.25rem;
}

/* ── Section titles ───────────────────── */
.c-section-title {
  font-size: .68rem; font-weight: 700; text-transform: uppercase;
  letter-spacing: .1em; color: #64748b; margin-bottom: .6rem;
}

/* ── Cards / surfaces ─────────────────── */
.c-surface {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,.07);
  /* No overflow:hidden — would clip the scanner widget injected by html5-qrcode */
  margin-bottom: 1rem;
}
.c-surface-scanner {
  /* Scanner surface gets its own clipping only at the wrap level */
  border-radius: 16px 16px 0 0;
  overflow: hidden;
}
.c-surface-body { padding: 1rem; }

/* ── Scanner ──────────────────────────── */
.c-scanner-wrap {
  position: relative;
  background: #000;
  border-radius: 16px 16px 0 0; /* matches parent surface top corners */
  overflow: hidden;
  width: 100%;
  min-height: 240px;
}
#c-qr-scan               { width:100% !important; border:none !important; }
#c-qr-scan video         { width:100% !important; object-fit:cover; }
#c-qr-scan img           { display:none !important; }

.scanner-frame {
  position: absolute; top:50%; left:50%;
  transform: translate(-50%, -50%);
  width: 72%; height: 58%;
  pointer-events: none; z-index: 10;
}
.scanner-frame::before,
.scanner-frame::after,
.scanner-frame-inner::before,
.scanner-frame-inner::after {
  content: ''; position: absolute;
  width: 22px; height: 22px;
  border-color: #fff; border-style: solid;
}
.scanner-frame::before        { top:0;    left:0;  border-width:3px 0 0 3px; }
.scanner-frame::after         { top:0;    right:0; border-width:3px 3px 0 0; }
.scanner-frame-inner::before  { bottom:0; left:0;  border-width:0 0 3px 3px; }
.scanner-frame-inner::after   { bottom:0; right:0; border-width:0 3px 3px 0; }

.scan-line {
  position: absolute; left: 50%;
  width: 72%; height: 2px;
  background: linear-gradient(90deg, transparent, #0d6efd, #0ea5e9, transparent);
  z-index: 11; pointer-events: none;
  animation: scanMove 2s ease-in-out infinite;
  will-change: transform, opacity;
}
@keyframes scanMove {
  0%   { transform:translate(-50%, -56px); opacity:0; }
  10%  { opacity:1; }
  90%  { opacity:1; }
  100% { transform:translate(-50%,  56px); opacity:0; }
}
.scanner-hint {
  position: absolute; bottom:10px; left:0; right:0;
  text-align: center; color:rgba(255,255,255,.8);
  font-size:.75rem; font-weight:500;
  pointer-events:none; z-index:10;
}

/* ── Buttons ──────────────────────────── */
.c-btn {
  display:flex; align-items:center; justify-content:center;
  gap:.5rem; border-radius:12px; font-weight:700;
  font-size:.9rem; line-height:1.2; padding:.8rem 1.25rem; border:none;
  cursor:pointer; width:100%; font-family:var(--font);
  text-decoration:none; /* safe when used on <a> */
  transition:transform .15s, box-shadow .15s, opacity .15s;
}
.c-btn:active          { transform:scale(.97); }
.c-btn:disabled,
.c-btn[disabled]       { opacity:.5; cursor:not-allowed; pointer-events:none; }

/* Auto-width modifier — replaces inline style overrides */
.c-btn-auto            { width:auto; display:inline-flex; }
/* Small modifier */
.c-btn-sm              { padding:.5rem 1rem; font-size:.82rem; }

.c-btn-primary         { background:linear-gradient(135deg,#0d6efd,#0ea5e9); color:#fff; box-shadow:0 4px 14px rgba(13,110,253,.3); }
.c-btn-primary:hover   { box-shadow:0 6px 18px rgba(13,110,253,.45); }
.c-btn-primary:active  { box-shadow:0 2px 6px  rgba(13,110,253,.3); }

.c-btn-danger          { background:#dc3545; color:#fff; box-shadow:0 4px 14px rgba(220,53,69,.3); }
.c-btn-danger:hover    { box-shadow:0 6px 18px rgba(220,53,69,.45); }
.c-btn-danger:active   { box-shadow:0 2px 6px  rgba(220,53,69,.3); }

.c-btn-outline         { background:#fff; color:var(--primary); border:2px solid var(--primary); }
.c-btn-outline:hover   { background:#eff6ff; }
.c-btn-outline:active  { background:#dbeafe; }

.c-btn-ghost           { background:transparent; color:#64748b; border:2px solid #e2e8f0; }
.c-btn-ghost:hover     { background:#f8fafc; border-color:#cbd5e1; }
.c-btn-ghost:active    { background:#f1f5f9; }

/* ── Input ────────────────────────────── */
.c-input-wrap {
  background:#f8fafc; border:2px solid #e2e8f0; border-radius:12px;
  display:flex; align-items:center; gap:.75rem;
  padding:.8rem 1rem; margin-bottom:.75rem;
  transition:border-color .15s;
}
.c-input-wrap:focus-within { border-color:var(--primary); background:#fff; }
.c-input-wrap i   { color:#94a3b8; font-size:1.1rem; flex-shrink:0; }
.c-input-wrap input {
  border:none; background:transparent; outline:none;
  width:100%; font-size:.95rem; font-family:'Courier New',monospace;
  font-weight:600; letter-spacing:.04em; color:#1e293b;
}

/* ── Alert ────────────────────────────── */
.c-alert {
  border-radius:10px; padding:.8rem 1rem;
  font-size:.85rem; display:flex; align-items:flex-start;
  gap:.6rem; margin-bottom:.75rem;
}
.c-alert i        { font-size:1rem; flex-shrink:0; margin-top:1px; }
.c-alert-danger   { background:#fef2f2; color:#991b1b; border:1px solid #fecaca; }
.c-alert-warning  { background:#fffbeb; color:#92400e; border:1px solid #fde68a; }

/* Needed for text-truncate to work inside flex containers */
.min-width-0 { min-width: 0; }

/* ── Greeting ─────────────────────────── */
.c-greeting {
  display:flex; align-items:center; gap:1rem; margin-bottom:1.25rem;
}
.c-avatar {
  width:52px; height:52px; border-radius:50%;
  background:linear-gradient(135deg,#1e3a8a,#0ea5e9);
  color:#fff; font-size:1.2rem; font-weight:800;
  display:flex; align-items:center; justify-content:center; flex-shrink:0;
}
.c-greeting-name  { font-size:1.1rem; font-weight:800; }
.c-greeting-meta  { font-size:.72rem; color:#64748b; font-family:monospace; }
.c-greeting-since { font-size:.7rem;  color:#94a3b8; }

/* ── Points hero ──────────────────────── */
.c-points-hero {
  border-radius:16px; padding:1.5rem 1.25rem;
  /* Fallback gradient if JS hasn't applied the custom design yet */
  background: linear-gradient(135deg,#1e3a8a 0%,#1d4ed8 45%,#0ea5e9 100%);
  color:#fff; margin-bottom:1rem;
  position:relative; overflow:hidden;
}
.c-points-hero::before {
  content:''; position:absolute; top:-60%; left:-40%;
  width:100%; height:180%;
  background:linear-gradient(105deg,rgba(255,255,255,0) 30%,rgba(255,255,255,.1) 50%,rgba(255,255,255,0) 70%);
  transform:rotate(-15deg); pointer-events:none;
}
.c-points-label  { font-size:.68rem; font-weight:700; letter-spacing:.1em; text-transform:uppercase; opacity:.75; margin-bottom:.25rem; }
.c-points-number { font-size:3.2rem; font-weight:900; line-height:1; margin-bottom:.2rem; }
.c-points-sub    { font-size:.82rem; opacity:.8; }
.c-points-expiry { font-size:.7rem;  opacity:.6; margin-top:.4rem; }

.c-redeem-box {
  display:flex; align-items:center; gap:.85rem;
  background:rgba(255,255,255,.15); border-radius:10px;
  padding:.8rem 1rem; margin-top:.9rem;
}
.c-redeem-box i   { font-size:1.4rem; }
.c-redeem-label   { font-size:.68rem; opacity:.75; }
.c-redeem-value   { font-size:1.1rem; font-weight:800; }
.c-redeem-note    { font-size:.63rem; opacity:.65; }

/* ── Stat pills ───────────────────────── */
.c-stats-row {
  display:grid; grid-template-columns:repeat(3,1fr);
  gap:.6rem; margin-bottom:1rem;
}
.c-stat-pill {
  background:#fff; border-radius:12px;
  padding:.8rem .65rem; text-align:center;
  box-shadow:0 1px 4px rgba(0,0,0,.06);
}
.c-stat-pill-val   { font-size:1.2rem; font-weight:800; color:#0f172a; line-height:1; }
.c-stat-pill-label { font-size:.6rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; margin-top:.2rem; }

/* ── Digital reward card ──────────────── */
.reward-card {
  width:100%; max-width:340px; height:210px;
  border-radius:14px;
  background:linear-gradient(135deg,#1e3a8a 0%,#1d4ed8 45%,#0ea5e9 100%);
  position:relative; overflow:hidden;
  box-shadow:0 10px 30px rgba(29,78,216,.4);
  margin:0 auto; display:flex; flex-direction:column;
}
.card-shimmer-overlay {
  position:absolute; top:-60%; left:-40%; width:100%; height:180%;
  background:linear-gradient(105deg,rgba(255,255,255,0) 30%,rgba(255,255,255,.13) 50%,rgba(255,255,255,0) 70%);
  transform:rotate(-15deg); pointer-events:none; z-index:1;
}
.card-circle-deco {
  position:absolute; right:-35px; top:-35px;
  width:140px; height:140px; border-radius:50%;
  background:rgba(255,255,255,.06); pointer-events:none; z-index:1;
}
.card-top {
  display:flex; align-items:center; justify-content:space-between;
  padding:12px 14px 6px; position:relative; z-index:2;
}
/* Top-left QR replaces the gold chip */
.card-top-qr { width:46px; height:46px; flex-shrink:0; border-radius:4px; overflow:hidden; }
.card-top-qr img,
.card-top-qr canvas { width:46px !important; height:46px !important; display:block; border-radius:4px; }
.card-store-name { font-size:.55rem; font-weight:700; letter-spacing:.16em; }
.card-stripe {
  background:rgba(0,0,0,.22); padding:3px 0 2px;
  display:flex; align-items:center; justify-content:center;
  position:relative; z-index:2;
}
.card-stripe svg { width:100%; height:34px; padding:0 8px; }
.card-bottom {
  flex:1; display:flex; align-items:flex-end;
  justify-content:space-between; padding:4px 14px 12px;
  position:relative; z-index:2;
}
.card-label    { font-size:.45rem; letter-spacing:.12em; text-transform:uppercase; margin-bottom:2px; }
.card-number   { font-size:.7rem;  font-weight:700; letter-spacing:.1em; font-family:'Courier New',monospace; }
.card-validity { font-size:.5rem;  letter-spacing:.1em; margin-top:2px; }
.card-qr-wrap img,
.card-qr-wrap canvas { width:64px !important; height:64px !important; border-radius:4px; display:block; }

/* ── Transaction list ─────────────────── */
.c-txn-list { background:#fff; border-radius:14px; overflow:hidden; box-shadow:0 1px 4px rgba(0,0,0,.06); margin-bottom:1rem; }
.c-txn-item { display:flex; align-items:center; gap:.85rem; padding:.8rem 1rem; border-bottom:1px solid #f1f5f9; }
.c-txn-item:last-child { border-bottom:none; }
.c-txn-icon {
  width:38px; height:38px; border-radius:10px;
  display:flex; align-items:center; justify-content:center;
  font-size:1rem; flex-shrink:0;
}
.c-txn-icon.earn   { background:#ecfdf5; color:#059669; }
.c-txn-icon.redeem { background:#eff6ff; color:#0d6efd; }
.c-txn-name  { font-weight:600; font-size:.85rem; }
.c-txn-note  { font-size:.7rem; color:#94a3b8; }
.c-txn-right { margin-left:auto; text-align:right; flex-shrink:0; }
.c-txn-pts   { font-weight:700; font-size:.88rem; }
.c-txn-date  { font-size:.65rem; color:#94a3b8; }
.earn-pts    { color:#059669; }
.redeem-pts  { color:#0d6efd; }

/* ── QR modal ─────────────────────────── */
.qr-modal {
  position:fixed; inset:0; background:rgba(0,0,0,.7);
  z-index:999; display:flex; align-items:center; justify-content:center;
  padding:1.5rem;
}
.qr-modal-card {
  background:#fff; border-radius:20px; padding:2rem 1.5rem;
  text-align:center; width:100%; max-width:300px;
}
.qr-modal-card h6   { font-weight:700; margin-bottom:1rem; }
.qr-modal-card code { font-size:.85rem; display:block; margin-top:.75rem; color:#475569; }

/* ── Empty state ──────────────────────── */
.c-empty { text-align:center; padding:2.5rem 1rem; color:#94a3b8; }
.c-empty i { font-size:2.5rem; display:block; margin-bottom:.75rem; opacity:.3; }

/* ── Footer ───────────────────────────── */
.c-footer { text-align:center; padding:1.5rem 1rem 2rem; color:#94a3b8; font-size:.72rem; }

@media (min-width:600px) {
  .c-wrap          { padding:1.5rem; }
  .c-points-number { font-size:3.8rem; }
}
</style>
</head>
<body>

<!-- ── Header ────────────────────────────── -->
<div class="c-header">
  <div class="c-store-name">
    <i class="bi bi-star-fill text-warning"></i>
    <?= htmlspecialchars($storeName) ?>
  </div>
  <span class="c-header-badge">Member Portal</span>
</div>

<!-- ══ STEP 1 — Scan / Enter Card ═══════════════════════ -->
<div id="step1" class="c-wrap">

  <div class="c-section-title"><i class="bi bi-upc-scan me-1"></i>Step 1 — Scan or Enter Your Card</div>

  <!-- Scanner surface -->
  <div class="c-surface c-surface-scanner">
    <div class="c-scanner-wrap">
      <div id="c-qr-scan"></div>
      <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
      <div class="scan-line"   id="cScanLine" style="display:none"></div>
      <div class="scanner-hint" id="cScanHint">Tap Start Camera to scan</div>
    </div>
    <div class="c-surface-body" style="display:grid;grid-template-columns:1fr 1fr;gap:.6rem">
      <button class="c-btn c-btn-primary" id="btnScanStart">
        <i class="bi bi-camera-video me-2"></i>Start Camera
      </button>
      <button class="c-btn c-btn-danger d-none" id="btnScanStop">
        <i class="bi bi-stop-circle me-2"></i>Stop
      </button>
    </div>
  </div>

  <!-- Manual entry surface -->
  <div class="c-surface">
    <div class="c-surface-body">
      <div class="c-input-wrap">
        <i class="bi bi-credit-card-2-front"></i>
        <input type="text" id="cardInput"
               placeholder="YYYY-MM-DD-####"
               value="<?= $prefill ?>"
               autocomplete="off"
               maxlength="30"
               style="text-transform:uppercase">
      </div>

      <div id="lookupAlert" style="display:none" class="c-alert c-alert-danger">
        <i class="bi bi-x-circle-fill"></i><span id="lookupAlertMsg"></span>
      </div>

      <button class="c-btn c-btn-primary" id="btnLookup">
        <i class="bi bi-search me-2"></i>Check My Rewards
      </button>
    </div>
  </div>

  <div class="c-footer">
    <i class="bi bi-shield-check me-1 text-success"></i>
    Your data is private. We only show points to the cardholder.
  </div>
</div>

<!-- ══ STEP 2 — Rewards Dashboard ════════════════════════ -->
<div id="step2" style="display:none" class="c-wrap">

  <!-- Back link -->
  <button class="c-btn c-btn-ghost c-btn-auto c-btn-sm mb-3" id="btnBack">
    <i class="bi bi-arrow-repeat me-2"></i>Check Another Card
  </button>

  <!-- Greeting -->
  <div class="c-greeting">
    <div class="c-avatar" id="dashAvatar">?</div>
    <div>
      <div class="c-greeting-name"  id="dashName">—</div>
      <div class="c-greeting-meta"  id="dashCard">—</div>
      <div class="c-greeting-since" id="dashSince">—</div>
    </div>
  </div>

  <!-- Points hero -->
  <div class="c-points-hero" id="pointsHero">
    <div class="c-points-label"><i class="bi bi-star-fill me-1"></i>Points Balance</div>
    <div class="c-points-number" id="dashPoints">0</div>
    <div class="c-points-sub"    id="dashPointsSub">—</div>
    <div class="c-points-expiry" id="dashExpiry"></div>
    <div class="c-redeem-box">
      <i class="bi bi-gift-fill"></i>
      <div class="flex-grow-1">
        <div class="c-redeem-label">Redemption Value</div>
        <div class="c-redeem-value" id="dashRedeemVal">₱0.00</div>
        <div class="c-redeem-note"  id="dashRedeemNote">—</div>
      </div>
      <div id="dashRedeemBadge"></div>
    </div>
  </div>

  <!-- Stat pills -->
  <div class="c-stats-row">
    <div class="c-stat-pill">
      <div class="c-stat-pill-val"   id="statSpend">₱0</div>
      <div class="c-stat-pill-label">Total Spend</div>
    </div>
    <div class="c-stat-pill">
      <div class="c-stat-pill-val"   id="statEarned">0</div>
      <div class="c-stat-pill-label">Pts Earned</div>
    </div>
    <div class="c-stat-pill">
      <div class="c-stat-pill-val"   id="statRedeemed">0</div>
      <div class="c-stat-pill-label">Pts Redeemed</div>
    </div>
  </div>

  <!-- Digital card -->
  <div class="c-section-title"><i class="bi bi-credit-card me-1"></i>Your Loyalty Card</div>
  <div class="c-surface" style="padding:1rem;text-align:center">
    <div id="digitalCardWrap"></div>
    <button class="c-btn c-btn-outline c-btn-auto c-btn-sm mt-3" id="btnShowQr">
      <i class="bi bi-qr-code me-2"></i>Show QR Code
    </button>
  </div>

  <!-- Recent transactions -->
  <div class="c-section-title"><i class="bi bi-clock-history me-1"></i>Recent Transactions</div>
  <div class="c-txn-list" id="txnList"></div>

  <div class="c-footer">
    <?= htmlspecialchars($storeName) ?> Loyalty Program &mdash; Points are non-transferable.
  </div>
</div>

<!-- ── QR Modal ───────────────────────────── -->
<div id="qrModal" class="qr-modal" style="display:none">
  <div class="qr-modal-card">
    <h6><i class="bi bi-qr-code me-2 text-primary"></i>Your Card QR Code</h6>
    <div id="qrModalCode" style="display:flex;justify-content:center;margin:1rem 0"></div>
    <code id="qrModalCardCode"></code>
    <button class="c-btn c-btn-primary mt-3" id="btnCloseQr">
      <i class="bi bi-x-lg me-2"></i>Close
    </button>
  </div>
</div>

<!-- html5-qrcode + shared MobileScanner helper -->
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script src="../mobile/assets/mobile.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
/* ══════════════════════════════════════════
   Customer Rewards Portal JS
   Step flow mirrors mobile/scan.php
══════════════════════════════════════════ */
var BASE_URL      = <?= json_encode(BASE_URL) ?>;
var currentCard   = '';
var currentDesign = null;

/* ── Helpers ─────────────────────────────── */
function showAlert(msg) {
    document.getElementById('lookupAlertMsg').innerHTML = msg;
    document.getElementById('lookupAlert').style.display = 'flex';
}
function hideAlert() {
    document.getElementById('lookupAlert').style.display = 'none';
}
function resetScanner() {
    MobileScanner.stop();
    document.getElementById('btnScanStart').classList.remove('d-none');
    document.getElementById('btnScanStop').classList.add('d-none');
    document.getElementById('cScanLine').style.display  = 'none';
    document.getElementById('cScanHint').textContent    = 'Tap Start Camera to scan';
}

/* ── Step 1 — Camera ─────────────────────── */
document.getElementById('btnScanStart').addEventListener('click', function () {
    this.classList.add('d-none');
    document.getElementById('btnScanStop').classList.remove('d-none');
    document.getElementById('cScanLine').style.display  = 'block';
    document.getElementById('cScanHint').textContent    = 'Align QR code or barcode in the frame';
    hideAlert();

    MobileScanner.start('c-qr-scan',
        function (code) {                               // success
            resetScanner();
            document.getElementById('cardInput').value = code.toUpperCase();
            doLookup(code.toUpperCase());
        },
        function (err) {                                // error
            resetScanner();
            showAlert(err);
        }
    );
});

document.getElementById('btnScanStop').addEventListener('click', function () {
    resetScanner();
});

/* ── Step 1 — Manual entry ───────────────── */
document.getElementById('btnLookup').addEventListener('click', function () {
    var code = document.getElementById('cardInput').value.trim().toUpperCase();
    if (!code) return showAlert('Please enter your card number.');
    doLookup(code);
});

document.getElementById('cardInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') document.getElementById('btnLookup').click();
});

// Auto-lookup if card pre-filled from URL ?card=
(function () {
    var pre = document.getElementById('cardInput').value.trim();
    if (pre) doLookup(pre);
})();

/* ── Lookup ──────────────────────────────── */
function doLookup(code) {
    var btn = document.getElementById('btnLookup');
    btn.disabled    = true;
    btn.innerHTML   = '<span class="spinner-border spinner-border-sm me-2"></span>Checking…';
    hideAlert();

    $.ajax({
        url:      BASE_URL + '/customer/ajax/lookup.php',
        type:     'POST',
        data:     { card_code: code },
        dataType: 'json',
        success: function (res) {
            btn.disabled  = false;
            btn.innerHTML = '<i class="bi bi-search me-2"></i>Check My Rewards';
            if (res.success) {
                currentCard   = code;
                currentDesign = res.design;
                showStep2(res);
            } else {
                showAlert(res.error || 'Card not found.');
            }
        },
        error: function (xhr) {
            btn.disabled  = false;
            btn.innerHTML = '<i class="bi bi-search me-2"></i>Check My Rewards';
            var msg = 'Connection error. Please try again.';
            try { msg = JSON.parse(xhr.responseText).error || msg; } catch (e) {}
            showAlert(msg);
        }
    });
}

/* ── Card background helper ──────────────── */
function cardBgStyle(d) {
    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%);';
}

/* ── Build digital card HTML ─────────────── */
function buildDigitalCard(cardCode, design) {
    var d        = design || {};
    var bgStyle  = cardBgStyle(d);
    var txtColor = 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 store    = (d.store_name  || 'Rewards').toUpperCase();

    var h  = '<div class="reward-card" style="' + bgStyle + '">';
    if (shimmer) h += '<div class="card-shimmer-overlay"></div>';
    h += '<div class="card-circle-deco"></div>';
    h += '<div class="card-top">';
    h += '  <div class="card-top-qr" id="custTopQrWrap"></div>';
    h += '  <div class="card-store-name" style="color:' + txtColor + ';opacity:.85;">' + store + '</div>';
    h += '  <i class="bi bi-' + icon + '" style="color:' + accent + ';font-size:1.1rem;"></i>';
    h += '</div>';
    h += '<div class="card-stripe"><svg id="custBarcode"></svg></div>';
    h += '<div class="card-bottom">';
    h += '  <div class="card-info">';
    h += '    <div class="card-label"    style="color:' + txtColor + ';opacity:.6;">' + label + '</div>';
    h += '    <div class="card-number"   style="color:' + txtColor + ';">' + cardCode + '</div>';
    h += '    <div class="card-validity" style="color:' + txtColor + ';opacity:.6;">' + subtitle + '</div>';
    h += '  </div>';
    h += '  <div class="card-qr-wrap" id="custQrWrap"></div>';
    h += '</div></div>';
    return h;
}

function renderCardCodes(cardCode, design) {
    var d         = design || {};
    var lineColor = d.text_color   || '#ffffff';
    var qrDark    = d.accent_color || '#1e3a8a';

    // Top-left QR — uses card_qr_text setting; falls back to card code if blank
    var topQrText = (d.card_qr_text && d.card_qr_text.trim()) ? d.card_qr_text.trim() : cardCode;
    var topQrEl   = document.getElementById('custTopQrWrap');
    if (topQrEl) {
        topQrEl.innerHTML = '';
        try {
            new QRCode(topQrEl, {
                text:         topQrText,
                width:        46, height:46,
                colorDark:    qrDark,
                colorLight:   'rgba(255,255,255,0.85)',
                correctLevel: QRCode.CorrectLevel.M
            });
        } catch (e) {}
    }

    // Middle barcode — always the card code
    try {
        JsBarcode('#custBarcode', cardCode, {
            format:'CODE128', lineColor:lineColor, background:'transparent',
            width:1.4, height:32, displayValue:false
        });
    } catch (e) {}

    // Bottom-right QR — always the card code
    var qrEl = document.getElementById('custQrWrap');
    if (qrEl) {
        qrEl.innerHTML = '';
        try {
            new QRCode(qrEl, { text:cardCode, width:64, height:64,
                colorDark:qrDark, colorLight:'#ffffff', correctLevel:QRCode.CorrectLevel.M });
        } catch (e) {}
    }
}

/* ── Step 2 — Render rewards dashboard ───── */
function showStep2(res) {
    var m = res.member;
    var d = res.design || {};

    // Greeting
    document.getElementById('dashAvatar').textContent = m.initials || '?';
    document.getElementById('dashName').textContent   = m.name;
    document.getElementById('dashCard').textContent   = m.card_code;
    document.getElementById('dashSince').textContent  = m.registered_at
        ? 'Member since ' + new Date(m.registered_at).toLocaleDateString('en', {year:'numeric', month:'long'})
        : 'Member';

    // Points hero gradient
    var hero = document.getElementById('pointsHero');
    hero.setAttribute('style',
        cardBgStyle(d) +
        'border-radius:16px;padding:1.5rem 1.25rem;color:#fff;margin-bottom:1rem;position:relative;overflow:hidden;'
    );

    // Points
    document.getElementById('dashPoints').textContent    = Number(res.balance).toLocaleString();
    document.getElementById('dashPointsSub').textContent =
        res.balance === 1 ? '1 loyalty point' : Number(res.balance).toLocaleString() + ' loyalty points';
    document.getElementById('dashExpiry').textContent    = res.expiry_note || '';

    // Redeem value
    document.getElementById('dashRedeemVal').textContent  = '₱' + parseFloat(res.redeem_value).toLocaleString('en', {minimumFractionDigits:2});
    document.getElementById('dashRedeemNote').textContent = res.can_redeem
        ? 'Ready to redeem! Visit the store.'
        : 'Need ' + res.min_redeem + ' pts minimum to redeem.';
    document.getElementById('dashRedeemBadge').innerHTML = res.can_redeem
        ? '<span style="background:rgba(255,255,255,.25);border-radius:99px;padding:4px 10px;font-size:.7rem;font-weight:700;white-space:nowrap">✓ Ready</span>'
        : '';

    // Stats
    var s = res.stats;
    document.getElementById('statSpend').textContent    = '₱' + Math.round(parseFloat(s.total_spend)).toLocaleString();
    document.getElementById('statEarned').textContent   = Number(s.total_earned).toLocaleString();
    document.getElementById('statRedeemed').textContent = Number(s.total_redeemed).toLocaleString();

    // Digital card
    var wrap = document.getElementById('digitalCardWrap');
    wrap.innerHTML = buildDigitalCard(m.card_code, d);
    setTimeout(function () { renderCardCodes(m.card_code, d); }, 100);

    // Transactions
    var txnList = document.getElementById('txnList');
    if (!res.transactions || !res.transactions.length) {
        txnList.innerHTML = '<div class="c-empty"><i class="bi bi-receipt"></i>No transactions yet.</div>';
    } else {
        txnList.innerHTML = res.transactions.map(function (t) {
            var isEarn  = t.type === 'earn';
            var icon    = isEarn ? 'plus-circle' : 'gift';
            var pts     = (isEarn ? '+' : '-') + Number(t.points).toLocaleString() + ' pts';
            var pClass  = isEarn ? 'earn-pts' : 'redeem-pts';
            var note    = isEarn
                ? (t.amount > 0 ? '₱' + parseFloat(t.amount).toLocaleString('en', {minimumFractionDigits:2}) + ' purchase' : 'Earn')
                : (t.notes || 'Points redeemed');
            var date    = new Date(t.created_at).toLocaleDateString('en', {month:'short', day:'numeric', year:'numeric'});
            return '<div class="c-txn-item">'
                + '<div class="c-txn-icon ' + t.type + '"><i class="bi bi-' + icon + '"></i></div>'
                + '<div class="flex-grow-1 min-width-0">'
                + '<div class="c-txn-name">' + (isEarn ? 'Purchase' : 'Redemption') + '</div>'
                + '<div class="c-txn-note text-truncate">' + note + '</div>'
                + '</div>'
                + '<div class="c-txn-right">'
                + '<div class="c-txn-pts ' + pClass + '">' + pts + '</div>'
                + '<div class="c-txn-date">' + date + '</div>'
                + '</div></div>';
        }).join('');
    }

    // Switch screens
    document.getElementById('step1').style.display = 'none';
    document.getElementById('step2').style.display = 'block';
    window.scrollTo(0, 0);
}

/* ── Back to Step 1 ──────────────────────── */
document.getElementById('btnBack').addEventListener('click', function () {
    resetScanner();
    document.getElementById('step2').style.display = 'none';
    document.getElementById('step1').style.display = 'block';
    document.getElementById('cardInput').value = '';
    hideAlert();
    window.scrollTo(0, 0);
});

/* ── QR Modal ────────────────────────────── */
document.getElementById('btnShowQr').addEventListener('click', function () {
    var modal   = document.getElementById('qrModal');
    var codeDiv = document.getElementById('qrModalCode');
    codeDiv.innerHTML = '';
    document.getElementById('qrModalCardCode').textContent = currentCard;
    var d = currentDesign || {};
    try {
        new QRCode(codeDiv, {
            text:         currentCard,
            width:        200, height:200,
            colorDark:    d.accent_color || '#1e3a8a',
            colorLight:   '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    } catch (e) {}
    modal.style.display = 'flex';
});

document.getElementById('btnCloseQr').addEventListener('click', function () {
    document.getElementById('qrModal').style.display = 'none';
});
document.getElementById('qrModal').addEventListener('click', function (e) {
    if (e.target === this) this.style.display = 'none';
});
</script>
</body>
</html>
