<?php
$pageTitle = 'Purchase Scanner';
require_once __DIR__ . '/includes/header.php';
$pesoPerPoint = getSetting('peso_per_point', 100);
?>

<div class="row g-4">

  <!-- Left: Scanner -->
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header bg-success text-white">
        <i class="bi bi-bag-check me-2"></i>Scan Member Card
      </div>
      <div class="card-body">
        <ul class="nav nav-tabs mb-3" id="scanTabs2">
          <li class="nav-item">
            <a class="nav-link active" href="#" data-tab2="webcam">
              <i class="bi bi-camera-video me-1"></i>Webcam
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#" data-tab2="manual">
              <i class="bi bi-keyboard me-1"></i>Manual
            </a>
          </li>
        </ul>

        <div id="tab2-webcam">
          <div id="qr-reader2" style="width:100%; min-height:200px; background:#000; border-radius:8px; overflow:hidden;"></div>
          <div class="d-grid gap-2 mt-2">
            <button class="btn btn-success" id="btnStartScan2">
              <i class="bi bi-camera-video me-2"></i>Start Camera
            </button>
            <button class="btn btn-danger d-none" id="btnStopScan2">
              <i class="bi bi-stop-circle me-2"></i>Stop Camera
            </button>
          </div>
        </div>

        <div id="tab2-manual" class="d-none">
          <div class="mb-2">
            <label class="form-label fw-semibold small">Card Code</label>
            <input type="text" id="manualCard2" class="form-control font-monospace"
                   placeholder="e.g. 2024-01-15-0001">
          </div>
          <button class="btn btn-success w-100" id="btnManualLookup2">
            <i class="bi bi-search me-2"></i>Look Up
          </button>
        </div>

        <div id="scanMsg2" class="alert mt-3 d-none"></div>
      </div>
    </div>

    <!-- Points calculator hint -->
    <div class="card shadow-sm mt-3">
      <div class="card-body p-3">
        <h6 class="fw-bold mb-2"><i class="bi bi-calculator me-1 text-primary"></i>Points Rate</h6>
        <div class="d-flex justify-content-between align-items-center">
          <span class="text-muted small">₱<?= number_format($pesoPerPoint, 0) ?> spent</span>
          <i class="bi bi-arrow-right text-muted"></i>
          <span class="badge bg-warning text-dark">1 Point</span>
        </div>
        <div class="progress mt-2" style="height:6px">
          <div class="progress-bar bg-warning" id="ptProgressBar" style="width:0%"></div>
        </div>
        <div class="text-muted small mt-1" id="ptProgressLabel">Enter amount to see preview</div>
      </div>
    </div>
  </div>

  <!-- Right: Purchase Form -->
  <div class="col-lg-7">

    <!-- Member info card -->
    <div class="card shadow-sm mb-3 d-none" id="memberInfoCard">
      <div class="card-body">
        <div class="d-flex align-items-center gap-3">
          <div class="member-avatar">
            <i class="bi bi-person-circle text-primary" style="font-size:3rem"></i>
          </div>
          <div class="flex-grow-1">
            <h5 class="mb-0 fw-bold" id="infoName">—</h5>
            <div class="text-muted small" id="infoPhone">—</div>
            <div class="text-muted small font-monospace" id="infoCard">—</div>
          </div>
          <div class="text-end">
            <div class="fw-bold fs-5 text-warning" id="infoPoints">0 pts</div>
            <div class="text-muted small">Current Balance</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Purchase form -->
    <div class="card shadow-sm">
      <div class="card-header bg-white">
        <i class="bi bi-receipt me-2 text-success"></i>Process Purchase
      </div>
      <div class="card-body">
        <form id="purchaseForm">
          <input type="hidden" id="pCardCode" name="card_code">

          <div class="mb-3">
            <label class="form-label fw-semibold">Spending Amount (₱) <span class="text-danger">*</span></label>
            <div class="input-group input-group-lg">
              <span class="input-group-text fw-bold">₱</span>
              <input type="number" name="amount" id="pAmount" class="form-control"
                     placeholder="0.00" min="0.01" step="0.01" required>
            </div>
          </div>

          <!-- Points preview -->
          <div class="points-preview mb-4 p-3 rounded-3 bg-success-subtle text-center" id="pointsPreview">
            <div class="text-muted small">Points to Earn</div>
            <div class="fw-bold fs-2 text-success" id="previewPoints">—</div>
            <div class="text-muted small" id="previewPointsNote">Enter amount above</div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Notes (optional)</label>
            <input type="text" name="notes" class="form-control" placeholder="e.g. Grocery purchase">
          </div>

          <div class="d-grid">
            <button type="submit" class="btn btn-success btn-lg fw-bold" id="btnProcess" disabled>
              <i class="bi bi-check2-circle me-2"></i>Process Purchase & Earn Points
            </button>
          </div>
        </form>

        <div id="processResult" class="alert mt-3 d-none"></div>
      </div>
    </div>

  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0">
      <div class="modal-body text-center p-5">
        <div class="mb-3">
          <i class="bi bi-check-circle-fill text-success" style="font-size:4rem"></i>
        </div>
        <h4 class="fw-bold">Purchase Processed!</h4>
        <p class="text-muted" id="modalMsg">—</p>
        <div class="d-flex justify-content-center gap-3">
          <div class="text-center">
            <div class="fw-bold fs-3 text-success" id="modalPoints">0</div>
            <div class="small text-muted">Points Earned</div>
          </div>
          <div class="vr"></div>
          <div class="text-center">
            <div class="fw-bold fs-3 text-warning" id="modalBalance">0</div>
            <div class="small text-muted">New Balance</div>
          </div>
        </div>
        <button class="btn btn-primary mt-4" data-bs-dismiss="modal">
          <i class="bi bi-arrow-repeat me-2"></i>Next Customer
        </button>
      </div>
    </div>
  </div>
