<?php
if ($_SESSION["usuario_nivel"] != 'Stand') {
    echo '<h1 class="text-center">Apenas usuarios com nivel stand podem registrar presençã de participantes!</h1>';
    exit;
}
?>
<h1 class="text-center">Aponte a camera para o QR CODE</h1>
<video id="video" autoplay style="width: 100%; max-width:350px;height: 100%; max-height:350px;"></video>
<canvas id="canvas" style="width: 100%; max-width:350px;height: 100%; max-height:350px; display:none"></canvas>


<script src="<?= __URLSITE__ ?>js/leitorqrcode.js"></script>
<script>
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const canvasContext = canvas.getContext('2d');
    // const outputData = document.getElementById('outputData');

    // Solicita permissão para acessar a câmera
    navigator.mediaDevices.getUserMedia({
            video: {
                facingMode: 'environment'
            }
        })
        .then((stream) => {
            video.srcObject = stream;
            video.setAttribute('playsinline', true); // necessário para iPhones
            video.play();
            requestAnimationFrame(scanQRCode);
        })
        .catch(err => {
            console.error('Erro ao acessar a câmera: ', err);
        });

    function scanQRCode() {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvasContext.drawImage(video, 0, 0, canvas.width, canvas.height);

            const imageData = canvasContext.getImageData(0, 0, canvas.width, canvas.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height);

            if (code) {

                $.post("<?= __URLSITE__ ?>modulos/frequencia/controller.php", {
                        qrcode: code.data
                    },
                    function(data, textStatus, jqXHR) {
                        if (data == 'sucesso') {
                            alert('Presença Registrada!');
                            window.location.href = '<?= (__URLSITE__) ?>'
                        } else {
                            alert('Erro ao registrar presença.');
                        }
                        video.stop();
                    }
                );
            }
        }
        requestAnimationFrame(scanQRCode);
    }
</script>