<?php
/**
 * Patrol QR Scanner Component
 * Standalone scanner interface with post selector
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Get the post_id from URL if provided
$selectedPostId = $_GET['post_id'] ?? null;

// Get guard's available posts (or all posts for managers/admins)
if ($userRole === 'guard') {
    // Guard sees only their assigned posts
    $posts = $db->fetchAll(
        "SELECT DISTINCT p.* FROM posts p
         JOIN guard_post_assignments gpa ON p.id = gpa.post_id
         WHERE gpa.guard_id = ? AND p.active = 1
         ORDER BY p.name ASC",
        [$_SESSION['user_id']]
    );
} else {
    // Admin/Manager/Controller see all active posts
    $posts = $db->fetchAll(
        "SELECT * FROM posts WHERE active = 1 ORDER BY name ASC"
    );
}

// Set selected post
if (!$selectedPostId && !empty($posts)) {
    $selectedPostId = $posts[0]['id'];
}

$selectedPost = $selectedPostId ? $db->fetch("SELECT * FROM posts WHERE id = ?", [$selectedPostId]) : null;
?>

<div class="scanner-interface">
    <!-- Post Selector (if multiple posts) -->
    <?php if (count($posts) > 1): ?>
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <label class="block text-sm font-semibold text-gray-700 mb-3">
            <i class="fas fa-building mr-2 text-blue-600"></i><?php echo Language::get('select_post'); ?>
        </label>
        <select id="postSelector" onchange="selectPost()" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
            <?php foreach ($posts as $post): ?>
            <option value="<?php echo $post['id']; ?>" <?php echo ($post['id'] == $selectedPostId) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($post['name']); ?> - <?php echo htmlspecialchars($post['location']); ?>
            </option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php endif; ?>

    <?php if ($selectedPost): ?>
    <!-- Post Info -->
    <div class="bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg shadow p-6 mb-6">
        <div class="flex items-start justify-between">
            <div>
                <h2 class="text-2xl font-bold"><?php echo htmlspecialchars($selectedPost['name']); ?></h2>
                <p class="text-blue-100 mt-2">
                    <i class="fas fa-map-marker-alt mr-2"></i><?php echo htmlspecialchars($selectedPost['location']); ?>
                </p>
            </div>
            <div id="currentTime" class="text-right">
                <p class="text-3xl font-bold" id="timeDisplay">00:00:00</p>
                <p class="text-sm text-blue-100"><?php echo Language::get('current_time'); ?></p>
            </div>
        </div>
    </div>

    <!-- Scanner Section -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">
            <i class="fas fa-qrcode text-blue-600 mr-2"></i><?php echo Language::get('scan_qr_code'); ?>
        </h3>

        <div class="scanner-box border-2 border-gray-300 rounded-lg p-4 bg-gray-50">
            <div id="qr-reader" style="width: 100%; min-height: 400px; border-radius: 6px;"></div>
            <div class="scanner-controls mt-4 flex gap-3 justify-center">
                <button class="btn btn-primary px-6 py-2 flex items-center gap-2" id="start-scanner" onclick="startScanner()">
                    <i class="fas fa-camera"></i><?php echo Language::get('start_scanner'); ?>
                </button>
                <button class="btn btn-secondary px-6 py-2 flex items-center gap-2" id="stop-scanner" style="display:none;" onclick="stopScanner()">
                    <i class="fas fa-stop"></i><?php echo Language::get('stop_scanner'); ?>
                </button>
            </div>
            <p class="text-center text-gray-500 text-sm mt-3">
                <i class="fas fa-info-circle mr-1"></i><?php echo Language::get('point_name'); ?>: <?php echo Language::get('scan_qr_code'); ?>
            </p>
        </div>
    </div>

    <!-- Last Scan Info -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Current Scan Result -->
        <div class="bg-white rounded-lg shadow p-6">
            <h4 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-check-circle text-green-600 mr-2"></i><?php echo Language::get('last_scan_info'); ?>
            </h4>
            <div id="last-scan-card" class="bg-gray-50 p-4 rounded-lg text-center text-gray-500 italic">
                <?php echo Language::get('no_scans_yet'); ?>
            </div>
        </div>

        <!-- Scan Counter -->
        <div class="bg-white rounded-lg shadow p-6">
            <h4 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-list-check text-blue-600 mr-2"></i><?php echo Language::get('scans'); ?>
            </h4>
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-blue-50 p-4 rounded-lg text-center">
                    <p class="text-3xl font-bold text-blue-600" id="scan-count">0</p>
                    <p class="text-sm text-gray-600"><?php echo Language::get('this_hour'); ?></p>
                </div>
                <div class="bg-purple-50 p-4 rounded-lg text-center">
                    <p class="text-3xl font-bold text-purple-600" id="total-scan-count">0</p>
                    <p class="text-sm text-gray-600"><?php echo Language::get('today'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Scans -->
    <div class="bg-white rounded-lg shadow p-6 mt-6">
        <h4 class="text-lg font-bold text-gray-800 mb-4">
            <i class="fas fa-history text-gray-600 mr-2"></i><?php echo Language::get('recent_scans'); ?>
        </h4>
        <div id="scans-list" class="space-y-2 max-h-64 overflow-y-auto">
            <p class="text-center text-gray-500 italic text-sm py-4"><?php echo Language::get('no_scans_yet'); ?></p>
        </div>
    </div>

    <?php else: ?>
    <!-- No Posts Available -->
    <div class="bg-white rounded-lg shadow border border-gray-200 p-12 text-center">
        <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
        <p class="text-gray-500 text-lg"><?php echo Language::get('no_posts_available'); ?></p>
        <p class="text-gray-400 text-sm mt-2"><?php echo Language::get('contact_administrator'); ?></p>
    </div>
    <?php endif; ?>
</div>

<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Scanner Configuration
let html5QrcodeScanner;
let scannerActive = false;
let currentPostId = <?php echo $selectedPostId ? $selectedPostId : 'null'; ?>;
let lastScannedQR = null;
let scanDebounceTimer = null;
let consecutiveScanCount = 0;
const SCAN_DEBOUNCE_MS = 200;  // Very short debounce for instant re-scanning
const CONSECUTIVE_SCAN_THRESHOLD = 1;  // Single detection is enough (already filtered by HTML5 QR library)

// Initialize scanner on load
document.addEventListener('DOMContentLoaded', function() {
    updateTimeDisplay();
    setInterval(updateTimeDisplay, 1000);
    loadScanStats();
});

function selectPost() {
    const postId = document.getElementById('postSelector').value;
    // Update URL without reload
    const url = new URL(window.location);
    url.searchParams.set('post_id', postId);
    window.history.replaceState({}, '', url);
    currentPostId = parseInt(postId);
    
    // Stop scanner if running
    if (scannerActive) {
        stopScanner();
    }
    
    // Reload scan stats
    loadScanStats();
}

function updateTimeDisplay() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    document.getElementById('timeDisplay').textContent = hours + ':' + minutes + ':' + seconds;
}

function loadScanStats() {
    if (!currentPostId) return;
    
    fetch(`?page=api&endpoint=patrol/dashboard&post_id=${currentPostId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                // Update scan count
                const currentStatus = data.data?.current_status || {};
                document.getElementById('scan-count').textContent = currentStatus.total_scans || 0;
                
                // Update today's total
                const todaySummary = data.data?.today_summary || {};
                document.getElementById('total-scan-count').textContent = todaySummary.total_scans || 0;
                
                // Update recent scans list
                updateRecentScans(data.data?.recent_scans || []);
                
                // Update last scan display
                if (data.data?.last_scan) {
                    updateLastScanDisplay(data.data.last_scan);
                }
            }
        })
        .catch(e => console.error('Failed to load scan stats:', e));
}

function startScanner() {
    if (!currentPostId) {
        Swal.fire({
            icon: 'warning',
            title: 'No Post Selected',
            text: 'Please select a post first',
            confirmButtonColor: '#3b82f6'
        });
        return;
    }
    
    scannerActive = true;
    lastScannedQR = null;
    consecutiveScanCount = 0;
    document.getElementById('start-scanner').style.display = 'none';
    document.getElementById('stop-scanner').style.display = 'inline-flex';
    
    try {
        html5QrcodeScanner = new Html5Qrcode("qr-reader");
        
        html5QrcodeScanner.start(
            { facingMode: "environment" },
            {
                fps: 60,                    // Ultra-fast 60 FPS for real-time detection
                qrbox: { width: 350, height: 350 }, // Larger scan box for better coverage
                aspectRatio: 1.0,
                disableFlip: true,
                formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE], // Only QR codes
                useBarCodeDetectorIfAvailable: true, // Use native scanner if available for better detection
                experimentalFeatures: {
                    useImageClipping: true  // Enable image clipping for better processing
                }
            },
            onScanSuccess,
            onScanError
        ).catch(err => {
            console.error('Failed to start scanner:', err);
            Swal.fire({
                icon: 'error',
                title: 'Camera Error',
                text: 'Unable to access camera. Please check permissions.',
                confirmButtonColor: '#3b82f6'
            });
            stopScanner();
        });
    } catch (error) {
        console.error('Scanner initialization error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Scanner Error',
            text: 'Unable to initialize camera. Please try again.',
            confirmButtonColor: '#3b82f6'
        });
        stopScanner();
    }
}

function stopScanner() {
    if (html5QrcodeScanner && scannerActive) {
        try {
            html5QrcodeScanner.stop().then(() => {
                cleanupScanner();
            }).catch(err => {
                console.error('Error stopping scanner:', err);
                cleanupScanner();
            });
        } catch (error) {
            console.error('Error in stopScanner:', error);
            cleanupScanner();
        }
    }
}

function cleanupScanner() {
    scannerActive = false;
    lastScannedQR = null;
    consecutiveScanCount = 0;
    if (scanDebounceTimer) clearTimeout(scanDebounceTimer);
    document.getElementById('start-scanner').style.display = 'inline-flex';
    document.getElementById('stop-scanner').style.display = 'none';
    html5QrcodeScanner = null;
}

function onScanSuccess(qrCode) {
    // More lenient detection - process immediately without requiring consecutive scans
    // The html5-qrcode library already has built-in validation
    if (qrCode && qrCode.trim().length > 0) {
        // Small debounce to prevent multiple submissions of the same code within 200ms
        if (qrCode === lastScannedQR && scanDebounceTimer) {
            // Same code detected recently, skip to prevent duplicates
            return;
        }
        
        lastScannedQR = qrCode;
        handleQRScan(qrCode);
        
        // Prevent duplicate submissions for 200ms
        if (scanDebounceTimer) clearTimeout(scanDebounceTimer);
        scanDebounceTimer = setTimeout(() => {
            lastScannedQR = null;
            scanDebounceTimer = null;
        }, SCAN_DEBOUNCE_MS);
    }
}

function onScanError(errorMessage) {
    // Suppress error logs - html5-qrcode produces many "not detected" errors which are normal
}

async function handleQRScan(qrCode) {
    try {
        console.log('Scan detected - Raw QR data:', qrCode);
        
        // Ensure we're sending the exact QR code detected, not a transformed version
        const scanData = {
            post_id: currentPostId,
            qr_code: qrCode,  // Send exactly as scanned
            device_info: navigator.userAgent
        };
        
        console.log('Submitting scan data:', scanData);
        
        const response = await fetch(`?page=api&endpoint=patrol/scan`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(scanData)
        });

        const data = await response.json();
        console.log('API Response:', data);

        if (data.success) {
            updateLastScanDisplay(data.point);
            loadScanStats();
            
            // Show SweetAlert success
            Swal.fire({
                icon: 'success',
                title: 'Scan Recorded!',
                html: `<strong>${data.point?.point_name || 'Point'}</strong> scanned successfully`,
                confirmButtonColor: '#10b981',
                timer: 200000,
                timerProgressBar: true,
                didClose: () => {
                    location.reload();
                }
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Scan Failed',
                text: data.error || 'Invalid QR code',
                confirmButtonColor: '#3b82f6'
            });
        }
    } catch (error) {
        console.error('Scan submission failed:', error);
        Swal.fire({
            icon: 'error',
            title: 'Connection Error',
            text: 'Failed to submit scan. Check your connection.',
            confirmButtonColor: '#3b82f6'
        });
    }
}

function updateLastScanDisplay(point) {
    const lastScanCard = document.getElementById('last-scan-card');
    if (lastScanCard && point) {
        const scanTime = point.scan_timestamp || point.last_scan_time;
        const scanDate = new Date(scanTime);
        lastScanCard.innerHTML = `
            <div class="text-left">
                <p class="text-lg font-bold text-gray-800">${point.point_name || 'Patrol Point'}</p>
                <p class="text-sm text-gray-600 mt-2">${scanDate.toLocaleTimeString()}</p>
                ${point.location_description ? `<p class="text-sm text-gray-500 mt-2"><i class="fas fa-map-pin mr-1"></i>${point.location_description}</p>` : ''}
            </div>
        `;
    }
}

function updateRecentScans(scans) {
    const scansList = document.getElementById('scans-list');
    if (!scansList) return;
    
    if (!scans || scans.length === 0) {
        scansList.innerHTML = `<p class="text-center text-gray-500 italic text-sm py-4"><?php echo Language::get('no_scans_yet'); ?></p>`;
        return;
    }
    
    let html = '';
    scans.forEach(scan => {
        const scanDate = new Date(scan.scan_timestamp);
        const timeStr = scanDate.toLocaleTimeString();
        const pointName = scan.point_name || 'Point';
        const guardName = scan.guard_name || 'Unknown Guard';
        
        html += `
            <div class="bg-gray-50 p-3 rounded border border-gray-200 text-sm">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="font-semibold text-gray-800">${pointName}</p>
                        <p class="text-gray-600 text-xs mt-1">${guardName}</p>
                    </div>
                    <span class="text-gray-500 text-xs">${timeStr}</span>
                </div>
            </div>
        `;
    });
    
    scansList.innerHTML = html;
}
</script>
