<?php
$page_title = 'ສະແກນໃບບິນ (QR Code)';
require_once '../includes/header.php';
?>

<style>
    .scanner-container {
        max-width: 100%;
        margin: 0 auto;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 16px;
        text-align: center;
    }

    #reader {
        width: 100%;
        height: 60vh;
        min-height: 400px;
        border-radius: 16px;
        overflow: hidden;
        border: 3px dashed var(--accent);
        position: relative;
        background: black;
    }

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

    .overlay {
        position: absolute;
        inset: 0;
        pointer-events: none;
        z-index: 5;
    }

    .scan-line {
        position: absolute;
        left: 5%; right: 5%;
        height: 5px;
        background: linear-gradient(to right, transparent, #00ff88, transparent);
        box-shadow: 0 0 15px #00ff88;
        animation: scan-move 2.8s infinite ease-in-out;
    }

    @keyframes scan-move {
        0%, 100% { top: 10%; }
        50% { top: 90%; }
    }

    .scan-text {
        position: absolute;
        bottom: 40px;
        left: 0; right: 0;
        color: #fff;
        font-size: 1.4rem;
        font-weight: bold;
        text-shadow: 0 0 8px #000;
        z-index: 6;
    }

    .guide {
        margin: 16px 0;
        color: var(--text-secondary);
        font-size: 1.1rem;
        line-height: 1.4;
    }

    .camera-btn {
        margin-top: 16px;
        padding: 12px 32px;
        font-size: 1.1rem;
    }

    .result-box, .error-box {
        margin-top: 16px;
        padding: 16px;
        border-radius: 12px;
        display: none;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }
</style>

<div class="content">
    <div class="scanner-container">
        <h2><i class="fas fa-qrcode text-primary"></i> ສະແກນໃບບິນ</h2>
        <p class="guide">ຖືໃຫ້ຄົງທີ່ ຫຼື ຂຽບຊ້າໆ – ແຕະຈໍເພື່ອໂຟກັສ QR ເທົ່ານັ້ນ (ບໍ່ໂຟກັສພື້ນຫຼັງ)</p>

        <div id="reader">
            <div class="overlay">
                <div class="scan-line"></div>
            </div>
            <div class="scan-text">ກຳລັງສະແກນ QR Code...</div>
        </div>

        <div class="result-box" id="success-result">
            <i class="fas fa-check-circle fa-lg"></i> <span>ກຳລັງໂຫຼດ...</span>
        </div>

        <div class="error-box" id="error-result"></div>

        <button id="start-btn" class="camera-btn" style="display: none;">
            <i class="fas fa-camera"></i> ເປີດກ້ອງໃໝ່
        </button>
    </div>
</div>

<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const html5QrCode = new Html5Qrcode("reader");
    const success = document.getElementById('success-result');
    const errorEl = document.getElementById('error-result');
    const startBtn = document.getElementById('start-btn');

    let isScanning = false;

    const config = {
        fps: 25,  // เร็วขึ้น แต่ยังสมดุล (ไม่ lag บนมือถือส่วนใหญ่)
        qrbox: (vw, vh) => {
            const min = Math.min(vw, vh);
            return { width: min * 0.82, height: min * 0.82 };  // ใหญ่ขึ้น จับ QR ง่าย ไม่ต้องตรงกรอบเป๊ะ
        },
        aspectRatio: 3/4,  // เหมาะมือถือ portrait
        disableFlip: true,
        useBarCodeDetectorIfSupported: true,  // ใช้ API native ถ้าเบราว์เซอร์รองรับ → เร็วมาก
        formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE],
        experimentalFeatures: { useBarCodeDetectorIfSupported: true }
    };

    function startScanner() {
        success.style.display = 'none';
        errorEl.style.display = 'none';
        startBtn.style.display = 'none';
        isScanning = false;

        html5QrCode.start(
            { facingMode: "environment" },
            config,
            (decodedText) => {
                if (isScanning) return;
                isScanning = true;

                console.log('Scanned:', decodedText);

                html5QrCode.stop().catch(console.error);

                let targetUrl = decodedText.trim();
                const currentOrigin = window.location.origin;

                // Force แปลง www. เป็น non-www. เพื่อ session ไม่หาย
                targetUrl = targetUrl.replace(/^(https?:\/\/)www\.epgroups\.com/i, '$1epgroups.com');

                if (targetUrl.startsWith('http')) {
                    try {
                        const u = new URL(targetUrl);
                        if (u.origin !== currentOrigin) {
                            targetUrl = currentOrigin + u.pathname + u.search;
                        }
                    } catch {}
                } else {
                    targetUrl = targetUrl.replace(/^[\.\/]+/, '');
                    if (!targetUrl.includes('view_order.php')) return showError();
                    targetUrl = currentOrigin + '/muanjai/system/pos/' + targetUrl;
                }

                if (targetUrl.includes('view_order.php')) {
                    success.style.display = 'flex';
                    window.location.href = targetUrl;
                } else {
                    showError();
                }
            },
            () => {}  // ignore scan failure เพื่อสแกนต่อเนื่อง
        ).catch(err => {
            errorEl.style.display = 'block';
            errorEl.innerHTML = `<i class="fas fa-exclamation-triangle"></i> ບໍ່ສາມາດເປີດກ້ອງ: ${err}`;
            startBtn.style.display = 'block';
        });

        // เพิ่มการโฟกัสเฉพาะ QR (แตะจอเพื่อ force focus)
        setTimeout(() => {
            const video = document.querySelector("#reader video");
            if (video) {
                video.addEventListener('touchstart', (e) => {
                    e.preventDefault();  // ป้องกัน zoom หรือ scroll
                    const stream = video.srcObject;
                    if (stream) {
                        const track = stream.getVideoTracks()[0];
                        if (track) {
                            const capabilities = track.getCapabilities();
                            if (capabilities.focusMode) {
                                track.applyConstraints({ advanced: [{ focusMode: "single-shot" }] })
                                    .then(() => {
                                        // หลัง single-shot กลับ continuous เพื่อสแกนต่อ
                                        setTimeout(() => {
                                            track.applyConstraints({ advanced: [{ focusMode: "continuous" }] });
                                        }, 1500);
                                    }).catch(console.log);
                            }
                        }
                    }
                }, { passive: false });
            }
        }, 2000);  // รอ video โหลด
    }

    function showError() {
        errorEl.style.display = 'block';
        errorEl.innerHTML = '<i class="fas fa-times-circle"></i> QR ບໍ່ຖືກຕ້ອງ ຫຼື ບໍ່ແມ່ນຂອງລະບົບ';
        setTimeout(() => { isScanning = false; }, 4000);
    }

    // เริ่มอัตโนมัติ
    startScanner();

    startBtn.addEventListener('click', startScanner);
});
</script>

<?php require_once '../includes/footer.php'; ?>