<?php
/**
 * Reusable scanner widget include.
 *
 * Required vars before include:
 *   $scannerId    – unique DOM id, e.g. 'm-qr-purchase'
 *   $scanLineId   – id for the animated line, e.g. 'purchaseScanLine'
 *   $scanHintId   – id for the hint text
 *   $btnStartId   – id for Start button
 *   $btnStopId    – id for Stop button
 *   $alertId      – id for the alert div below
 *   $onScanJs     – JS expression called with (decodedCode) on success
 *   $startBtnClass– optional extra class on Start button (default m-btn-primary)
 */
$startClass = $startBtnClass ?? 'm-btn-primary';
?>
<div class="m-card mb-3">
  <div class="m-scanner-wrap" id="<?= $scannerId ?>Wrap">
    <div id="<?= $scannerId ?>"></div>
    <div class="scanner-frame"><div class="scanner-frame-inner"></div></div>
    <div class="scan-line" id="<?= $scanLineId ?>" style="display:none"></div>
    <div class="scanner-hint" id="<?= $scanHintId ?>">Tap Start to activate camera</div>
  </div>

  <!-- HTTPS warning (shown before start if not secure) -->
  <div id="<?= $scannerId ?>HttpsWarn" class="m-alert m-alert-warning" style="display:none;margin:.75rem">
    <i class="bi bi-shield-exclamation"></i>
    <span></span>
  </div>

  <div style="padding:.75rem 1rem;display:flex;flex-direction:column;gap:.5rem">
    <button class="m-btn <?= $startClass ?>" id="<?= $btnStartId ?>">
      <i class="bi bi-camera-video me-2"></i>Start Camera
    </button>
    <button class="m-btn m-btn-danger d-none" id="<?= $btnStopId ?>">
      <i class="bi bi-stop-circle me-2"></i>Stop Camera
    </button>
  </div>
</div>

<script>
(function () {
    var scannerId = <?= json_encode($scannerId) ?>;
    var lineId    = <?= json_encode($scanLineId) ?>;
    var hintId    = <?= json_encode($scanHintId) ?>;
    var startId   = <?= json_encode($btnStartId) ?>;
    var stopId    = <?= json_encode($btnStopId) ?>;
    var alertId   = <?= json_encode($alertId) ?>;

    function showScannerLine(show) {
        var l = document.getElementById(lineId);
        if (l) l.style.display = show ? 'block' : 'none';
    }
    function setHint(txt) {
        var h = document.getElementById(hintId);
        if (h) h.textContent = txt;
    }
    function setButtons(scanning) {
        var s = document.getElementById(startId);
        var p = document.getElementById(stopId);
        if (!s || !p) return;
        if (scanning) {
            s.classList.add('d-none');
            p.classList.remove('d-none');
        } else {
            s.classList.remove('d-none');
            p.classList.add('d-none');
        }
    }

    // Warn immediately if not HTTPS
    if (!isSecureContext()) {
        var w = document.getElementById(scannerId + 'HttpsWarn');
        if (w) { w.querySelector('span').innerHTML = buildHttpsWarning(); w.style.display = 'flex'; }
        var startBtn = document.getElementById(startId);
        if (startBtn) { startBtn.disabled = true; startBtn.title = 'HTTPS required'; }
    }

    document.getElementById(startId).addEventListener('click', function () {
        mHideAlert(alertId);
        setButtons(true);
        showScannerLine(true);
        setHint('Align QR code or barcode in the frame\u2026');

        MobileScanner.start(
            scannerId,
            function (code) {
                setButtons(false);
                showScannerLine(false);
                setHint('Scanned!');
                // call the page-specific handler
                window[<?= json_encode($onScanJs) ?>] && window[<?= json_encode($onScanJs) ?>](code);
                // if the caller is an inline function name – eval it
                (function(c){ <?= $onScanJs ?>(c); })(code);
            },
            function (errHtml) {
                setButtons(false);
                showScannerLine(false);
                setHint('Camera error. Use Manual Entry below.');
                mShowAlert(alertId, 'danger', errHtml);
            }
        );
    });

    document.getElementById(stopId).addEventListener('click', function () {
        MobileScanner.stop().then(function () {
            setButtons(false);
            showScannerLine(false);
            setHint('Tap Start to activate camera');
        });
    });
})();
</script>
