@extends('layouts.scanner')

@section('content')
<style>
.scanner-wrapper {
    width: 100%;
    height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
}

#reader {
    width: 100%;
    height: 400px !important;
    max-width: 100%;
    /* border: 2px solid #ccc; */
    /* border-radius: 12px; */
    overflow: hidden;
}

#reader video {
    width: 100% !important;
    height: 400px !important;
    max-width: 100% !important;
    object-fit: cover !important;
}

</style>
<div class="scanner-wrapper">
    <div id="reader" style="width: 100%; height: 400px; margin: 0 auto;"></div> <!-- Set height for mobile view -->
</div>
<div id="result" class="mt-4"></div>

@endsection

@push('scripts')
<script src="https://unpkg.com/html5-qrcode"></script>
<!-- <script src="https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js"></script> -->

<script>
    function showResult(type, message) {
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML = `
            <div class="alert alert-${type === 'success' ? 'success' : 'danger'}">
                ${message}
            </div>
        `;
    }

    const qrScanner = new Html5Qrcode("reader");
    let isScanning = false;
    const config = {
    fps: 60,
    qrbox: function(viewfinderWidth, viewfinderHeight) {
        const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
        return {
            width: minEdge * 0.8,
            height: minEdge * 0.8
        };
    }
    };
    function handleScan(qrCodeMessage) {
        if (isScanning) return;
        isScanning = true;

        qrScanner.stop();

        let url = new URL(qrCodeMessage);
        let code = url.searchParams.get('code');
        let day = url.searchParams.get('day');

        fetch("/api/validate-qr", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": '{{ csrf_token() }}'
            },
            body: JSON.stringify({ code, day })
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                showResult('success', `✅ ${data.message} <br> Name: ${data.label} <br> Day: ${data.day}`);
            } else {
                showResult('error', `❌ ${data.message} <br> Name: ${data.label} <br> Day: ${data.day}`);
            }

            // Restart scanner after short delay
            setTimeout(() => {
                isScanning = false;
                qrScanner.start(
                    { facingMode: "environment" },
                    config,
                    handleScan
                );
            }, 2000);
        })
        .catch(err => {
            showResult('error', '❌ Something went wrong.');
            console.error(err);
            isScanning = false;
        });
    }

    // Initial scanner start
    qrScanner.start(
        { facingMode: "environment" },
        config,
        handleScan,
        errorMessage => {
            // Optional: handle scanning errors
            // console.log('QR not detected:', errorMessage);
        }
    ).catch(err => {
        console.error("Camera init error:", err);
    });
</script>
@endpush
