<div class="row">
    <div class="col-12 col-md-8 offset-md-2">
        <div class="card">
            <div class="card-header">
                <h2>Scan QR Code Aset</h2>
            </div>
            <div class="card-body text-center">
                <p>Arahkan kamera ke QR Code yang tertempel pada aset.</p>
                <div id="qr-reader" style="width: 100%; max-width: 500px; margin: auto;"></div>
                <div id="qr-reader-results" class="mt-3"></div>
            </div>
            <div class="card-footer text-muted">
                Pastikan Anda memberikan izin akses kamera pada browser.
            </div>
        </div>
    </div>
</div>

<!-- html5-qrcode library -->
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const resultsContainer = document.getElementById('qr-reader-results');
        let lastResult, countResults = 0;

        function onScanSuccess(decodedText, decodedResult) {
            if (decodedText !== lastResult) {
                lastResult = decodedText;
                resultsContainer.innerHTML = `<div class="alert alert-success">Scan berhasil! Mengalihkan ke halaman maintenance...</div>`;

                // Attempt to extract asset ID. Assuming QR code contains just the ID or "id=ID"
                let assetId = null;
                try {
                    const urlParams = new URLSearchParams(decodedText.split('?')[1]); // Try to parse as URL
                    if (urlParams.has('id')) { 
                        assetId = urlParams.get('id');
                    }
                } catch (e) {
                    // Not a URL with params, try direct ID
                }
                
                if (assetId === null && !isNaN(decodedText) && decodedText.trim() !== '') { // if QR contains just the number ID
                    assetId = decodedText;
                }

                if (assetId) {
                    window.location.href = `?page=maintenance_form&id_aset=${assetId}`;
                } else {
                    console.error("QR Code tidak mengandung ID Aset yang dikenali:", decodedText);
                    resultsContainer.innerHTML = `<div class="alert alert-danger">QR Code tidak valid. Pastikan berisi ID Aset atau URL yang valid. (${decodedText})</div>`;
                }
            }
        }

        function onScanFailure(error) {
            // handle scan failure, usually better to ignore and keep scanning.
            // console.warn(`Code scan error = ${error}`);
        }

        let html5QrcodeScanner = new Html5QrcodeScanner(
            "qr-reader", 
            { fps: 10, qrbox: { width: 250, height: 250 } },
            /* verbose= */ false
        );

        html5QrcodeScanner.render(onScanSuccess, onScanFailure);
    });
</script>
