<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>`;

                let assetId = null;
                try {
                    // The scanned URL contains '...&id_aset=X'
                    const url = new URL(decodedText);
                    if (url.searchParams.has('id_aset')) { // Check for the correct parameter
                        assetId = url.searchParams.get('id_aset');
                    }
                } catch (e) {
                    // Not a full URL, maybe it's just a number
                    console.log("Scanned text is not a full URL. Checking if it is a numeric ID.");
                }
                
                // If parsing the URL fails, check if the scanned text is just a plain number.
                if (assetId === null && !isNaN(decodedText) && decodedText.trim() !== '') {
                    assetId = decodedText.trim();
                }

                if (assetId) {
                    // Always redirect to the maintenance form, as per user's request.
                    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>
