<?php 
// Filename: scanner_view.php
require 'config.php'; 
requireLogin(); 
$geo_enabled = getSetting('geolocation_enabled', '1');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Scan Attendance</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background-color: var(--bg-color); 
            height: 100vh; 
            display: flex; 
            flex-direction: column; 
            overflow: hidden; 
            padding-bottom: 90px; 
        }

        .app-header {
            background: var(--primary-grad);
            padding: 30px 20px 100px 20px; 
            border-radius: 0 0 35px 35px;
            color: white;
            text-align: center;
            flex-shrink: 0;
        }

        .scanner-wrapper {
            flex-grow: 1; display: flex; flex-direction: column;
            align-items: center; 
            margin-top: -80px; 
            padding: 0 20px;
            position: relative; z-index: 10;
            overflow-y: auto;
        }

        .camera-card {
            background: white; width: 100%; max-width: 400px;
            border-radius: 24px; padding: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.15);
            display: flex; flex-direction: column; align-items: center;
            min-height: 400px; 
        }

        .scan-frame { 
            width: 100%; 
            border-radius: 16px; overflow: hidden;
            background: #000; position: relative;
            aspect-ratio: 1 / 1;
        }
        #reader { width: 100%; height: 100%; object-fit: cover; }
        
        .scan-guide {
            position: absolute; top: 20px; left: 20px; right: 20px; bottom: 20px;
            border: 2px dashed rgba(255,255,255,0.6); border-radius: 12px;
            pointer-events: none; z-index: 20;
            box-shadow: 0 0 0 1000px rgba(0,0,0,0.3); 
        }

        .status-badge {
            margin-top: 15px; padding: 8px 16px; border-radius: 20px;
            background: #f1f5f9; color: #64748b; font-size: 0.8rem; font-weight: 600;
            display: flex; align-items: center; gap: 8px;
        }
        .dot { width: 8px; height: 8px; border-radius: 50%; background: #cbd5e1; }
        .dot.active { background: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2); }
        .dot.error { background: #ef4444; }

        /* LOCATION INFO BOX */
        .location-info {
            width: 100%;
            margin-top: 12px;
            padding: 12px 16px;
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border: 1px solid #bae6fd;
            border-radius: 16px;
            font-size: 0.75rem;
        }
        .location-info.verified {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border-color: #bbf7d0;
        }
        .location-info.warning {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            border-color: #fcd34d;
        }
        .location-info.error {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            border-color: #fca5a5;
        }
        .location-row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
        }
        .location-row:last-child {
            margin-bottom: 0;
        }
        .location-icon {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255,255,255,0.5);
            border-radius: 8px;
            font-size: 0.9rem;
        }
        .location-text {
            flex: 1;
            font-weight: 600;
            color: #334155;
        }
        .location-detail {
            font-size: 0.7rem;
            color: #64748b;
            font-weight: 500;
        }
        .pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .5; }
        }

        .permission-box {
            text-align: center; padding: 40px 20px;
        }
        .perm-icon {
            width: 80px; height: 80px; background: #eff6ff; color: #3b82f6;
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            font-size: 2rem; margin: 0 auto 20px auto;
        }

        .close-btn {
            margin-top: 20px; margin-bottom: 20px;
            color: #64748b; font-weight: 600; text-decoration: none; font-size: 0.9rem;
        }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Scan QR</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Align the QR code within the frame</div>
    </div>

    <div class="scanner-wrapper">
        <div class="camera-card">
            
            <div id="permission-screen" class="permission-box" style="display: none;">
                <div class="perm-icon"><i class="bi bi-geo-alt-fill"></i></div>
                <h5 class="fw-bold text-dark">Location Required</h5>
                <p class="text-muted small mb-4">We need to verify you are within school grounds to mark attendance.</p>
                <button onclick="requestLocation()" class="btn btn-primary w-100 rounded-pill fw-bold py-2 shadow-sm">
                    Enable Location
                </button>
            </div>

            <div id="camera-screen" style="display: none; width: 100%;">
                <div class="scan-frame">
                    <div class="scan-guide"></div>
                    <div id="reader"></div>
                </div>
                
                <div class="text-center">
                    <div class="status-badge d-inline-flex" id="statusIndicator">
                        <span class="dot active"></span> 
                        <span id="statusText">Scanning...</span>
                    </div>
                </div>

                <!-- LOCATION INFO BOX -->
                <div id="locationInfo" class="location-info" style="display: none;">
                    <div class="location-row">
                        <div class="location-icon">
                            <i class="bi bi-geo-alt-fill text-primary"></i>
                        </div>
                        <div>
                            <div class="location-text" id="locationStatus">Location verified</div>
                            <div class="location-detail" id="locationCoords">0.0000, 0.0000</div>
                        </div>
                    </div>
                    <div class="location-row" id="accuracyRow" style="display: none;">
                        <div class="location-icon">
                            <i class="bi bi-bullseye text-success"></i>
                        </div>
                        <div>
                            <div class="location-text">Accuracy</div>
                            <div class="location-detail" id="accuracyText">± 0m</div>
                        </div>
                    </div>
                </div>

            </div>

            <div id="result_screen" class="text-center p-4" style="display: none;">
                <div id="resIcon" class="mb-3 display-1 text-success"><i class="bi bi-check-circle-fill"></i></div>
                <h4 class="fw-bold text-dark" id="resTitle">Success!</h4>
                <p class="text-muted small mb-4" id="resMsg">Attendance marked.</p>
                <button id="resBtn" class="btn btn-primary w-100 rounded-pill fw-bold">Continue</button>
            </div>

        </div>

        <a href="dashboard.php" class="close-btn">Close Scanner</a>
    </div>

    <?php include 'menu.php'; ?>

    <script>
        const geoEnabled = "<?= $geo_enabled ?>";
        const permissionScreen = document.getElementById('permission-screen');
        const cameraScreen = document.getElementById('camera-screen');
        const resultScreen = document.getElementById('result_screen');
        const statusText = document.getElementById('statusText');
        const locationInfo = document.getElementById('locationInfo');
        const locationStatus = document.getElementById('locationStatus');
        const locationCoords = document.getElementById('locationCoords');
        const accuracyRow = document.getElementById('accuracyRow');
        const accuracyText = document.getElementById('accuracyText');
        
        let userLat = null;
        let userLon = null;
        let userAccuracy = null;
        let html5QrcodeScanner = null;

        // --- INIT LOGIC ---
        if (geoEnabled === '1') {
            permissionScreen.style.display = 'block';
        } else {
            cameraScreen.style.display = 'block';
            startScanner();
        }

        // --- 1. GEOLOCATION ---
        function requestLocation() {
            permissionScreen.innerHTML = `<div class="perm-icon"><span class="spinner-border text-primary"></span></div><h5 class="fw-bold">Locating...</h5>`;
            
            if (!navigator.geolocation) {
                permissionScreen.innerHTML = `
                    <div class="perm-icon bg-danger text-white">
                        <i class="bi bi-exclamation-octagon"></i>
                    </div>
                    <h5 class="fw-bold">Not Supported</h5>
                    <p class="small text-muted">Geolocation is not supported by this browser.</p>
                    <button class="btn btn-outline-secondary btn-sm rounded-pill" onclick="window.location.href='dashboard.php'">Go Back</button>
                `;
                return;
            }

            navigator.geolocation.getCurrentPosition(
                (position) => {
                    userLat = position.coords.latitude;
                    userLon = position.coords.longitude;
                    userAccuracy = position.coords.accuracy;
                    
                    permissionScreen.style.display = 'none';
                    cameraScreen.style.display = 'block';
                    updateLocationDisplay();
                    startScanner();
                },
                (error) => {
                    let errorMsg = 'Please allow location access in your browser settings.';
                    let errorIcon = 'exclamation-octagon';
                    
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMsg = 'Location access denied. Please enable location in your browser settings.';
                            errorIcon = 'x-circle';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMsg = 'Location information unavailable. Check your device settings.';
                            errorIcon = 'question-circle';
                            break;
                        case error.TIMEOUT:
                            errorMsg = 'Location request timed out. Please try again.';
                            errorIcon = 'clock';
                            break;
                    }
                    
                    permissionScreen.innerHTML = `
                        <div class="perm-icon bg-danger text-white">
                            <i class="bi bi-${errorIcon}"></i>
                        </div>
                        <h5 class="fw-bold">Location Error</h5>
                        <p class="small text-muted">${errorMsg}</p>
                        <button class="btn btn-danger btn-sm rounded-pill px-4" onclick="location.reload()">
                            <i class="bi bi-arrow-clockwise me-1"></i> Try Again
                        </button>
                    `;
                },
                { 
                    enableHighAccuracy: true, 
                    timeout: 10000,
                    maximumAge: 0 
                }
            );
        }

        // --- UPDATE LOCATION DISPLAY ---
        function updateLocationDisplay() {
            if (geoEnabled !== '1' || userLat === null || userLon === null) {
                return;
            }

            locationInfo.style.display = 'block';
            
            // Format coordinates (4 decimal places)
            const latStr = userLat.toFixed(4);
            const lonStr = userLon.toFixed(4);
            locationCoords.textContent = `${latStr}, ${lonStr}`;
            
            // Show accuracy if available
            if (userAccuracy !== null) {
                accuracyRow.style.display = 'flex';
                const accMeters = Math.round(userAccuracy);
                accuracyText.textContent = `± ${accMeters}m`;
                
                // Style based on accuracy
                if (accMeters <= 20) {
                    locationInfo.className = 'location-info verified';
                    locationStatus.textContent = 'Location verified';
                    accuracyText.innerHTML = `<i class="bi bi-check-circle-fill text-success me-1"></i>± ${accMeters}m (Excellent)`;
                } else if (accMeters <= 50) {
                    locationInfo.className = 'location-info';
                    locationStatus.textContent = 'Location detected';
                    accuracyText.innerHTML = `<i class="bi bi-check-circle text-primary me-1"></i>± ${accMeters}m (Good)`;
                } else {
                    locationInfo.className = 'location-info warning';
                    locationStatus.textContent = 'Location approximate';
                    accuracyText.innerHTML = `<i class="bi bi-exclamation-triangle text-warning me-1"></i>± ${accMeters}m (Low accuracy)`;
                }
            } else {
                locationInfo.className = 'location-info';
                locationStatus.textContent = 'Location detected';
            }
        }

        // --- 2. CAMERA START ---
        function startScanner() {
            // Check if camera API is available
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                showResult('error', 'Camera Not Available', 'Your browser does not support camera access.');
                return;
            }

            const config = { 
                fps: 10, 
                qrbox: {width: 250, height: 250},
                videoConstraints: {
                    facingMode: "environment" 
                },
                supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA]
            };
            
            html5QrcodeScanner = new Html5QrcodeScanner("reader", config, false);
            html5QrcodeScanner.render(onScanSuccess, onScanFailure);
        }

        // --- 3. SCAN SUCCESS ---
        function onScanSuccess(decodedText, decodedResult) {
            html5QrcodeScanner.clear();
            cameraScreen.style.display = 'none';
            showResult('loading', 'Verifying QR...', 'Please wait.');

            if(geoEnabled === '1' && (userLat === null || userLon === null)) {
                showResult('error', 'Location Lost', 'Please refresh and allow location.');
                return;
            }

            fetch('scan.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    qr_token: decodedText, 
                    lat: userLat, 
                    lon: userLon,
                    accuracy: userAccuracy 
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showResult('success', 'Success!', data.message, data.redirectUrl);
                } else {
                    showResult('error', 'Failed', data.message);
                }
            })
            .catch(err => {
                showResult('error', 'Network Error', 'Check your connection.');
            });
        }

        function onScanFailure(error) {
            // Silent handling of scan failures
        }

        // --- HELPER: SHOW RESULTS ---
        function showResult(type, title, msg, redirectUrl = null) {
            resultScreen.style.display = 'block';
            const iconEl = document.getElementById('resIcon');
            const btn = document.getElementById('resBtn');

            document.getElementById('resTitle').innerText = title;
            document.getElementById('resMsg').innerText = msg;

            if (type === 'success') {
                iconEl.className = 'mb-3 display-1 text-success animate__animated animate__bounceIn';
                iconEl.innerHTML = '<i class="bi bi-check-circle-fill"></i>';
                btn.className = 'btn btn-primary w-100 rounded-pill fw-bold';
                btn.innerText = 'Proceed';
                btn.onclick = () => window.location.href = redirectUrl || 'dashboard.php';
                setTimeout(() => window.location.href = redirectUrl || 'dashboard.php', 2000);

            } else if (type === 'error') {
                iconEl.className = 'mb-3 display-1 text-danger animate__animated animate__shakeX';
                iconEl.innerHTML = '<i class="bi bi-x-circle-fill"></i>';
                btn.className = 'btn btn-outline-danger w-100 rounded-pill fw-bold';
                btn.innerText = 'Try Again';
                btn.onclick = () => location.reload();

            } else if (type === 'loading') {
                iconEl.className = 'mb-3 display-1 text-primary';
                iconEl.innerHTML = '<div class="spinner-border" role="status"></div>';
                btn.style.display = 'none';
            }
        }
    </script>
</body>
</html>