<?php
$mobileTitle = 'Scan Card';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
include __DIR__ . '/includes/m_header.php';
?>

<div id="scan-step1">
  <div class="m-section-title">Step 1 — Scan Card</div>
  <div class="m-card mb-3">
    <div class="m-scanner-wrap">
      <div id="m-qr-scan"></div>
      <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
      <div class="scan-line" id="scanLine" style="display:none"></div>
      <div class="scanner-hint" id="scanHint">Tap Start to scan card</div>
    </div>
    <div style="padding:.75rem 1rem">
      <button class="m-btn m-btn-primary mb-2" id="btnScanStart">
        <i class="bi bi-camera-video me-2"></i>Start Camera
      </button>
      <button class="m-btn m-btn-danger mb-2 d-none" id="btnScanStop">
        <i class="bi bi-stop-circle me-2"></i>Stop
      </button>
    </div>
  </div>

  <div class="m-card mb-3">
    <div class="m-card-body">
      <div class="m-input-group">
        <i class="bi bi-credit-card"></i>
        <input type="text" id="scanCardInput" placeholder="YYYY-MM-DD-####"
               autocomplete="off" inputmode="text" style="font-family:monospace">
      </div>
      <button class="m-btn m-btn-outline" id="btnScanManual">
        <i class="bi bi-search me-2"></i>Look Up
      </button>
    </div>
  </div>
  <div id="scanAlert" style="display:none"></div>
</div>

<div id="scan-step2" style="display:none">
  <div class="d-flex align-items-center gap-2 mb-3">
    <div class="fw-bold small font-monospace" id="scanCardLabel"></div>
    <span class="badge" id="scanCardBadge">—</span>
  </div>
  <div class="m-section-title">Step 2 — Member Info</div>
  <div class="m-card mb-3">
    <div class="m-card-body">
      <div class="m-member-banner">
        <div class="m-member-avatar"><i class="bi bi-person-fill"></i></div>
        <div class="flex-grow-1 min-width-0">
          <div class="m-member-name text-truncate" id="scanMemberName">—</div>
          <div class="m-member-card" id="scanMemberCard">—</div>
          <div class="small mt-1 text-truncate" id="scanMemberPhone" style="opacity:.7">—</div>
          <div class="m-member-points">
            <span class="m-member-pts-val" id="scanMemberPoints">0</span>
            <span class="m-member-pts-label">points</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="d-flex gap-2 mb-2">
    <a class="m-btn m-btn-success flex-grow-1" id="btnGoPurchase" href="#">
      <i class="bi bi-bag-check me-1"></i>Purchase
    </a>
    <a class="m-btn m-btn-warning flex-grow-1" id="btnGoRedeem" href="#">
      <i class="bi bi-gift me-1"></i>Redeem
    </a>
  </div>
  <button class="m-btn m-btn-outline" id="btnScanBack">
    <i class="bi bi-arrow-repeat me-2"></i>Scan Another Card
  </button>
  <div id="scanStep2Alert" style="display:none;margin-top:1rem"></div>
</div>

