<?php
$pageTitle = 'Member Registration';
require_once __DIR__ . '/includes/header.php';
$prefillCard = htmlspecialchars($_GET['card'] ?? '', ENT_QUOTES);
?>

<div class="row g-4">

  <!-- Scan Section -->
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">
        <i class="bi bi-qr-code-scan me-2"></i>Scan Card
      </div>
      <div class="card-body">
        <!-- Tabs: webcam / manual -->
        <ul class="nav nav-tabs mb-3" id="scanTabs">
          <li class="nav-item">
            <a class="nav-link active" href="#" data-tab="webcam">
              <i class="bi bi-camera-video me-1"></i>Webcam
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#" data-tab="manual">
              <i class="bi bi-keyboard me-1"></i>Manual
            </a>
          </li>
        </ul>

        <!-- Webcam scanner -->
        <div id="tab-webcam">
          <div id="qr-reader" style="width:100%; min-height:220px; background:#000; border-radius:8px; overflow:hidden;"></div>
          <div class="d-grid gap-2 mt-2">
            <button class="btn btn-success" id="btnStartScan">
              <i class="bi bi-camera-video me-2"></i>Start Camera
            </button>
            <button class="btn btn-danger d-none" id="btnStopScan">
              <i class="bi bi-stop-circle me-2"></i>Stop Camera
            </button>
          </div>
        </div>

        <!-- Manual input -->
        <div id="tab-manual" class="d-none">
          <div class="mb-3">
            <label class="form-label fw-semibold">Card Code</label>
            <input type="text" id="manualCardCode" class="form-control font-monospace"
                   placeholder="e.g. 2024-01-15-0001"
                   value="<?= $prefillCard ?>">
          </div>
          <button class="btn btn-primary w-100" id="btnManualLookup">
            <i class="bi bi-search me-2"></i>Look Up Card
          </button>
        </div>

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

  <!-- Form Section -->
  <div class="col-lg-7">
    <div class="card shadow-sm" id="memberFormCard">
      <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <span><i class="bi bi-person-fill me-2 text-primary"></i>Member Information</span>
        <span class="badge bg-secondary" id="formCardBadge">No card scanned</span>
      </div>
      <div class="card-body">

        <!-- Card info preview -->
        <div id="cardPreviewRow" class="row g-3 mb-4 d-none">
          <div class="col-12">
            <div class="d-flex align-items-center gap-3 p-3 bg-light rounded-3">
              <i class="bi bi-credit-card-fill text-primary fs-2"></i>
              <div>
                <div class="fw-bold" id="previewCardCode">—</div>
                <div class="text-muted small" id="previewStatus">—</div>
              </div>
              <div class="ms-auto">
                <span class="badge" id="previewRegistered">—</span>
              </div>
            </div>
          </div>
        </div>

        <form id="memberForm">
          <input type="hidden" id="fCardCode" name="card_code">

          <div class="mb-3">
            <label class="form-label fw-semibold">Full Name <span class="text-danger">*</span></label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-person"></i></span>
              <input type="text" name="name" id="fName" class="form-control"
                     placeholder="Juan Dela Cruz" required>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Address</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-geo-alt"></i></span>
              <textarea name="address" id="fAddress" class="form-control" rows="2"
                        placeholder="Street, City, Province"></textarea>
            </div>
          </div>

          <div class="mb-4">
            <label class="form-label fw-semibold">Cellphone <span class="text-danger">*</span></label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-phone"></i></span>
              <input type="tel" name="phone" id="fPhone" class="form-control"
                     placeholder="09XX-XXX-XXXX" required>
            </div>
          </div>

          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary flex-grow-1" id="btnSaveMember" disabled>
              <i class="bi bi-person-check me-2"></i>Save / Update Member
            </button>
            <button type="button" class="btn btn-outline-secondary" id="btnClearForm">
              <i class="bi bi-x-lg"></i>
            </button>
          </div>
        </form>

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

</div>

<?php
// Bug Fix #1: inject BASE_URL as a real JS variable via PHP echo
$jsBaseUrl = json_encode(BASE_URL);
$extraJS   = '<script>const BASE_URL=' . $jsBaseUrl . ';</script>' . <<<'ENDJS'
<script>
var html5QrScanner = null;
var isScanning     = false;
var scannedOnce    = false;

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

// ── Scanner ───────────────────────────────────────────────
document.getElementById('btnStartScan').addEventListener('click', startScanner);
document.getElementById('btnStopScan').addEventListener('click', stopScanner);

