<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8" />
  <title>Scanner QR Code - Validation Invitation</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body { padding: 2rem; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f7f9fc; }
    #reader { width: 100%; max-width: 400px; margin: 0 auto; }
  </style>
</head>
<body>
  <div class="container text-center">
    <h1 class="mb-4 text-primary">Scanner QR Code</h1>
    <div id="reader"></div>
    <p id="status" class="mt-3 text-muted">Ouvre ta caméra et scanne le QR code.</p>
  </div>

  <form id="validationForm" action="validation.php" method="POST" style="display:none;">
    <input type="hidden" name="invitation_id" id="invitation_id" />
  </form>

  <script src="https://unpkg.com/html5-qrcode@2.3.7/minified/html5-qrcode.min.js"></script>
  <script>
    function onScanSuccess(decodedText, decodedResult) {
      try {
        const data = JSON.parse(decodedText);
        if (data.invitation_id) {
          document.getElementById('invitation_id').value = data.invitation_id;
          document.getElementById('status').textContent = "QR Code scanné ! Validation en cours...";
          // Stop scanner avant soumission
          html5QrcodeScanner.clear().then(() => {
            document.getElementById('validationForm').submit();
          });
        } else {
          document.getElementById('status').textContent = "QR Code non valide (pas d'invitation_id).";
        }
      } catch(e) {
        document.getElementById('status').textContent = "Erreur lecture QR Code : format JSON invalide.";
      }
    }

    var html5QrcodeScanner = new Html5QrcodeScanner(
      "reader", { fps: 10, qrbox: 250 });
    html5QrcodeScanner.render(onScanSuccess);
  </script>
</body>
</html>
