<?php
/**
 * Reusable scan panel — QR + Barcode separated.
 *
 * Required vars:
 *   $spId       - unique base id string, e.g. 'scan', 'purchase', 'redeem'
 *   $spAlertId  - DOM id for the alert div on this page
 *   $spOnScan   - JS function name called with (decodedCode)
 */
$spBase  = $spId;
?>
<div class="m-card mb-3">
  <div class="m-card-header">
    <i class="bi bi-qr-code-scan text-primary me-1"></i> Scan Card
  </div>
  <div class="m-card-body">

    <!-- TWO TAKE-PHOTO BUTTONS: QR and Barcode -->
    <div class="m-scan-grid">

      <!-- QR Code -->
      <button class="m-scan-btn qr" id="btn<?= ucfirst($spBase) ?>QrPhoto">
        <span class="m-scan-btn-icon">&#x25A6;</span>
        <span class="m-scan-btn-label">Scan QR Code</span>
        <span class="m-scan-btn-sub">Opens camera app</span>
      </button>

      <!-- Barcode -->
      <button class="m-scan-btn barcode" id="btn<?= ucfirst($spBase) ?>BcPhoto">
        <span class="m-scan-btn-icon" style="font-size:1.6rem;letter-spacing:-2px">
          <i class="bi bi-upc-scan"></i>
        </span>
        <span class="m-scan-btn-label">Scan Barcode</span>
        <span class="m-scan-btn-sub">Opens camera app</span>
      </button>
    </div>

    <div class="text-muted small text-center mb-2" style="font-size:.7rem">
      <i class="bi bi-info-circle me-1"></i>
      Both open your Android camera — works without HTTPS
    </div>

    <!-- Live stream section (HTTPS only) -->
    <div id="<?= $spBase ?>LiveSection">
      <div class="m-live-row" id="<?= $spBase ?>LiveBtns">
        <button class="m-live-btn qr" id="btn<?= ucfirst($spBase) ?>LiveQr">
          <i class="bi bi-camera-video"></i> Live QR
        </button>
        <button class="m-live-btn barcode" id="btn<?= ucfirst($spBase) ?>LiveBc">
          <i class="bi bi-camera-video"></i> Live Barcode
        </button>
        <button class="m-live-btn" id="btn<?= ucfirst($spBase) ?>Stop" style="display:none;flex:0 0 auto;padding:.6rem .75rem">
          <i class="bi bi-stop-circle text-danger"></i>
        </button>
      </div>

      <!-- Stream container (hidden until live activated) -->
      <div id="<?= $spBase ?>StreamWrap" style="display:none;margin-bottom:.5rem">
        <div class="m-scanner-wrap" style="min-height:200px">
          <div id="m-qr-<?= $spBase ?>"></div>
          <div class="scanner-frame" id="<?= $spBase ?>Frame">
            <div class="scanner-frame-inner"></div>
          </div>
          <div class="scan-line" id="<?= $spBase ?>ScanLine" style="display:none"></div>
          <div class="scanner-hint" id="<?= $spBase ?>Hint"></div>
        </div>
      </div>

      <div id="<?= $spBase ?>HttpsNote" class="m-alert m-alert-info" style="display:none;margin-top:.5rem;font-size:.78rem">
        <i class="bi bi-info-circle-fill"></i>
        <span>Live scan needs HTTPS. <strong>Take Photo</strong> (above) works on any connection. <a href="camera-help.php" style="color:inherit">Help →</a></span>
      </div>
    </div>

  </div>
</div>

<script>
(function() {
  var base    = <?= json_encode($spBase) ?>;
  var alertId = <?= json_encode($spAlertId) ?>;
  var onScan  = <?= json_encode($spOnScan) ?>;   // function name string

  function callOnScan(code) {
    if (typeof window[onScan] === 'function') window[onScan](code);
  }

  // Show HTTPS note if not secure
  if (!isSecureCtx()) {
    var note = document.getElementById(base + 'HttpsNote');
    if (note) note.style.display = 'flex';
    var liveRow = document.getElementById(base + 'LiveBtns');
    if (liveRow) {
      // Hide QR and Barcode live buttons, keep stop hidden
      liveRow.querySelectorAll('.m-live-btn:not(#btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'Stop)')
             .forEach(function(b){ b.style.display = 'none'; });
    }
  }

  // Take Photo — QR
  var btnQrPhoto = document.getElementById('btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'QrPhoto');
  if (btnQrPhoto) btnQrPhoto.addEventListener('click', function() {
    mHideAlert(alertId);
    NativeScanner.open('qr', callOnScan, function(err) {
      mShowAlert(alertId, 'danger', err + '<br><small><a href="camera-help.php" style="color:inherit">Camera Help →</a></small>');
    });
  });

  // Take Photo — Barcode
  var btnBcPhoto = document.getElementById('btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'BcPhoto');
  if (btnBcPhoto) btnBcPhoto.addEventListener('click', function() {
    mHideAlert(alertId);
    NativeScanner.open('barcode', callOnScan, function(err) {
      mShowAlert(alertId, 'danger', err + '<br><small><a href="camera-help.php" style="color:inherit">Camera Help →</a></small>');
    });
  });

  // Live QR
  var btnLiveQr = document.getElementById('btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'LiveQr');
  if (btnLiveQr) btnLiveQr.addEventListener('click', function() {
    startLive('qr');
  });

  // Live Barcode
  var btnLiveBc = document.getElementById('btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'LiveBc');
  if (btnLiveBc) btnLiveBc.addEventListener('click', function() {
    startLive('barcode');
  });

  // Stop
  var btnStop = document.getElementById('btn' + base.charAt(0).toUpperCase() + base.slice(1) + 'Stop');
  if (btnStop) btnStop.addEventListener('click', function() {
    StreamScanner.stop().then(function() { hideLive(); });
  });

  function startLive(mode) {
    mHideAlert(alertId);
    if (!isSecureCtx()) {
      mShowAlert(alertId, 'warning', buildHttpsWarning());
      return;
    }
    // Toggle UI
    var wrap  = document.getElementById(base + 'StreamWrap');
    var line  = document.getElementById(base + 'ScanLine');
    var hint  = document.getElementById(base + 'Hint');
    var frame = document.getElementById(base + 'Frame');
    if (wrap)  wrap.style.display  = 'block';
    if (line)  line.style.display  = 'block';
    if (hint)  hint.textContent    = mode === 'qr' ? 'Point at the QR code…' : 'Align the barcode in the frame…';
    if (frame) frame.className     = 'scanner-frame' + (mode === 'barcode' ? ' barcode-mode' : '');
    if (btnStop) btnStop.style.display = 'flex';

    StreamScanner.stop().then(function() {
      StreamScanner.start('m-qr-' + base, mode,
        function(code) {
          hideLive();
          callOnScan(code);
        },
        function(err) {
          hideLive();
          mShowAlert(alertId, 'danger', err + '<br><small><a href="camera-help.php" style="color:inherit">Camera Help →</a></small>');
        }
      );
    });
  }

  function hideLive() {
    var wrap = document.getElementById(base + 'StreamWrap');
    var line = document.getElementById(base + 'ScanLine');
    var hint = document.getElementById(base + 'Hint');
    if (wrap)  wrap.style.display  = 'none';
    if (line)  line.style.display  = 'none';
    if (hint)  hint.textContent    = '';
    if (btnStop) btnStop.style.display = 'none';
  }
})();
</script>
