<?php
$mobileTitle = 'Camera Help';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
include __DIR__ . '/includes/m_header.php';
?>

<div class="m-section-title">Camera Troubleshooting</div>

<!-- HTTPS Status -->
<div class="m-card mb-3" id="httpsStatus">
  <div class="m-card-body">
    <div class="d-flex align-items-center gap-3">
      <div id="httpsIcon" style="font-size:2.5rem"></div>
      <div>
        <div class="fw-bold" id="httpsTitle">Checking…</div>
        <div class="text-muted small" id="httpsDetail"></div>
      </div>
    </div>
  </div>
</div>

<!-- Camera API Status -->
<div class="m-card mb-3">
  <div class="m-card-body">
    <div class="fw-bold mb-2"><i class="bi bi-camera-video me-2 text-primary"></i>Camera API Test</div>
    <button class="m-btn m-btn-primary mb-2" id="btnTestCamera">
      <i class="bi bi-play-circle me-2"></i>Test Camera Access
    </button>
    <div id="cameraTestResult" class="m-alert d-none"></div>
    <div id="testVideoWrap" style="display:none;margin-top:.75rem">
      <video id="testVideo" autoplay playsinline muted
             style="width:100%;border-radius:12px;background:#000;max-height:200px;object-fit:cover"></video>
      <button class="m-btn m-btn-danger mt-2" id="btnStopTest">
        <i class="bi bi-stop-circle me-2"></i>Stop Test
      </button>
    </div>
  </div>
</div>

<!-- Step-by-step guide -->
<div class="m-section-title">Fix Steps for Android Chrome</div>

<div class="m-card mb-3">
  <div class="m-card-body" style="padding:.75rem 1rem">

    <div class="m-help-step">
      <div class="m-help-num">1</div>
      <div>
        <div class="fw-semibold">Allow Camera Permission</div>
        <div class="text-muted small">When prompted, tap <b>Allow</b>. If you already denied it:</div>
        <div class="text-muted small mt-1">Chrome address bar → 🔒 or ⓘ icon → <b>Permissions</b> → Camera → <b>Allow</b></div>
      </div>
    </div>

    <div class="m-help-step">
      <div class="m-help-num">2</div>
      <div>
        <div class="fw-semibold">Use HTTPS or Localhost</div>
        <div class="text-muted small">Android Chrome only allows camera on <b>HTTPS</b> or <code>localhost</code>.</div>
        <div class="text-muted small mt-1">
          If you're accessing by IP (e.g. 192.168.x.x), use a tunnel:<br>
          • <a href="https://ngrok.com" target="_blank">ngrok.com</a> — free HTTPS tunnel<br>
          • Run: <code>ngrok http 80</code> → use the https://xxxx.ngrok.io URL
        </div>
      </div>
    </div>

    <div class="m-help-step">
      <div class="m-help-num">3</div>
      <div>
        <div class="fw-semibold">Close Other Camera Apps</div>
        <div class="text-muted small">Camera can only be used by one app at a time. Close WhatsApp, TikTok, etc.</div>
      </div>
    </div>

    <div class="m-help-step">
      <div class="m-help-num">4</div>
      <div>
        <div class="fw-semibold">Clear Browser Cache</div>
        <div class="text-muted small">Chrome → ⋮ menu → Settings → Privacy → Clear browsing data → Cached images and files.</div>
      </div>
    </div>

    <div class="m-help-step" style="border-bottom:none">
      <div class="m-help-num">5</div>
      <div>
        <div class="fw-semibold">Use Manual Entry</div>
        <div class="text-muted small">Every scanner page has a <b>Manual Entry</b> field. Type or paste the card code if the camera is unavailable.</div>
      </div>
    </div>

  </div>
</div>

<!-- Current URL info -->
<div class="m-card mb-3">
  <div class="m-card-body">
    <div class="fw-bold mb-2"><i class="bi bi-info-circle me-2 text-info"></i>Your Current URL</div>
    <code id="currentUrl" class="small" style="word-break:break-all"></code>
    <div class="text-muted small mt-2" id="urlAdvice"></div>
  </div>