function startScanner() {
    scannedOnce    = false;
    html5QrScanner = new Html5Qrcode('qr-reader');
    html5QrScanner.start(
        { facingMode: 'environment' },
        { fps: 10, qrbox: { width: 220, height: 100 } },
        onScanSuccess,
        function() {}
    ).then(function() {
        isScanning = true;
        document.getElementById('btnStartScan').classList.add('d-none');
        document.getElementById('btnStopScan').classList.remove('d-none');
    }).catch(function(err) {
        showScanMsg('danger', 'Camera error: ' + err);
    });
}

function stopScanner() {
    if (html5QrScanner) {
        html5QrScanner.stop().then(function() {
            html5QrScanner.clear();
            html5QrScanner = null;
        });
    }
    isScanning = false;
    document.getElementById('btnStartScan').classList.remove('d-none');
    document.getElementById('btnStopScan').classList.add('d-none');
}

function onScanSuccess(code) {
    if (scannedOnce) return;
    scannedOnce = true;
    stopScanner();
    lookupCard(code);
}

// ── Manual lookup ─────────────────────────────────────────
document.getElementById('btnManualLookup').addEventListener('click', function() {
    var code = document.getElementById('manualCardCode').value.trim();
    if (!code) return showScanMsg('warning', 'Enter a card code first.');
    lookupCard(code);
});
document.getElementById('manualCardCode').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') document.getElementById('btnManualLookup').click();
});

// ── Prefill from URL query string ─────────────────────────
(function() {
    var code = new URLSearchParams(window.location.search).get('card');
    if (code) lookupCard(code);
})();

// ── Lookup card via AJAX ──────────────────────────────────
// Bug Fix: use BASE_URL variable for absolute path (not relative 'ajax/...')
function lookupCard(code) {
    showScanMsg('info', '<span class="spinner-border spinner-border-sm me-2"></span>Looking up card&hellip;');
    $.get(BASE_URL + '/ajax/get_member.php', { card_code: code }, function(res) {
        if (res.success) {
            populateForm(res.member, code);
            showScanMsg('success', '<i class="bi bi-check-circle me-2"></i>Card found: <strong>' + code + '</strong>');
        } else {
            showScanMsg('danger', '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Card not found. Save the card first.'));
        }
    }, 'json').fail(function() {
        showScanMsg('danger', '<i class="bi bi-x-circle me-2"></i>Server error. Check your connection.');
    });
}

// ── Populate form ─────────────────────────────────────────
function populateForm(member, code) {
    document.getElementById('fCardCode').value          = code;
    document.getElementById('fName').value              = member.name    || '';
    document.getElementById('fAddress').value           = member.address || '';
    document.getElementById('fPhone').value             = member.phone   || '';
    document.getElementById('btnSaveMember').disabled   = false;
    document.getElementById('cardPreviewRow').classList.remove('d-none');
    document.getElementById('previewCardCode').textContent = code;
    document.getElementById('formCardBadge').textContent   = code;

    var isReg = !!member.name;
    var badge = document.getElementById('previewRegistered');
    badge.textContent = isReg ? 'Registered' : 'Unregistered';
    badge.className   = 'badge ' + (isReg ? 'bg-success' : 'bg-secondary');
    document.getElementById('previewStatus').textContent =
        isReg ? 'Updating member record' : 'New registration';
}

// ── Save member via AJAX ──────────────────────────────────
document.getElementById('memberForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var btn = document.getElementById('btnSaveMember');
    btn.disabled  = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving&hellip;';

    $.post(BASE_URL + '/ajax/save_member.php', $(this).serialize(), function(res) {
        var el = document.getElementById('saveMsg');
        if (res.success) {
            el.className = 'alert alert-success';
            el.innerHTML = '<i class="bi bi-check-circle me-2"></i>' + res.message;
        } else {
            el.className = 'alert alert-danger';
            el.innerHTML = '<i class="bi bi-x-circle me-2"></i>' + (res.error || 'Save failed');
        }
        el.classList.remove('d-none');
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-person-check me-2"></i>Save / Update Member';
    }, 'json').fail(function() {
        document.getElementById('saveMsg').className = 'alert alert-danger';
        document.getElementById('saveMsg').textContent = 'Server error. Please try again.';
        document.getElementById('saveMsg').classList.remove('d-none');
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-person-check me-2"></i>Save / Update Member';
    });
});

// ── Clear form ────────────────────────────────────────────
document.getElementById('btnClearForm').addEventListener('click', function() {
    document.getElementById('memberForm').reset();
    document.getElementById('fCardCode').value             = '';
    document.getElementById('btnSaveMember').disabled      = true;
    document.getElementById('cardPreviewRow').classList.add('d-none');
    document.getElementById('formCardBadge').textContent   = 'No card scanned';
    document.getElementById('saveMsg').classList.add('d-none');
    document.getElementById('scanMsg').classList.add('d-none');
    scannedOnce = false;
});

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