<?php
$mobileTitle = 'Purchase';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
$pesoPerPoint = (int) getSetting('peso_per_point', 100);
$prefillCard  = trim($_GET['card'] ?? '');
include __DIR__ . '/includes/m_header.php';
?>

<!-- Step indicator -->
<div class="d-flex align-items-center gap-2 mb-3">
  <div class="step-dot active" id="step1dot"></div>
  <div class="flex-grow-1" style="height:3px;background:#e2e8f0;border-radius:2px">
    <div id="stepBar" style="height:100%;width:0%;background:#0d6efd;border-radius:2px;transition:width .3s"></div>
  </div>
  <div class="step-dot" id="step2dot"></div>
</div>

<!-- STEP 1: Scan Card -->
<div id="step1">
  <div class="m-section-title">Step 1 — Scan or Enter Card</div>

  <div class="m-card mb-3">
    <div class="m-scanner-wrap">
      <div id="m-qr-purchase"></div>
      <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
      <div class="scan-line" id="purchaseScanLine" style="display:none"></div>
      <div class="scanner-hint" id="purchaseScanHint">Tap Start Camera to scan card</div>
    </div>
    <div style="padding:.75rem 1rem">
      <button class="m-btn m-btn-primary mb-2" id="btnPurchaseStart">
        <i class="bi bi-camera-video me-2"></i>Start Camera
      </button>
      <button class="m-btn m-btn-danger mb-2 d-none" id="btnPurchaseStop">
        <i class="bi bi-stop-circle me-2"></i>Stop
      </button>
    </div>
  </div>

  <div class="m-card mb-3">
    <div class="m-card-header"><i class="bi bi-keyboard text-secondary"></i>Manual Card Entry</div>
    <div class="m-card-body">
      <label class="m-input-label">Card Code</label>
      <div class="m-input-group">
        <i class="bi bi-credit-card"></i>
        <input type="text" id="purchaseCardInput" placeholder="YYYY-MM-DD-####"
               value="<?= e($prefillCard) ?>" style="font-family:monospace">
      </div>
      <button class="m-btn m-btn-outline" id="btnPurchaseManual">
        <i class="bi bi-search me-2"></i>Look Up
      </button>
    </div>
  </div>

  <div id="purchaseScanAlert" style="display:none"></div>
</div>

<!-- STEP 2: Enter Amount -->
<div id="step2" style="display:none">
  <!-- Member Banner -->
  <div class="m-member-banner mb-3">
    <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="p2Name">—</div>
      <div class="m-member-card" id="p2Card">—</div>
      <div class="m-member-points">
        <span class="m-member-pts-val" id="p2Points">0</span>
        <span class="m-member-pts-label">pts balance</span>
      </div>
    </div>
  </div>

  <div class="m-section-title">Step 2 — Enter Amount</div>
  <div class="m-card mb-3">
    <div class="m-card-body">
      <label class="m-input-label">Purchase Amount (₱)</label>
      <div class="m-input-group">
        <i class="bi bi-currency-exchange"></i>
        <input type="number" id="purchaseAmount" placeholder="0.00"
               min="0.01" step="0.01" inputmode="decimal" class="m-input-lg">
      </div>

      <!-- Points preview -->
      <div class="m-points-box" id="pointsBox">
        <div class="text-muted small mb-1">Points to Earn</div>
        <div class="m-points-number" id="pointsPreview">—</div>
        <div class="text-muted small mt-1" id="pointsNote">Enter amount above</div>
      </div>

      <label class="m-input-label">Notes (optional)</label>
      <div class="m-input-group">
        <i class="bi bi-chat-text"></i>
        <input type="text" id="purchaseNotes" placeholder="e.g. Grocery purchase">
      </div>
    </div>
  </div>

  <input type="hidden" id="purchaseCardCode">
  <button class="m-btn m-btn-success mb-2" id="btnProcessPurchase" disabled>
    <i class="bi bi-check2-circle me-2"></i>Process Purchase
  </button>
  <button class="m-btn m-btn-outline" id="btnPurchaseBack">
    <i class="bi bi-arrow-left me-2"></i>Scan Different Card
  </button>
</div>

<!-- Print area (hidden) -->
<div id="m-printArea"></div>

<?php
$jsBaseUrl    = json_encode(BASE_URL);
$jsPesoPoint  = (int)$pesoPerPoint;
$jsPrefill    = json_encode($prefillCard);
$mExtraJS = '<script>var BASE_URL=' . $jsBaseUrl . ';var PESO_PER_POINT=' . $jsPesoPoint . ';var PREFILL_CARD=' . $jsPrefill . ';</script>' . <<<'ENDJS'
<script>
var purchaseCard = null;

