document.addEventListener('DOMContentLoaded', () => {
    const messageArea = document.getElementById('message-area');
    const resultsDiv = document.getElementById('qr-reader-results');
    const qrReaderDiv = document.getElementById('qr-reader');
    let lastScanTime = 0;
    const cooldownPeriod = 2000; // 2 seconds cooldown

    // Function to detect if the device is a mobile phone
    function isMobileDevice() {
        const userAgent = navigator.userAgent || navigator.vendor || window.opera;
        return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|rim)|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|ob)|al(av|ca|co)|amoi|an(d|ex)|ny|p(us|rn)|so)|ap(ad|ice|al|ty)|aq(ta|ss)|es|ct(ly|go)|fe(i|mo|t)|fg(no|t)|ha(v|w|b)|hi(pt|ad)|(a|ph)on|hp(i|si)|ht(c_|o_)|htc|hu(aw|h|l)|i(2000|go|gu|ki)|t(v|v2)|in(co|tk)|i|ja(c|r)|j(v|j|z)|k(c|o|v)|l(in|go)|m(o|o2|o3|a|w|n)|m(an|in)|(o|in)|p(c|p|t)|qi(a|b)|qu(r|z)|s(on|it|s)|sh(mo|w)|sz(s|k)|t(a|m)|un(mo|m|u)|v(a|u)|wa(a|d)|z(a|t)|oo|f(mo|t)|m(f|v)|t(mo|b)|v(g|aj)|w(i|ow))/i.test(userAgent.substr(0, 4));
    }

    // Function to handle the scanned data
    async function processQRCode(decodedText) {
        const currentTime = new Date().getTime();
        // Check for cooldown to avoid multiple scans of the same code
        if (currentTime - lastScanTime < cooldownPeriod) {
            return;
        }

        lastScanTime = currentTime;
        resultsDiv.textContent = `Scanned ID: ${decodedText}`;

        try {
            const response = await fetch('process_scan.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `user_id=${decodedText}`
            });

            const data = await response.json();

            if (data.status === 'success') {
                messageArea.className = 'success';
                messageArea.innerHTML = `✅ Check-in successful for **${data.fullname}**! <br> You have **${data.meals_remaining}** meal(s) left.`;
            } else {
                messageArea.className = 'error';
                messageArea.innerHTML = `❌ Error: ${data.message}`;
            }
        } catch (error) {
            console.error('Error processing scan:', error);
            messageArea.className = 'error';
            messageArea.innerHTML = '❌ An error occurred while processing the scan.';
        }
    }

    // Conditional logic to initialize the scanner
    if (isMobileDevice()) {
        // Mobile device: Initialize and start the camera scanner
        const html5QrCode = new Html5Qrcode("qr-reader");
        const config = { fps: 10, qrbox: { width: 250, height: 250 } };
    
        html5QrCode.start({ facingMode: "environment" }, config, 
            (decodedText) => {
                processQRCode(decodedText);
            },
            (errorMessage) => {
                // Optional: display scanning errors
            }
        ).catch(err => {
            messageArea.className = 'error';
            messageArea.innerHTML = '❌ Camera access denied or not available.';
            console.error('Camera start error:', err);
        });

    } else {
        // PC/Desktop: Display a message and listen for barcode scanner input
        qrReaderDiv.innerHTML = '<p>Please use a barcode scanner to scan the QR code.</p>';
        messageArea.innerHTML = 'Waiting for scanner input...';

        // Handle input from a physical barcode scanner
        let barcodeBuffer = '';
        document.addEventListener('keypress', (event) => {
            if (event.key === 'Enter' || event.keyCode === 13) {
                if (barcodeBuffer.length > 0) {
                    processQRCode(barcodeBuffer);
                    barcodeBuffer = ''; // Reset the buffer
                }
            } else {
                barcodeBuffer += event.key;
            }
        });
    }
});