<?php
$mobileTitle = 'Redeem Points';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
$minRedeem   = (int)  getSetting('min_redeem',       50);
$pointPeso   = (float)getSetting('point_peso_value',  1);
$prefillCard = trim($_GET['card'] ?? '');
include __DIR__ . '/includes/m_header.php';
?>

<!-- STEP 1: Scan -->
<div id="r-step1">
  <div class="m-section-title">Scan Member Card</div>

  <div class="m-card mb-3">
    <div class="m-scanner-wrap">
      <div id="m-qr-redeem"></div>
      <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
      <div class="scan-line" id="redeemScanLine" style="display:none"></div>
      <div class="scanner-hint" id="redeemScanHint">Tap Start Camera to scan card</div>
    </div>
    <div style="padding:.75rem 1rem">
      <button class="m-btn m-btn-warning mb-2" id="btnRedeemStart">
        <i class="bi bi-camera-video me-2"></i>Start Camera
      </button>
      <button class="m-btn m-btn-danger mb-2 d-none" id="btnRedeemStop">
        <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 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="redeemCardInput" placeholder="YYYY-MM-DD-####"
               value="<?= e($prefillCard) ?>" style="font-family:monospace">
      </div>
      <button class="m-btn m-btn-outline" id="btnRedeemManual">
        <i class="bi bi-search me-2"></i>Look Up
      </button>
    </div>
  </div>
  <div id="redeemAlert" style="display:none"></div>
</div>

<!-- STEP 2: Redeem -->
<div id="r-step2" style="display:none">
  <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="r2Name">—</div>
      <div class="m-member-card" id="r2Card">—</div>
      <div class="m-member-points">
        <span class="m-member-pts-val" id="r2Points">0</span>
        <span class="m-member-pts-label">available</span>
      </div>
    </div>
  </div>

  <div class="m-section-title">Enter Points to Redeem</div>
  <div class="m-card mb-3">
    <div class="m-card-body">
      <label class="m-input-label">Points (min <?= number_format($minRedeem) ?>)</label>
      <div class="m-input-group">
        <i class="bi bi-star-fill text-warning"></i>
        <input type="number" id="redeemPoints" placeholder="0" min="<?= $minRedeem ?>"
               step="1" inputmode="numeric" class="m-input-lg">
      </div>

      <!-- Peso value preview -->
      <div class="m-points-box" style="background:linear-gradient(135deg,#fffbeb,#fef3c7);border-color:#f59e0b">
        <div class="text-muted small mb-1">Discount Value</div>
        <div class="m-points-number" style="color:#d97706" id="redeemPesoPreview">₱0.00</div>
        <div class="text-muted small mt-1" id="redeemNote">Enter points 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="redeemNotes" placeholder="Reason for redemption">
      </div>
    </div>
  </div>

  <input type="hidden" id="redeemCardCode">
  <button class="m-btn m-btn-warning mb-2" id="btnDoRedeem" disabled>
    <i class="bi bi-gift me-2"></i>Redeem Points
  </button>
  <button class="m-btn m-btn-outline" id="btnRedeemBack">
    <i class="bi bi-arrow-left me-2"></i>Back
  </button>
</div>

