<?php
require_once __DIR__ . '/config/auth.php';
require_login();

$pageTitle = 'Guard QR Scanner';
$activePage = 'guard_scan';

include __DIR__ . '/includes/header.php';
?>

<section class="content-panel">
    <div class="panel-heading">
        <div>
            <h2>Guard QR Scanner</h2>
            <p>Scan a gatepass QR code to verify pass details.</p>
        </div>
    </div>

    <div id="scanAlert" class="alert d-none"></div>

    <div class="row g-4">
        <div class="col-md-5">
            <div id="qr-reader" style="width:100%;"></div>
        </div>

        <div class="col-md-7">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h5>Scan Result</h5>
                    <div id="scanResult" class="text-muted">
                        No QR scanned yet.
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="https://unpkg.com/html5-qrcode"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const resultBox = document.getElementById('scanResult');
    const alertBox = document.getElementById('scanAlert');

    function showAlert(message, type = 'danger') {
        alertBox.className = 'alert alert-' + type;
        alertBox.textContent = message;
        alertBox.classList.remove('d-none');
    }

    function extractReference(text) {
        const match = text.match(/GP-[A-Z0-9-]+/i);
        return match ? match[0].trim() : text.trim();
    }

    async function verifyQr(qrText) {
        const reference = extractReference(qrText);

        resultBox.innerHTML = `
            <div class="text-muted">Checking reference...</div>
            <strong>${reference}</strong>
        `;

        const formData = new FormData();
        formData.append('transaction_ref', reference);

        try {
            const response = await fetch('api/guard_scan.php', {
                method: 'POST',
                body: formData,
                headers: {
                    Accept: 'application/json'
                }
            });

            const result = await response.json();

            if (!result.success) {
                showAlert(result.message || 'Pass not found.');
                resultBox.innerHTML = '<span class="text-danger">Pass not found.</span>';
                return;
            }

            const pass = result.data;

            resultBox.innerHTML = `
                <div class="mb-2">
                    <small class="text-muted">Transaction Ref</small>
                    <h4>${pass.transaction_ref}</h4>
                </div>

                <div class="mb-2">
                    <small class="text-muted">Pass Type</small>
                    <div>${pass.pass_type}</div>
                </div>

                <div class="mb-2">
                    <small class="text-muted">Name / Description</small>
                    <div>${pass.main_name}</div>
                </div>

                <div class="mb-2">
                    <small class="text-muted">Date</small>
                    <div>${pass.pass_date || 'N/A'}</div>
                </div>

                <div class="mb-2">
                    <small class="text-muted">Status</small>
                    <span class="badge bg-warning text-dark">${pass.status}</span>
                </div>
            `;
        } catch (error) {
            showAlert('Unable to connect to server.');
        }
    }

    const scanner = new Html5QrcodeScanner(
        "qr-reader",
        {
            fps: 10,
            qrbox: 250
        }
    );

    scanner.render(function (decodedText) {
        verifyQr(decodedText);
    });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>