<?php
session_start();
include 'header.php';
include 'db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
?>

<!--
<div class="text-center">
    <h2>Scan QR Code</h2>
    <p>Align the QR code within the box to scan.</p>

    // Camera Preview with Reduced Size
    <video id="preview" style="width: 300px; height: 300px; border: 2px solid #007bff; border-radius: 10px;"></video>

    <form action="save_scanned_qr.php" method="POST">
        <label for="app_name">Enter App Name:</label>
        <input type="text" id="app_name" name="app_name" required class="form-control mb-2">

        <input type="hidden" id="scanned_qr" name="scanned_qr">
        <button type="submit" class="btn btn-success">Save Scanned QR</button>
    </form>
</div>
-->


<div class="container mt-5">
    <h2 class="mb-4">Scan QR Code</h2>
    <p>Scan a QR code from another application to generate OTPs.</p>

      <video id="preview" style="width: 300px; height: 300px; border: 2px solid #007bff; border-radius: 10px;"></video>

    <div id="qr-reader" style="width: 100%; "></div>
    <p id="qr-result" class="mt-3 alert alert-info d-none"></p>

  <!--  <form id="save-secret-form" action="save_scanned_qr.php" method="POST" class="mt-3 d-none">
        <input type="hidden" name="secret" id="scanned-secret">
        <button type="submit" class="btn btn-success">Save QR Code</button>
    </form>
  -->

    <form id="save-secret-form" action="save_scanned_qr.php" method="POST" class="mt-3 d-none">

<label for="app_name">Enter App Name:</label>
    <input type="text" id="scanned_qr" name="app_name" required class="form-control mb-2">


    <input type="text" id="scanned-secret" name="secret" >

    <button type="submit" class="btn btn-success">Save Scanned QR</button>
</form>

</div>

<!-- Load QR Code Scanner Library -->
<script src="https://unpkg.com/html5-qrcode"></script>
<script>
    function onScanSuccess(decodedText) {
        document.getElementById('qr-result').textContent = "✅ QR Code Scanned: " + decodedText;
        document.getElementById('qr-result').classList.remove('d-none');
        document.getElementById('scanned-secret').value = decodedText;
        document.getElementById('save-secret-form').classList.remove('d-none');
    }

    function onScanFailure(error) {
        console.warn("QR Scan Error: ", error);
    }

    const qrScanner = new Html5Qrcode("qr-reader");
    qrScanner.start(
        { facingMode: "environment" }, // Use back camera
        { fps: 10, qrbox: 250 },
        onScanSuccess,
        onScanFailure
    );
</script>

<?php include 'footer.php'; ?>