<?php
$jsBaseUrl   = json_encode(BASE_URL);
$jsMin       = (int)$minRedeem;
$jsPointPeso = (float)$pointPeso;
$jsPrefill   = json_encode($prefillCard);
$mExtraJS = '<script>var BASE_URL=' . $jsBaseUrl . ';var MIN_REDEEM=' . $jsMin . ';var POINT_PESO=' . $jsPointPeso . ';var PREFILL_CARD=' . $jsPrefill . ';</script>' . <<<'ENDJS'
<script>
/* ── Camera start ─────────────────────────────────────── */
document.getElementById('btnRedeemStart').addEventListener('click', function () {
    this.classList.add('d-none');
    document.getElementById('btnRedeemStop').classList.remove('d-none');
    document.getElementById('redeemScanLine').style.display = 'block';
    document.getElementById('redeemScanHint').textContent   = 'Align QR code or barcode in the frame';
    mHideAlert('redeemAlert');
    MobileScanner.start('m-qr-redeem',
        function (code) {
            document.getElementById('btnRedeemStart').classList.remove('d-none');
            document.getElementById('btnRedeemStop').classList.add('d-none');
            document.getElementById('redeemScanLine').style.display = 'none';
            document.getElementById('redeemCardInput').value = code;
            lookupMemberRedeem(code);
        },
        function (err) {
            document.getElementById('btnRedeemStart').classList.remove('d-none');
            document.getElementById('btnRedeemStop').classList.add('d-none');
            document.getElementById('redeemScanLine').style.display = 'none';
            document.getElementById('redeemScanHint').textContent   = 'Tap Start Camera to scan card';
            mShowAlert('redeemAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});

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

/* ── Manual lookup ────────────────────────────────────── */
document.getElementById('btnRedeemManual').addEventListener('click', function () {
    var code = document.getElementById('redeemCardInput').value.trim();
    if (!code) return mShowAlert('redeemAlert', 'warning', 'Enter a card code.');
    lookupMemberRedeem(code);
});
document.getElementById('redeemCardInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') document.getElementById('btnRedeemManual').click();
});
if (PREFILL_CARD) lookupMemberRedeem(PREFILL_CARD);

function lookupMemberRedeem(code) {
    mShowAlert('redeemAlert', '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('redeemAlert', 'danger', '<i class="bi bi-slash-circle me-1"></i><strong>Card deactivated.</strong> Cannot be used for redemptions.');
        } else if (res.success && res.member.name) {
            mHideAlert('redeemAlert');
            document.getElementById('r-step1').style.display = 'none';
            document.getElementById('r-step2').style.display = 'block';
            document.getElementById('r2Name').textContent    = res.member.name;
            document.getElementById('r2Card').textContent    = code;
            document.getElementById('r2Points').textContent  = Number(res.member.points).toLocaleString();
            document.getElementById('redeemCardCode').value  = code;
            document.getElementById('redeemPoints').max      = res.member.points;
            document.getElementById('redeemPoints').focus();
            MobileScanner.stop();
        } else {
            mShowAlert('redeemAlert', 'danger', res.error || 'Not found / not registered.');
        }
    });
}

/* ── Live peso preview ────────────────────────────────── */
document.getElementById('redeemPoints').addEventListener('input', function () {
    var pts  = parseInt(this.value) || 0;
    var peso = (pts * POINT_PESO).toFixed(2);
    document.getElementById('redeemPesoPreview').textContent = '\u20B1' + parseFloat(peso).toLocaleString('en', { minimumFractionDigits: 2 });
    document.getElementById('redeemNote').textContent        = pts + ' pts \u00d7 \u20B1' + POINT_PESO + ' per point';
    document.getElementById('btnDoRedeem').disabled          = (pts < MIN_REDEEM);
});

/* ── Redeem ───────────────────────────────────────────── */
document.getElementById('btnDoRedeem').addEventListener('click', function () {
    var btn   = this;
    var pts   = parseInt(document.getElementById('redeemPoints').value) || 0;
    var code  = document.getElementById('redeemCardCode').value;
    var notes = document.getElementById('redeemNotes').value;
    if (pts < MIN_REDEEM) return mShowAlert('redeemAlert', 'warning', 'Minimum ' + MIN_REDEEM + ' points required.');
    mBtnLoading(btn, true);
    mAjaxPost(BASE_URL + '/ajax/redeem_points.php',
        { card_code: code, points: pts, notes: notes },
        function (res) {
            mBtnLoading(btn, false);
            if (res.success) {
                mShowSuccess({
                    icon: 'gift-fill',
                    iconClass: 'bg-warning-subtle text-warning',
                    title: 'Points Redeemed!',
                    lines: [
                        { label: 'Points Used:', value: res.points_redeemed },
                        { label: 'Discount Value:', value: '\u20B1' + parseFloat(res.peso_value).toFixed(2) },
                        { label: 'Remaining Balance:', value: res.new_balance + ' pts' }
                    ],
                    btnText: 'Done',
                    onClose: function () {
                        document.getElementById('r-step2').style.display = 'none';
                        document.getElementById('r-step1').style.display = 'block';
                        document.getElementById('redeemPoints').value = '';
                        document.getElementById('redeemNotes').value  = '';
                        MobileScanner.reset();
                    }
                });
            } else {
                mShowAlert('redeemAlert', 'danger', res.error || 'Redemption failed.');
            }
        },
        function (err) {
            mBtnLoading(btn, false);
            mShowAlert('redeemAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});

document.getElementById('btnRedeemBack').addEventListener('click', function () {
    document.getElementById('r-step2').style.display = 'none';
    document.getElementById('r-step1').style.display = 'block';
    document.getElementById('redeemPoints').value = '';
    MobileScanner.reset();
});
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
