<?php
$pageTitle = 'Redeem Points';
require_once __DIR__ . '/includes/header.php';
$minRedeem     = (int) getSetting('min_redeem', 50);
$pointPesoVal  = (float) getSetting('point_peso_value', 1);
?>

<div class="row g-4">

  <!-- Scan -->
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header bg-warning text-dark">
        <i class="bi bi-gift me-2"></i>Scan Member Card
      </div>
      <div class="card-body">
        <ul class="nav nav-tabs mb-3" id="scanTabsR">
          <li class="nav-item">
            <a class="nav-link active" href="#" data-tabr="webcam"><i class="bi bi-camera-video me-1"></i>Webcam</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#" data-tabr="manual"><i class="bi bi-keyboard me-1"></i>Manual</a>
          </li>
        </ul>

        <div id="tabr-webcam">
          <div id="qr-reader-r" 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-warning" id="btnStartR">
              <i class="bi bi-camera-video me-2"></i>Start Camera
            </button>
            <button class="btn btn-danger d-none" id="btnStopR">
              <i class="bi bi-stop-circle me-2"></i>Stop
            </button>
          </div>
        </div>

        <div id="tabr-manual" class="d-none">
          <input type="text" id="manualCardR" class="form-control font-monospace mb-2" placeholder="Card code…">
          <button class="btn btn-warning w-100" id="btnLookupR">
            <i class="bi bi-search me-2"></i>Look Up
          </button>
        </div>

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

        <div class="card bg-light mt-3">
          <div class="card-body p-3 small">
            <h6 class="fw-bold mb-2"><i class="bi bi-info-circle me-1 text-warning"></i>Redemption Rules</h6>
            <ul class="mb-0 text-muted ps-3">
              <li>Minimum: <strong><?= number_format($minRedeem) ?> points</strong></li>
              <li>1 point = <strong>₱<?= number_format($pointPesoVal, 2) ?></strong> discount</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Redeem Form -->
  <div class="col-lg-7">
    <div class="card shadow-sm mb-3 d-none" id="memberInfoR">
      <div class="card-body">
        <div class="d-flex align-items-center gap-3">
          <i class="bi bi-person-circle text-warning" style="font-size:3rem"></i>
          <div class="flex-grow-1">
            <h5 class="mb-0 fw-bold" id="rInfoName">—</h5>
            <div class="text-muted small font-monospace" id="rInfoCard">—</div>
          </div>
          <div class="text-center">
            <div class="fw-bold fs-3 text-warning" id="rInfoPoints">0</div>
            <div class="small text-muted">Points Balance</div>
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-header bg-white">
        <i class="bi bi-gift me-2 text-warning"></i>Redeem Points
      </div>
      <div class="card-body">
        <form id="redeemForm">
          <input type="hidden" id="rCardCode" name="card_code">

          <div class="mb-3">
            <label class="form-label fw-semibold">Points to Redeem</label>
            <div class="input-group input-group-lg">
              <span class="input-group-text"><i class="bi bi-star-fill text-warning"></i></span>
              <input type="number" name="points" id="rPoints" class="form-control"
                     placeholder="e.g. 100" min="<?= $minRedeem ?>" step="1">
              <span class="input-group-text text-muted" id="rPesoPreview">= ₱0.00</span>
            </div>
            <div class="form-text">Minimum <?= number_format($minRedeem) ?> points</div>
          </div>

          <div class="mb-4">
            <label class="form-label fw-semibold small">Notes</label>
            <input type="text" name="notes" class="form-control" placeholder="Reason for redemption">
          </div>

          <div class="d-grid">
            <button type="submit" class="btn btn-warning btn-lg fw-bold" id="btnRedeem" disabled>
              <i class="bi bi-gift me-2"></i>Redeem Points
            </button>
          </div>
        </form>
        <div id="redeemMsg" class="alert mt-3 d-none"></div>
      </div>
    </div>
  </div>
</div>

<!-- Success modal -->
<div class="modal fade" id="redeemModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0">
      <div class="modal-body text-center p-5">
        <i class="bi bi-gift-fill text-warning" style="font-size:4rem"></i>
        <h4 class="fw-bold mt-3">Points Redeemed!</h4>
        <p class="text-muted" id="redeemModalMsg">—</p>
        <div class="d-flex justify-content-center gap-4">
          <div>
            <div class="fw-bold fs-3 text-warning" id="rModalPts">0</div>
            <div class="small text-muted">Points Used</div>
          </div>
          <div class="vr"></div>
          <div>
            <div class="fw-bold fs-3 text-success" id="rModalPeso">₱0</div>
            <div class="small text-muted">Discount Value</div>
          </div>
          <div class="vr"></div>
          <div>
            <div class="fw-bold fs-3 text-primary" id="rModalBalance">0</div>
            <div class="small text-muted">Remaining</div>
          </div>
        </div>
        <button class="btn btn-warning mt-4" data-bs-dismiss="modal">
          <i class="bi bi-arrow-repeat me-2"></i>Next
        </button>
      </div>
    </div>
  </div>