</div>

<?php
// Bug Fix #1: inject PHP value before the nowdoc, nowdoc handles the static JS
$jsConst = '<script>'
    . 'const BASE_URL=' . json_encode(BASE_URL) . ';'
    . 'const PESO_PER_POINT=' . (int)$pesoPerPoint . ';'
    . '</script>';
$extraJS  = $jsConst . <<<'ENDJS'
<script>
let html5Scanner2 = null, scanning2 = false, scannedOnce2 = false;
let currentMemberId = null;

// ── Tab switching ─────────────────────────────────────────
document.querySelectorAll('[data-tab2]').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        document.querySelectorAll('[data-tab2]').forEach(function(l) { l.classList.remove('active'); });
        link.classList.add('active');
        document.getElementById('tab2-webcam').classList.toggle('d-none', link.dataset.tab2 !== 'webcam');
        document.getElementById('tab2-manual').classList.toggle('d-none', link.dataset.tab2 !== 'manual');
        if (link.dataset.tab2 !== 'webcam' && scanning2) stopScanner2();
    });
});

// ── Scanner ───────────────────────────────────────────────
document.getElementById('btnStartScan2').addEventListener('click', startScanner2);
document.getElementById('btnStopScan2').addEventListener('click', stopScanner2);

function startScanner2() {
    scannedOnce2 = false;
    html5Scanner2 = new Html5Qrcode('qr-reader2');
    html5Scanner2.start(
        { facingMode: 'environment' },
        { fps: 10, qrbox: { width: 220, height: 80 } },
        function(code) { if (!scannedOnce2) { scannedOnce2 = true; stopScanner2(); lookupMember(code); } },
        function() {}
    ).then(function() {
        scanning2 = true;
        document.getElementById('btnStartScan2').classList.add('d-none');
        document.getElementById('btnStopScan2').classList.remove('d-none');
    }).catch(function(err) { showMsg2('danger', 'Camera error: ' + err); });
}

function stopScanner2() {
    if (html5Scanner2) { html5Scanner2.stop().then(function() { html5Scanner2.clear(); html5Scanner2 = null; }); }
    scanning2 = false;
    document.getElementById('btnStartScan2').classList.remove('d-none');
    document.getElementById('btnStopScan2').classList.add('d-none');
}

document.getElementById('btnManualLookup2').addEventListener('click', function() {
    var code = document.getElementById('manualCard2').value.trim();
    if (!code) return showMsg2('warning', 'Enter a card code first.');
    lookupMember(code);
});
document.getElementById('manualCard2').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') document.getElementById('btnManualLookup2').click();
});