</div>

<style>
.m-help-step {
  display:flex; gap:.85rem; padding:.75rem 0;
  border-bottom:1px solid #f1f5f9; align-items:flex-start;
}
.m-help-num {
  width:28px; height:28px; border-radius:50%;
  background:#0d6efd; color:#fff;
  display:flex; align-items:center; justify-content:center;
  font-size:.8rem; font-weight:700; flex-shrink:0; margin-top:1px;
}
</style>

<?php
$mExtraJS = <<<'ENDJS'
<script>
/* ── HTTPS Status ─────────────────────────────────────── */
var icon  = document.getElementById('httpsIcon');
var title = document.getElementById('httpsTitle');
var detail= document.getElementById('httpsDetail');
var urlEl = document.getElementById('currentUrl');
var adv   = document.getElementById('urlAdvice');

urlEl.textContent = window.location.href;

if (isSecureContext()) {
    icon.innerHTML  = '<i class="bi bi-shield-fill-check text-success"></i>';
    title.textContent = 'Secure Connection \u2714';
    title.className   = 'fw-bold text-success';
    detail.textContent = 'HTTPS or localhost detected. Camera should work.';
    adv.textContent   = '\u2705 This URL is allowed to use the camera.';
} else {
    icon.innerHTML  = '<i class="bi bi-shield-fill-x text-danger"></i>';
    title.textContent = 'NOT Secure \u2717 — Camera Blocked';
    title.className   = 'fw-bold text-danger';
    detail.innerHTML  = 'Access via <code>http://localhost/rewards/</code> or use HTTPS.';
    adv.innerHTML     = '\u274C Camera is blocked on this URL. See fix steps below.';
}

/* ── Live Camera Test ─────────────────────────────────── */
var testStream = null;

document.getElementById('btnTestCamera').addEventListener('click', function () {
    var btn    = this;
    var result = document.getElementById('cameraTestResult');
    var wrap   = document.getElementById('testVideoWrap');
    var video  = document.getElementById('testVideo');

    if (!isSecureContext()) {
        result.className = 'm-alert m-alert-danger';
        result.innerHTML = '<i class="bi bi-x-circle-fill"></i><span>' + buildHttpsWarning() + '</span>';
        result.classList.remove('d-none');
        return;
    }

    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        result.className = 'm-alert m-alert-danger';
        result.innerHTML = '<i class="bi bi-x-circle-fill"></i><span>getUserMedia not supported in this browser.</span>';
        result.classList.remove('d-none');
        return;
    }

    btn.disabled  = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Opening camera\u2026';
    result.classList.add('d-none');

    navigator.mediaDevices.getUserMedia({
        video: { facingMode: { ideal: 'environment' } },
        audio: false
    }).then(function (stream) {
        testStream = stream;
        video.srcObject = stream;
        wrap.style.display = 'block';
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-play-circle me-2"></i>Test Camera Access';
        result.className = 'm-alert m-alert-success';
        result.innerHTML = '<i class="bi bi-check-circle-fill"></i><span><strong>Camera is working!</strong> The scanner should work on this device.</span>';
        result.classList.remove('d-none');
    }).catch(function (err) {
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-play-circle me-2"></i>Test Camera Access';
        var msg = MobileScanner._humanise(err);
        result.className = 'm-alert m-alert-danger';
        result.innerHTML = '<i class="bi bi-x-circle-fill"></i><span>' + msg + '</span>';
        result.classList.remove('d-none');
    });
});

document.getElementById('btnStopTest').addEventListener('click', function () {
    if (testStream) {
        testStream.getTracks().forEach(function (t) { t.stop(); });
        testStream = null;
    }
    document.getElementById('testVideo').srcObject = null;
    document.getElementById('testVideoWrap').style.display = 'none';
});
</script>
ENDJS;
include __DIR__ . '/includes/m_footer.php';