<?php
$jsBaseUrl = json_encode(BASE_URL);
$mExtraJS  = '<script>var BASE_URL=' . $jsBaseUrl . ';</script>' . <<<'ENDJS'
<script>
document.getElementById('btnScanStart').addEventListener('click', function () {
    this.classList.add('d-none');
    document.getElementById('btnScanStop').classList.remove('d-none');
    document.getElementById('scanLine').style.display = 'block';
    document.getElementById('scanHint').textContent   = 'Align QR code or barcode in the frame';
    mHideAlert('scanAlert');
    MobileScanner.start('m-qr-scan',
        function (code) {
            document.getElementById('btnScanStart').classList.remove('d-none');
            document.getElementById('btnScanStop').classList.add('d-none');
            document.getElementById('scanLine').style.display = 'none';
            document.getElementById('scanCardInput').value    = code;
            lookupCard(code);
        },
        function (err) {
            document.getElementById('btnScanStart').classList.remove('d-none');
            document.getElementById('btnScanStop').classList.add('d-none');
            document.getElementById('scanLine').style.display = 'none';
            document.getElementById('scanHint').textContent   = 'Tap Start to scan card';
            mShowAlert('scanAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});

document.getElementById('btnScanStop').addEventListener('click', function () {
    MobileScanner.stop();
    document.getElementById('btnScanStart').classList.remove('d-none');
    this.classList.add('d-none');
    document.getElementById('scanLine').style.display = 'none';
    document.getElementById('scanHint').textContent   = 'Tap Start to scan card';
});

document.getElementById('btnScanManual').addEventListener('click', function () {
    var code = document.getElementById('scanCardInput').value.trim();
    if (!code) return mShowAlert('scanAlert', 'warning', 'Enter a card code.');
    lookupCard(code);
});

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

function lookupCard(code) {
    mShowAlert('scanAlert', 'info', '<span class="spinner-border spinner-border-sm me-2"></span>Looking up\u2026');
    mAjaxGet(BASE_URL + '/ajax/get_member.php', { card_code: code }, function (res) {
        if (res.success) {
            mHideAlert('scanAlert');
            var m    = res.member;
            var base = BASE_URL + '/mobile/';
            var isReg = !!m.name;

            document.getElementById('scan-step1').style.display = 'none';
            document.getElementById('scan-step2').style.display = 'block';
            document.getElementById('scanCardLabel').textContent    = code;
            document.getElementById('scanMemberName').textContent   = m.name   || 'Unregistered';
            document.getElementById('scanMemberCard').textContent   = code;
            document.getElementById('scanMemberPhone').textContent  = m.phone  || '';
            document.getElementById('scanMemberPoints').textContent = Number(m.points || 0).toLocaleString();

            var badge = document.getElementById('scanCardBadge');

            // Show deactivated warning and block Purchase/Redeem
            if (m.deactivated) {
                badge.textContent = 'DEACTIVATED';
                badge.className   = 'badge bg-danger';
                document.getElementById('btnGoPurchase').href = '#';
                document.getElementById('btnGoRedeem').href   = '#';
                mShowAlert('scanStep2Alert', 'danger',
                    '<i class="bi bi-slash-circle me-1"></i>' +
                    '<strong>This card is deactivated.</strong> It cannot be used for purchases or redemptions. ' +
                    'Contact an administrator to reactivate.');
                MobileScanner.stop();
                return;
            }

            badge.textContent = isReg ? 'Registered' : 'Unregistered';
            badge.className   = 'badge ' + (isReg ? 'bg-success' : 'bg-secondary');

            if (isReg) {
                document.getElementById('btnGoPurchase').href = base + 'purchase.php?card=' + encodeURIComponent(code);
                document.getElementById('btnGoRedeem').href   = base + 'redeem.php?card='   + encodeURIComponent(code);
                mHideAlert('scanStep2Alert');
            } else {
                document.getElementById('btnGoPurchase').href = base + 'register.php?card=' + encodeURIComponent(code);
                document.getElementById('btnGoRedeem').href   = '#';
                mShowAlert('scanStep2Alert', 'warning', 'Card not registered. <a href="' + base + 'register.php?card=' + encodeURIComponent(code) + '" class="alert-link">Register member first \u2192</a>');
            }

            MobileScanner.stop();
        } else {
            mShowAlert('scanAlert', 'danger', res.error || 'Card not found. Generate and save card first.');
        }
    });
}

document.getElementById('btnScanBack').addEventListener('click', function () {
    document.getElementById('scan-step2').style.display = 'none';
    document.getElementById('scan-step1').style.display = 'block';
    document.getElementById('scanCardInput').value = '';
    mHideAlert('scanAlert');
    mHideAlert('scanStep2Alert');
    document.getElementById('scanHint').textContent = 'Tap Start to scan card';
    MobileScanner.reset();
});
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