// ── Lookup member ─────────────────────────────────────────
function lookupMember(code) {
    showMsg2('info', '<span class="spinner-border spinner-border-sm me-2"></span>Looking up member&hellip;');
    $.get(BASE_URL + '/ajax/get_member.php', { card_code: code }, function(res) {
        if (res.success && res.member.name) {
            var m = res.member;
            currentMemberId = m.id;
            document.getElementById('pCardCode').value         = code;
            document.getElementById('infoName').textContent    = m.name;
            document.getElementById('infoPhone').textContent   = m.phone || '—';
            document.getElementById('infoCard').textContent    = code;
            document.getElementById('infoPoints').textContent  = Number(m.points).toLocaleString() + ' pts';
            document.getElementById('memberInfoCard').classList.remove('d-none');
            document.getElementById('btnProcess').disabled = false;
            showMsg2('success', '<i class="bi bi-check-circle me-2"></i>Member found: <strong>' + m.name + '</strong>');
        } else {
            showMsg2('danger', '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Member not found or not registered.'));
        }
    }, 'json');
}

// ── Live points preview ───────────────────────────────────
document.getElementById('pAmount').addEventListener('input', function() {
    var amt  = parseFloat(this.value) || 0;
    var pts  = Math.floor(amt / PESO_PER_POINT);
    var pct  = PESO_PER_POINT > 0 ? Math.min(100, (amt % PESO_PER_POINT) / PESO_PER_POINT * 100) : 0;
    var note = pts > 0
        ? '&#x20B1;' + amt.toLocaleString() + ' spend \u00f7 &#x20B1;' + PESO_PER_POINT
        : 'Minimum &#x20B1;' + PESO_PER_POINT;
    var lbl  = pts > 0
        ? '+' + pts + ' point' + (pts !== 1 ? 's' : '')
        : '&#x20B1;' + Math.max(0, PESO_PER_POINT - amt).toFixed(0) + ' more for 1 point';

    document.getElementById('previewPoints').textContent         = pts > 0 ? pts.toLocaleString() : '0';
    document.getElementById('previewPointsNote').innerHTML       = note;
    document.getElementById('ptProgressBar').style.width        = pct + '%';
    document.getElementById('ptProgressLabel').innerHTML        = lbl;
});

// ── Process purchase ──────────────────────────────────────
document.getElementById('purchaseForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var btn = document.getElementById('btnProcess');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing&hellip;';

    $.post(BASE_URL + '/ajax/process_purchase.php', $(this).serialize(), function(res) {
        if (res.success) {
            document.getElementById('modalMsg').textContent     = 'Purchase of \u20B1' + parseFloat($('#pAmount').val()).toFixed(2) + ' recorded.';
            document.getElementById('modalPoints').textContent  = res.points_earned;
            document.getElementById('modalBalance').textContent = res.new_balance;
            document.getElementById('infoPoints').textContent   = res.new_balance + ' pts';
            new bootstrap.Modal(document.getElementById('successModal')).show();
            document.getElementById('purchaseForm').reset();
            document.getElementById('previewPoints').textContent     = '—';
            document.getElementById('previewPointsNote').textContent = 'Enter amount above';
        } else {
            var el = document.getElementById('processResult');
            el.className = 'alert alert-danger';
            el.innerHTML = '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Error');
            el.classList.remove('d-none');
        }
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-check2-circle me-2"></i>Process Purchase & Earn Points';
    }, 'json');
});

// Reset on modal close
document.getElementById('successModal').addEventListener('hidden.bs.modal', function() {
    document.getElementById('memberInfoCard').classList.add('d-none');
    document.getElementById('btnProcess').disabled = true;
    document.getElementById('pCardCode').value     = '';
    document.getElementById('processResult').classList.add('d-none');
    document.getElementById('scanMsg2').classList.add('d-none');
    currentMemberId = null;
    scannedOnce2    = false;
});

function showMsg2(type, html) {
    var el = document.getElementById('scanMsg2');
    el.className = 'alert alert-' + type;
    el.innerHTML = html;
    el.classList.remove('d-none');
}
</script>
ENDJS;
require_once __DIR__ . '/includes/footer.php';