/* ── Camera start ─────────────────────────────────────── */
document.getElementById('btnPurchaseStart').addEventListener('click', function () {
    this.classList.add('d-none');
    document.getElementById('btnPurchaseStop').classList.remove('d-none');
    document.getElementById('purchaseScanLine').style.display = 'block';
    document.getElementById('purchaseScanHint').textContent   = 'Align QR code or barcode in the frame';
    mHideAlert('purchaseScanAlert');
    MobileScanner.start('m-qr-purchase',
        function (code) {
            document.getElementById('btnPurchaseStart').classList.remove('d-none');
            document.getElementById('btnPurchaseStop').classList.add('d-none');
            document.getElementById('purchaseScanLine').style.display = 'none';
            document.getElementById('purchaseCardInput').value = code;
            lookupMemberForPurchase(code);
        },
        function (err) {
            document.getElementById('btnPurchaseStart').classList.remove('d-none');
            document.getElementById('btnPurchaseStop').classList.add('d-none');
            document.getElementById('purchaseScanLine').style.display = 'none';
            document.getElementById('purchaseScanHint').textContent   = 'Tap Start Camera to scan card';
            mShowAlert('purchaseScanAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});

/* ── Camera stop ──────────────────────────────────────── */
document.getElementById('btnPurchaseStop').addEventListener('click', function () {
    MobileScanner.stop();
    document.getElementById('btnPurchaseStart').classList.remove('d-none');
    this.classList.add('d-none');
    document.getElementById('purchaseScanLine').style.display = 'none';
    document.getElementById('purchaseScanHint').textContent   = 'Tap Start Camera to scan card';
});

/* ── Manual lookup ────────────────────────────────────── */
document.getElementById('btnPurchaseManual').addEventListener('click', function () {
    var code = document.getElementById('purchaseCardInput').value.trim();
    if (!code) return mShowAlert('purchaseScanAlert', 'warning', 'Enter a card code.');
    lookupMemberForPurchase(code);
});
document.getElementById('purchaseCardInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') document.getElementById('btnPurchaseManual').click();
});

/* ── Prefill from URL ─────────────────────────────────── */
if (PREFILL_CARD) {
    lookupMemberForPurchase(PREFILL_CARD);
}

/* ── Member lookup ────────────────────────────────────── */
function lookupMemberForPurchase(code) {
    mShowAlert('purchaseScanAlert', '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 && res.member.deactivated) {
            mShowAlert('purchaseScanAlert', 'danger', '<i class="bi bi-slash-circle me-1"></i><strong>Card deactivated.</strong> Cannot be used for purchases.');
        } else if (res.success && res.member.name) {
            mHideAlert('purchaseScanAlert');
            purchaseCard = { code: code, member: res.member };
            goToStep2(code, res.member);
        } else if (res.success && !res.member.name) {
            mShowAlert('purchaseScanAlert', 'warning', 'Card not registered. <a href="' + BASE_URL + '/mobile/register.php?card=' + encodeURIComponent(code) + '" class="alert-link">Register now</a>');
        } else {
            mShowAlert('purchaseScanAlert', 'danger', res.error || 'Card not found.');
        }
    });
}

/* ── Go to Step 2 ─────────────────────────────────────── */
function goToStep2(code, member) {
    document.getElementById('step1').style.display = 'none';
    document.getElementById('step2').style.display = 'block';
    document.getElementById('stepBar').style.width = '100%';
    document.getElementById('step2dot').classList.add('active');
    document.getElementById('p2Name').textContent   = member.name;
    document.getElementById('p2Card').textContent   = code;
    document.getElementById('p2Points').textContent = Number(member.points).toLocaleString();
    document.getElementById('purchaseCardCode').value = code;
    document.getElementById('purchaseAmount').focus();
    MobileScanner.stop();
}

/* ── Back to Step 1 ───────────────────────────────────── */
document.getElementById('btnPurchaseBack').addEventListener('click', function () {
    document.getElementById('step1').style.display = 'block';
    document.getElementById('step2').style.display = 'none';
    document.getElementById('stepBar').style.width = '0%';
    document.getElementById('step2dot').classList.remove('active');
    document.getElementById('purchaseAmount').value = '';
    document.getElementById('pointsPreview').textContent = '\u2014';
    document.getElementById('pointsNote').textContent    = 'Enter amount above';
    document.getElementById('btnProcessPurchase').disabled = true;
    purchaseCard = null;
    MobileScanner.reset();
});

/* ── Live points preview ──────────────────────────────── */
document.getElementById('purchaseAmount').addEventListener('input', function () {
    var amt = parseFloat(this.value) || 0;
    var pts = Math.floor(amt / PESO_PER_POINT);
    document.getElementById('pointsPreview').textContent = pts > 0 ? pts.toLocaleString() : '0';
    document.getElementById('pointsNote').textContent    = pts > 0
        ? '\u20B1' + amt.toLocaleString() + ' \u00f7 \u20B1' + PESO_PER_POINT
        : 'Minimum \u20B1' + PESO_PER_POINT + ' to earn 1 point';
    document.getElementById('btnProcessPurchase').disabled = (amt <= 0);
});

/* ── Process Purchase ─────────────────────────────────── */
document.getElementById('btnProcessPurchase').addEventListener('click', function () {
    var btn    = this;
    var amount = parseFloat(document.getElementById('purchaseAmount').value) || 0;
    var code   = document.getElementById('purchaseCardCode').value;
    var notes  = document.getElementById('purchaseNotes').value;
    if (amount <= 0) return mShowAlert('purchaseScanAlert', 'warning', 'Enter a valid amount.');
    mBtnLoading(btn, true);
    mAjaxPost(BASE_URL + '/ajax/process_purchase.php',
        { card_code: code, amount: amount, notes: notes },
        function (res) {
            mBtnLoading(btn, false);
            if (res.success) {
                mShowSuccess({
                    icon: 'bag-check-fill',
                    iconClass: 'bg-success-subtle text-success',
                    title: 'Purchase Processed!',
                    lines: [
                        { label: 'Amount:', value: '\u20B1' + parseFloat(amount).toFixed(2) },
                        { label: 'Points Earned:', value: '+' + res.points_earned },
                        { label: 'New Balance:', value: res.new_balance + ' pts' }
                    ],
                    btnText: 'Next Customer',
                    onClose: function () {
                        document.getElementById('btnPurchaseBack').click();
                    }
                });
            } else {
                mShowAlert('purchaseScanAlert', 'danger', res.error || 'Processing failed.');
            }
        },
        function (err) {
            mBtnLoading(btn, false);
            mShowAlert('purchaseScanAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
