<?php
$mobileTitle = 'Register Member';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
$prefillCard = trim($_GET['card'] ?? '');
include __DIR__ . '/includes/m_header.php';
?>

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

<div id="reg-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-reg"></div>
      <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
      <div class="scan-line" id="regScanLine" style="display:none"></div>
      <div class="scanner-hint" id="regScanHint">Tap Start to scan card</div>
    </div>
    <div style="padding:.75rem 1rem">
      <button class="m-btn m-btn-primary mb-2" id="btnRegStart">
        <i class="bi bi-camera-video me-2"></i>Start Camera
      </button>
      <button class="m-btn m-btn-danger mb-2 d-none" id="btnRegStop">
        <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="regCardInput" placeholder="YYYY-MM-DD-####"
               value="<?= e($prefillCard) ?>" style="font-family:monospace">
      </div>
      <button class="m-btn m-btn-outline" id="btnRegManual">
        <i class="bi bi-search me-2"></i>Look Up
      </button>
    </div>
  </div>
  <div id="regScanAlert" style="display:none"></div>
</div>

<div id="reg-step2" style="display:none">
  <div class="d-flex align-items-center gap-2 mb-3">
    <div class="fw-bold small font-monospace" id="regCardLabel"></div>
    <span class="badge" id="regCardBadge">—</span>
  </div>
  <div class="m-section-title">Step 2 — Member Info</div>
  <div class="m-card mb-3">
    <div class="m-card-body">
      <input type="hidden" id="regCardCode">
      <label class="m-input-label">Full Name *</label>
      <div class="m-input-group">
        <i class="bi bi-person"></i>
        <input type="text" id="regName" placeholder="Juan Dela Cruz" required>
      </div>
      <label class="m-input-label">Cellphone *</label>
      <div class="m-input-group">
        <i class="bi bi-phone"></i>
        <input type="tel" id="regPhone" placeholder="09XX-XXX-XXXX" inputmode="tel">
      </div>
      <label class="m-input-label">Address</label>
      <div class="m-input-group">
        <i class="bi bi-geo-alt"></i>
        <input type="text" id="regAddress" placeholder="Street, City">
      </div>
    </div>
  </div>
  <button class="m-btn m-btn-primary mb-2" id="btnSaveReg">
    <i class="bi bi-person-check me-2"></i>Save Member
  </button>
  <button class="m-btn m-btn-outline" id="btnRegBack">
    <i class="bi bi-arrow-left me-2"></i>Back
  </button>
  <div id="regSaveAlert" style="display:none;margin-top:1rem"></div>
</div>

<?php
$jsBaseUrl = json_encode(BASE_URL);
$jsPrefill = json_encode($prefillCard);
$mExtraJS  = '<script>var BASE_URL=' . $jsBaseUrl . ';var PREFILL_CARD=' . $jsPrefill . ';</script>' . <<<'ENDJS'
<script>
document.getElementById('btnRegStart').addEventListener('click', function () {
    this.classList.add('d-none');
    document.getElementById('btnRegStop').classList.remove('d-none');
    document.getElementById('regScanLine').style.display = 'block';
    MobileScanner.start('m-qr-reg',
        function (code) {
            document.getElementById('btnRegStart').classList.remove('d-none');
            document.getElementById('btnRegStop').classList.add('d-none');
            document.getElementById('regScanLine').style.display = 'none';
            lookupCardReg(code);
        },
        function (err) {
            document.getElementById('btnRegStart').classList.remove('d-none');
            document.getElementById('btnRegStop').classList.add('d-none');
            document.getElementById('regScanLine').style.display = 'none';
            mShowAlert('regScanAlert', 'danger', err + '<br><a href=\"camera-help.php\" class=\"alert-link\">\u2192 Camera Help</a>');
        }
    );
});
document.getElementById('btnRegStop').addEventListener('click', function () {
    MobileScanner.stop();
    document.getElementById('btnRegStart').classList.remove('d-none');
    this.classList.add('d-none');
    document.getElementById('regScanLine').style.display = 'none';
});
document.getElementById('btnRegManual').addEventListener('click', function () {
    var code = document.getElementById('regCardInput').value.trim();
    if (!code) return mShowAlert('regScanAlert', 'warning', 'Enter a card code.');
    lookupCardReg(code);
});
document.getElementById('regCardInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') document.getElementById('btnRegManual').click();
});
if (PREFILL_CARD) lookupCardReg(PREFILL_CARD);

function lookupCardReg(code) {
    mShowAlert('regScanAlert', '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('regScanAlert');
            document.getElementById('reg-step1').style.display = 'none';
            document.getElementById('reg-step2').style.display = 'block';
            document.getElementById('regStepBar').style.width  = '100%';
            document.getElementById('regStep2dot').classList.add('active');
            document.getElementById('regCardCode').value       = code;
            document.getElementById('regCardLabel').textContent = code;
            var isReg = !!res.member.name;
            var badge = document.getElementById('regCardBadge');
            badge.textContent = isReg ? 'Update Mode' : 'New Registration';
            badge.className   = 'badge ' + (isReg ? 'bg-success' : 'bg-primary');
            document.getElementById('regName').value    = res.member.name    || '';
            document.getElementById('regPhone').value   = res.member.phone   || '';
            document.getElementById('regAddress').value = res.member.address || '';
            MobileScanner.stop();
        } else {
            mShowAlert('regScanAlert', 'danger', res.error || 'Card not found. Generate and save it first.');
        }
    });
}

document.getElementById('btnSaveReg').addEventListener('click', function () {
    var btn  = this;
    var name = document.getElementById('regName').value.trim();
    var phone= document.getElementById('regPhone').value.trim();
    if (!name  ) return mShowAlert('regSaveAlert', 'warning', 'Name is required.');
    if (!phone ) return mShowAlert('regSaveAlert', 'warning', 'Phone is required.');
    mBtnLoading(btn, true);
    mAjaxPost(BASE_URL + '/ajax/save_member.php', {
        card_code: document.getElementById('regCardCode').value,
        name:      name,
        phone:     phone,
        address:   document.getElementById('regAddress').value
    }, function (res) {
        mBtnLoading(btn, false);
        if (res.success) {
            mShowSuccess({
                icon: 'person-check-fill',
                iconClass: 'bg-primary-subtle text-primary',
                title: 'Member Saved!',
                lines: [{ label: 'Name:', value: name }, { label: 'Phone:', value: phone }],
                btnText: 'Register Another',
                onClose: function () {
                    document.getElementById('reg-step2').style.display = 'none';
                    document.getElementById('reg-step1').style.display = 'block';
                    document.getElementById('regStepBar').style.width  = '0%';
                    document.getElementById('regStep2dot').classList.remove('active');
                    document.getElementById('regCardInput').value = '';
                    document.getElementById('regName').value = '';
                    document.getElementById('regPhone').value = '';
                    document.getElementById('regAddress').value = '';
                    MobileScanner.reset();
                }
            });
        } else {
            mShowAlert('regSaveAlert', 'danger', res.error || 'Save failed.');
        }
    });
});
document.getElementById('btnRegBack').addEventListener('click', function () {
    document.getElementById('reg-step2').style.display = 'none';
    document.getElementById('reg-step1').style.display = 'block';
    document.getElementById('regStepBar').style.width  = '0%';
    document.getElementById('regStep2dot').classList.remove('active');
    MobileScanner.reset();
});
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