</div>

<?php
// Bug Fix #1: inject PHP values before nowdoc block
$extraJS = '<script>'
    . 'const BASE_URL=' . json_encode(BASE_URL) . ';'
    . 'const MIN_REDEEM=' . (int)$minRedeem . ';'
    . 'const POINT_PESO=' . (float)$pointPesoVal . ';'
    . '</script>'
. <<<'ENDJS'
<script>
let scannerR = null, scanningR = false, scannedR = false;

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

// ── Camera ────────────────────────────────────────────────
document.getElementById('btnStartR').addEventListener('click', function() {
    scannedR = false;
    scannerR = new Html5Qrcode('qr-reader-r');
    scannerR.start(
        { facingMode: 'environment' },
        { fps: 10, qrbox: { width: 220, height: 80 } },
        function(code) { if (!scannedR) { scannedR = true; stopScannerR(); lookupMemberR(code); } },
        function() {}
    ).then(function() {
        scanningR = true;
        document.getElementById('btnStartR').classList.add('d-none');
        document.getElementById('btnStopR').classList.remove('d-none');
    }).catch(function(err) { showMsgR('danger', 'Camera: ' + err); });
});

document.getElementById('btnStopR').addEventListener('click', stopScannerR);

function stopScannerR() {
    if (scannerR) { scannerR.stop().then(function() { scannerR.clear(); scannerR = null; }); }
    scanningR = false;
    document.getElementById('btnStartR').classList.remove('d-none');
    document.getElementById('btnStopR').classList.add('d-none');
}

// ── Manual lookup ─────────────────────────────────────────
document.getElementById('btnLookupR').addEventListener('click', function() {
    var code = document.getElementById('manualCardR').value.trim();
    if (code) lookupMemberR(code); else showMsgR('warning', 'Enter card code.');
});
document.getElementById('manualCardR').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') document.getElementById('btnLookupR').click();
});

// ── Member lookup ─────────────────────────────────────────
function lookupMemberR(code) {
    showMsgR('info', '<span class="spinner-border spinner-border-sm me-2"></span>Looking up&hellip;');
    $.get(BASE_URL + '/ajax/get_member.php', { card_code: code }, function(res) {
        if (res.success && res.member.name) {
            var m = res.member;
            document.getElementById('rCardCode').value          = code;
            document.getElementById('rInfoName').textContent    = m.name;
            document.getElementById('rInfoCard').textContent    = code;
            document.getElementById('rInfoPoints').textContent  = Number(m.points).toLocaleString();
            document.getElementById('memberInfoR').classList.remove('d-none');
            document.getElementById('btnRedeem').disabled = false;
            document.getElementById('rPoints').max = m.points;
            showMsgR('success', '<i class="bi bi-check-circle me-2"></i>Member: <strong>' + m.name + '</strong>');
        } else {
            showMsgR('danger', '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Not found / not registered.'));
        }
    }, 'json');
}

// ── Peso preview ──────────────────────────────────────────
document.getElementById('rPoints').addEventListener('input', function() {
    var pts  = parseInt(this.value) || 0;
    var peso = (pts * POINT_PESO).toFixed(2);
    document.getElementById('rPesoPreview').textContent =
        '= \u20B1' + parseFloat(peso).toLocaleString('en', { minimumFractionDigits: 2 });
});

// ── Redeem submit ─────────────────────────────────────────
document.getElementById('redeemForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var btn = document.getElementById('btnRedeem');
    var pts = parseInt(document.getElementById('rPoints').value) || 0;
    if (pts < MIN_REDEEM) return showMsgR('danger', 'Minimum ' + MIN_REDEEM + ' points required.');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing&hellip;';
    $.post(BASE_URL + '/ajax/redeem_points.php', $(this).serialize(), function(res) {
        if (res.success) {
            document.getElementById('rModalPts').textContent     = res.points_redeemed;
            document.getElementById('rModalPeso').textContent    = '\u20B1' + parseFloat(res.peso_value).toFixed(2);
            document.getElementById('rModalBalance').textContent = res.new_balance;
            document.getElementById('rInfoPoints').textContent   = res.new_balance;
            new bootstrap.Modal(document.getElementById('redeemModal')).show();
            document.getElementById('redeemForm').reset();
            document.getElementById('rPesoPreview').textContent = '= \u20B10.00';
        } else {
            showMsgR('danger', '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Redeem failed'));
        }
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-gift me-2"></i>Redeem Points';
    }, 'json');
});

// ── Reset on modal close ──────────────────────────────────
document.getElementById('redeemModal').addEventListener('hidden.bs.modal', function() {
    document.getElementById('memberInfoR').classList.add('d-none');
    document.getElementById('btnRedeem').disabled = true;
    document.getElementById('rCardCode').value    = '';
    document.getElementById('rPoints').value      = '';
    document.getElementById('rPesoPreview').textContent = '= \u20B10.00';
    scannedR = false;
    document.getElementById('scanMsgR').classList.add('d-none');
});

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