<?php
require_once '../config/config.php';
require_once '../includes/classes/QRCode.php';

// Require admin login
requireRole('secretariat');

$pageTitle = 'QR Code Scanner - Secretariat - PSAU GAD';
$db = getDB();
$activityId = (int)get('id', 0);

// Get activity details
$stmt = $db->prepare("SELECT * FROM activities WHERE activity_id = ? AND is_active = 1");
$stmt->execute([$activityId]);
$activity = $stmt->fetch();

if (!$activity) {
    setFlashMessage('error', 'Activity not found');
    redirect('attendance.php');
}

// Handle QR code scan (AJAX)
if (isPost() && isset($_POST['qr_data'])) {
    header('Content-Type: application/json');
    
    try {
        $qrData = post('qr_data');
        $qrCode = new QRCode();
        
        // Verify and mark attendance
        $result = $qrCode->verifyAndMarkAttendance($qrData, $activityId);
        
        echo json_encode($result);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error processing QR code: ' . $e->getMessage()
        ]);
    }
    exit;
}

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

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4 max-w-4xl">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center mb-4">
                <a href="attendance.php" class="text-secretariat hover:text-secretariat-dark mr-4">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <h1 class="text-3xl font-bold text-gray-900">
                    <i class="fas fa-qrcode text-secretariat mr-3"></i>
                    QR Code Scanner
                </h1>
            </div>
            <p class="text-gray-600">Scan participant QR codes to mark attendance</p>
        </div>

        <!-- Activity Info -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-xl font-bold text-gray-900 mb-4">
                <?php echo htmlspecialchars($activity['title']); ?>
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                <div>
                    <p class="text-gray-600">
                        <i class="fas fa-calendar mr-2 text-secretariat"></i>
                        <?php echo formatDate($activity['activity_date']); ?>
                    </p>
                </div>
                <div>
                    <p class="text-gray-600">
                        <i class="fas fa-clock mr-2 text-secretariat"></i>
                        <?php echo formatTime($activity['start_time']); ?> - <?php echo formatTime($activity['end_time']); ?>
                    </p>
                </div>
                <div>
                    <p class="text-gray-600">
                        <i class="fas fa-map-marker-alt mr-2 text-secretariat"></i>
                        <?php echo htmlspecialchars($activity['venue']); ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Scanner Interface -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-8">
            <div class="p-6">
                <h3 class="text-lg font-bold text-gray-900 mb-4">
                    <i class="fas fa-camera mr-2 text-secretariat"></i>
                    Camera Scanner
                </h3>
                
                <!-- Video Preview -->
                <div id="qr-reader" class="rounded-lg overflow-hidden mb-4" style="width: 100%;"></div>

                <!-- Scanner Controls -->
                <div class="flex items-center justify-center space-x-4 mb-4">
                    <button id="start-scan" class="bg-green-500 text-white px-6 py-3 rounded-lg hover:bg-green-600 transition font-semibold">
                        <i class="fas fa-play mr-2"></i> Start Scanner
                    </button>
                    <button id="stop-scan" class="bg-red-500 text-white px-6 py-3 rounded-lg hover:bg-red-600 transition font-semibold" style="display: none;">
                        <i class="fas fa-stop mr-2"></i> Stop Scanner
                    </button>
                </div>

                <!-- Status Message -->
                <div id="scan-status" class="text-center text-gray-600">
                    <i class="fas fa-info-circle mr-2"></i>
                    Click "Start Scanner" to begin scanning QR codes
                </div>
            </div>
        </div>

        <!-- Recent Scans -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6">
                <h3 class="text-lg font-bold text-gray-900 mb-4">
                    <i class="fas fa-history mr-2 text-secretariat"></i>
                    Recent Scans
                </h3>
                <div id="recent-scans" class="space-y-3">
                    <p class="text-center text-gray-500 text-sm py-4">No scans yet</p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$additionalJS = "
<script src='https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js'></script>
<script>
let html5QrCode;
let isScanning = false;

document.getElementById('start-scan').addEventListener('click', function() {
    startScanner();
});

document.getElementById('stop-scan').addEventListener('click', function() {
    stopScanner();
});

function startScanner() {
    html5QrCode = new Html5QrcodeScanner('qr-reader', {
        fps: 10,
        qrbox: { width: 250, height: 250 },
        aspectRatio: 1.0
    });

    html5QrCode.render(onScanSuccess, onScanError);

    isScanning = true;
    document.getElementById('start-scan').style.display = 'none';
    document.getElementById('stop-scan').style.display = 'inline-block';
    updateStatus('Scanner active. Point camera at QR code...', 'info');
}

function stopScanner() {
    if (html5QrCode && isScanning) {
        html5QrCode.clear();
        isScanning = false;
        document.getElementById('start-scan').style.display = 'inline-block';
        document.getElementById('stop-scan').style.display = 'none';
        updateStatus('Scanner stopped', 'info');
    }
}

function onScanSuccess(decodedText, decodedResult) {
    // Process the scanned QR code
    processQRCode(decodedText);
}

function onScanError(errorMessage) {
    // Ignore scan errors (happens when no QR code is in view)
}

function processQRCode(qrData) {
    // Temporarily stop scanning to prevent duplicate scans
    if (!isScanning) return;
    
    updateStatus('Processing QR code...', 'info');
    
    // Send to server
    fetch(window.location.href, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'qr_data=' + encodeURIComponent(qrData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateStatus(data.message, 'success');
            addRecentScan(data);
            
            // Play success sound (optional)
            playSound('success');
        } else {
            updateStatus(data.message, 'error');
            playSound('error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        updateStatus('Failed to process QR code', 'error');
        playSound('error');
    });
}

function updateStatus(message, type) {
    const statusDiv = document.getElementById('scan-status');
    let icon = 'fa-info-circle';
    let colorClass = 'text-gray-600';
    
    if (type === 'success') {
        icon = 'fa-check-circle';
        colorClass = 'text-green-600';
    } else if (type === 'error') {
        icon = 'fa-exclamation-circle';
        colorClass = 'text-red-600';
    }
    
    statusDiv.innerHTML = '<i class=\"fas ' + icon + ' mr-2\"></i>' + message;
    statusDiv.className = 'text-center font-semibold ' + colorClass;
}

function addRecentScan(data) {
    const recentScansDiv = document.getElementById('recent-scans');
    
    // Remove 'no scans' message
    if (recentScansDiv.querySelector('p')) {
        recentScansDiv.innerHTML = '';
    }
    
    const scanItem = document.createElement('div');
    scanItem.className = 'flex items-center justify-between p-3 bg-green-50 border border-green-200 rounded-lg';
    scanItem.innerHTML = `
        <div class=\"flex items-center\">
            <div class=\"w-10 h-10 bg-green-500 rounded-full flex items-center justify-center text-white font-semibold mr-3\">
                <i class=\"fas fa-check\"></i>
            </div>
            <div>
                <h4 class=\"font-semibold text-gray-900\">\${data.employee_name || 'Employee'}</h4>
                <p class=\"text-xs text-gray-600\">\${data.status_text || 'Attendance marked'}</p>
            </div>
        </div>
        <span class=\"px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700\">
            <i class=\"fas fa-clock mr-1\"></i> Just now
        </span>
    `;
    
    recentScansDiv.insertBefore(scanItem, recentScansDiv.firstChild);
    
    // Keep only last 5 scans
    while (recentScansDiv.children.length > 5) {
        recentScansDiv.removeChild(recentScansDiv.lastChild);
    }
}

function playSound(type) {
    // Optional: Add sound effects
    // You can use Web Audio API or HTML5 Audio
}

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    if (isScanning) {
        stopScanner();
    }
});
</script>
";

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

