<?php
session_start();
require_once '../config.php';

// Cek apakah user sudah login dan role-nya guru
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'guru') {
    header('Location: ../login.php');
    exit();
}

$current_user = $_SESSION['user'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aplikasi Kehadiran Ujian - Guru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .navbar-brand {
            font-weight: bold;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .btn-action {
            margin: 5px;
        }
        #scanner-container {
            position: relative;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            display: none;
        }
        #qr-video {
            width: 100%;
            border-radius: 8px;
            background-color: #f8f9fa;
        }
        #qr-canvas {
            display: none;
        }
        .scan-overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 250px;
            height: 250px;
            border: 3px solid #007bff;
            border-radius: 8px;
            pointer-events: none;
            box-shadow: 0 0 0 100vmax rgba(0,0,0,0.5);
        }
        .scan-line {
            position: absolute;
            width: 100%;
            height: 2px;
            background: #007bff;
            top: 0;
            animation: scan 2s linear infinite;
        }
        @keyframes scan {
            0% { top: 0; }
            50% { top: 100%; }
            100% { top: 0; }
        }
        .camera-permission {
            padding: 20px;
            text-align: center;
            background-color: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        #manual-input {
            display: none;
        }
        .scanner-active {
            display: block !important;
        }
        .toast-container {
            z-index: 1055;
        }
        .mobile-warning {
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .browser-list {
            list-style: none;
            padding: 0;
        }
        .browser-list li {
            padding: 5px 0;
        }
        .browser-list i {
            width: 20px;
            margin-right: 10px;
        }
        .user-info {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="fas fa-qrcode me-2"></i>Kehadiran Ujian - Guru
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
             <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-camera me-1"></i>Scan QR
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="data_kehadiran.php">
                            <i class="fas fa-database me-1"></i>Data Kehadiran
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../logout.php">
                            <i class="fas fa-sign-out-alt me-1"></i>Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Konten Utama -->
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 mx-auto">
                
                <!-- Info Pengguna -->
                <div class="user-info">
                    <h5><i class="fas fa-user-tie me-2"></i>Selamat Datang, <?= htmlspecialchars($current_user['nama_lengkap']); ?></h5>
                    <p class="mb-0">Anda login sebagai <strong>Guru Pengawas Ujian</strong></p>
                </div>

                <!-- Warning untuk Mobile -->
                <div id="mobile-warning" class="mobile-warning" style="display: none;">
                    <h5><i class="fas fa-mobile-alt me-2"></i>Tips untuk Perangkat Mobile</h5>
                    <p class="mb-2">Jika scanner tidak bekerja di perangkat mobile:</p>
                    <ul class="browser-list">
                        <li><i class="fas fa-check-circle"></i>Gunakan browser <strong>Chrome</strong> atau <strong>Firefox</strong></li>
                        <li><i class="fas fa-check-circle"></i>Pastikan mengakses via <strong>HTTPS</strong></li>
                        <li><i class="fas fa-check-circle"></i>Berikan izin kamera ketika diminta</li>
                    </ul>
                </div>

                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0"><i class="fas fa-camera me-2"></i>Scanner Kehadiran Ujian</h4>
                    </div>
                    <div class="card-body">
                        <!-- Pilih Mata Pelajaran -->
                        <div class="mb-4">
                            <label for="mapel" class="form-label">Pilih Mata Pelajaran</label>
                            <select class="form-select" id="mapel" required>
                                <option value="">-- Pilih Mata Pelajaran --</option>
                                <?php
                                $sql = "SELECT * FROM ujn_mata_pelajaran";
                                $result = $conn->query($sql);
                                if ($result && $result->num_rows > 0) {
                                    while($row = $result->fetch_assoc()) {
                                        echo "<option value='{$row['kode_mapel']}'>{$row['nama_mapel']}</option>";
                                    }
                                } else {
                                    echo "<option value=''>Tidak ada mata pelajaran</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- Info Izin Kamera -->
                        <div id="camera-permission" class="camera-permission">
                            <i class="fas fa-camera fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Kamera akan diaktifkan ketika tombol "Mulai Scan" ditekan</p>
                            <small class="text-muted">Pastikan Anda memberikan izin akses kamera ketika diminta</small>
                            
                            <!-- Info Tambahan untuk Mobile -->
                            <div id="mobile-camera-info" style="display: none;" class="mt-3 p-3 bg-warning rounded">
                                <small>
                                    <i class="fas fa-info-circle me-1"></i>
                                    <strong>Tips Mobile:</strong> Jika kamera tidak bisa diakses, gunakan browser Chrome/Firefox.
                                </small>
                            </div>
                        </div>

                        <!-- Scanner QR Code -->
                        <div id="scanner-container" class="mb-3">
                            <video id="qr-video" playsinline></video>
                            <canvas id="qr-canvas"></canvas>
                            <div class="scan-overlay">
                                <div class="scan-line"></div>
                            </div>
                        </div>

                        <!-- Status Scanner -->
                        <div id="scanner-status" class="alert alert-info text-center">
                            <i class="fas fa-info-circle me-2"></i>Pilih mata pelajaran dan mulai scan QR Code
                        </div>

                        <!-- Tombol Aksi -->
                        <div class="text-center">
                            <button id="start-scanner" class="btn btn-success">
                                <i class="fas fa-play me-2"></i>Mulai Scan
                            </button>
                            <button id="stop-scanner" class="btn btn-danger" disabled>
                                <i class="fas fa-stop me-2"></i>Stop Scan
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
    
    <script>
        // Inisialisasi variabel
        let videoStream = null;
        let isScannerActive = false;
        let scanInterval = null;
        let lastScannedCode = null;
        let scanCooldown = false;
        const video = document.getElementById('qr-video');
        const canvas = document.getElementById('qr-canvas');
        const scannerContainer = document.getElementById('scanner-container');
        const cameraPermission = document.getElementById('camera-permission');
        const startBtn = document.getElementById('start-scanner');
        const stopBtn = document.getElementById('stop-scanner');
        const scannerStatus = document.getElementById('scanner-status');
        const mapelSelect = document.getElementById('mapel');
        const mobileWarning = document.getElementById('mobile-warning');
        const mobileCameraInfo = document.getElementById('mobile-camera-info');

        // Deteksi perangkat mobile
        function isMobileDevice() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
                   (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
        }

        // Fungsi untuk menampilkan modal popup
        function showModal(title, message, type = 'info', autoClose = true, duration = 3000) {
            // Hapus modal yang sudah ada
            const existingModal = document.getElementById('dynamic-modal');
            if (existingModal) {
                existingModal.remove();
            }

            const modalClass = {
                'success': 'text-success',
                'warning': 'text-warning',
                'danger': 'text-danger',
                'info': 'text-info'
            };

            const modalIcon = {
                'success': 'fa-check-circle',
                'warning': 'fa-exclamation-triangle',
                'danger': 'fa-times-circle',
                'info': 'fa-info-circle'
            };

            const modalHTML = `
                <div class="modal fade" id="dynamic-modal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header border-0">
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center">
                                <i class="fas ${modalIcon[type]} ${modalClass[type]}" style="font-size: 4rem;"></i>
                                <h4 class="mt-3 ${modalClass[type]}">${title}</h4>
                                <div class="mt-3">${message}</div>
                            </div>
                            <div class="modal-footer border-0 justify-content-center">
                                <button type="button" class="btn btn-${type}" data-bs-dismiss="modal">
                                    OK
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Tambahkan modal ke body
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            // Tampilkan modal
            const modal = new bootstrap.Modal(document.getElementById('dynamic-modal'));
            modal.show();
            
            // Auto close jika diaktifkan
            if (autoClose) {
                setTimeout(() => {
                    if (document.getElementById('dynamic-modal')) {
                        modal.hide();
                    }
                }, duration);
            }
            
            // Hapus modal setelah ditutup
            document.getElementById('dynamic-modal').addEventListener('hidden.bs.modal', function () {
                this.remove();
            });
        }

        // Fungsi untuk menampilkan alert modal
        function showAlert(message, type = 'danger') {
            const alertTitle = {
                'success': 'Berhasil!',
                'warning': 'Peringatan!',
                'danger': 'Error!',
                'info': 'Informasi'
            };

            showModal(alertTitle[type], message, type, true, null);
        }

        // Cek dukungan kamera
        function checkCameraSupport() {
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                const message = isMobileDevice() ? 
                    'Browser tidak mendukung akses kamera. Gunakan Chrome atau Firefox di perangkat mobile.' :
                    'Browser tidak mendukung akses kamera. Gunakan browser modern seperti Chrome, Firefox, atau Edge.';
                showAlert(message, 'warning');
                return false;
            }

            if (isMobileDevice()) {
                mobileWarning.style.display = 'block';
                mobileCameraInfo.style.display = 'block';
            }

            return true;
        }

        // Fungsi untuk memulai scanner
        async function startScanner() {
            if (!mapelSelect.value) {
                showAlert('Pilih mata pelajaran terlebih dahulu!', 'warning');
                return;
            }

            if (!checkCameraSupport()) {
                return;
            }

            try {
                scannerStatus.innerHTML = '<i class="fas fa-camera me-2"></i>Mengaktifkan kamera...';
                scannerStatus.className = 'alert alert-warning text-center';
                
                startBtn.disabled = true;
                
                const constraints = {
                    video: {
                        facingMode: 'environment',
                        width: { ideal: isMobileDevice() ? 640 : 1280 },
                        height: { ideal: isMobileDevice() ? 480 : 720 }
                    }
                };

                videoStream = await navigator.mediaDevices.getUserMedia(constraints);

                video.srcObject = videoStream;
                
                video.onloadedmetadata = function() {
                    video.play();
                    
                    scannerContainer.style.display = 'block';
                    cameraPermission.style.display = 'none';
                    scannerStatus.innerHTML = '<i class="fas fa-camera me-2"></i>Scanner aktif - Arahkan kamera ke QR Code';
                    scannerStatus.className = 'alert alert-success text-center';
                    
                    startBtn.disabled = true;
                    stopBtn.disabled = false;
                    isScannerActive = true;
                    
                    lastScannedCode = null;
                    scanCooldown = false;
                    
                    startScanning();
                };
                
            } catch (error) {
                console.error('Error starting scanner:', error);
                let errorMsg = 'Gagal mengaktifkan kamera: ';
                
                if (error.name === 'NotAllowedError') {
                    errorMsg = 'Izin kamera ditolak. ';
                    if (isMobileDevice()) {
                        errorMsg += 'Pastikan Anda memberikan izin akses kamera di pengaturan browser.';
                    } else {
                        errorMsg += 'Silakan berikan izin akses kamera.';
                    }
                } else if (error.name === 'NotFoundError') {
                    errorMsg = 'Tidak ada kamera yang ditemukan.';
                } else if (error.name === 'NotSupportedError') {
                    errorMsg = 'Browser tidak mendukung fitur ini.';
                } else if (error.name === 'NotReadableError') {
                    errorMsg = 'Kamera sedang digunakan oleh aplikasi lain.';
                } else {
                    errorMsg += error.message;
                }
                
                showAlert(errorMsg, 'danger');
                scannerStatus.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>Gagal mengaktifkan scanner';
                scannerStatus.className = 'alert alert-danger text-center';
                startBtn.disabled = false;
            }
        }

        // Fungsi untuk memulai proses scanning
        function startScanning() {
            const canvasElement = document.getElementById('qr-canvas');
            const canvas = canvasElement.getContext('2d');

            scanInterval = setInterval(() => {
                if (video.readyState === video.HAVE_ENOUGH_DATA && !scanCooldown) {
                    canvasElement.height = video.videoHeight;
                    canvasElement.width = video.videoWidth;
                    canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
                    
                    const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
                    const code = jsQR(imageData.data, imageData.width, imageData.height, {
                        inversionAttempts: "dontInvert",
                    });
                    
                    if (code && code.data !== lastScannedCode) {
                        lastScannedCode = code.data;
                        handleScanResult(code.data);
                    }
                }
            }, 200);
        }

        // Fungsi untuk menghentikan scanner
        function stopScanner() {
            if (scanInterval) {
                clearInterval(scanInterval);
                scanInterval = null;
            }
            
            if (videoStream) {
                videoStream.getTracks().forEach(track => track.stop());
                videoStream = null;
            }
            
            if (video.srcObject) {
                video.srcObject = null;
            }
            
            scannerContainer.style.display = 'none';
            cameraPermission.style.display = 'block';
            scannerStatus.innerHTML = '<i class="fas fa-info-circle me-2"></i>Scanner dihentikan';
            scannerStatus.className = 'alert alert-info text-center';
            startBtn.disabled = false;
            stopBtn.disabled = true;
            isScannerActive = false;
            
            lastScannedCode = null;
            scanCooldown = false;
        }

        // Event listeners
        startBtn.addEventListener('click', startScanner);
        stopBtn.addEventListener('click', stopScanner);

        // Fungsi untuk menangani hasil scan
        function handleScanResult(qrData) {
            const dataParts = qrData.split(':');
            if (dataParts.length !== 3) {
                showAlert('Format QR Code tidak valid! Pastikan QR Code berasal dari sistem ini.', 'warning');
                return;
            }

            const nis = dataParts[0];
            const nama = dataParts[1];
            const kelas = dataParts[2];
            const kodeMapel = mapelSelect.value;

            scanCooldown = true;
            setTimeout(() => {
                scanCooldown = false;
            }, 2000);

            scannerStatus.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Menyimpan data kehadiran...';
            scannerStatus.className = 'alert alert-warning text-center';

            fetch('proses_kehadiran.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `nis=${encodeURIComponent(nis)}&kode_mapel=${encodeURIComponent(kodeMapel)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Tampilkan modal sukses dengan detail kehadiran
                    const successMessage = `
                        <div class="text-start">
                            <p><strong>NIS:</strong> ${nis}</p>
                            <p><strong>Nama:</strong> ${nama}</p>
                            <p><strong>Kelas:</strong> ${kelas}</p>
                            <p><strong>Mata Pelajaran:</strong> ${mapelSelect.options[mapelSelect.selectedIndex].text}</p>
                            <p><strong>Tanggal:</strong> ${data.tanggal}</p>
                            <p><strong>Jam:</strong> ${data.jam}</p>
                        </div>
                    `;
                    showModal('Kehadiran Berhasil!', successMessage, 'success', true, 5000);
                    
                    if (isScannerActive) {
                        scannerStatus.innerHTML = '<i class="fas fa-camera me-2"></i>Scanner aktif - Arahkan kamera ke QR Code';
                        scannerStatus.className = 'alert alert-success text-center';
                    }
                } else {
                    // Tampilkan pesan error khusus untuk data duplikat
                    let alertType = 'warning';
                    let alertTitle = 'Peringatan!';
                    
                    if (data.message.includes('sudah pernah') || data.message.includes('sudah ada')) {
                        alertType = 'info';
                        alertTitle = 'Informasi';
                        
                        const duplicateMessage = `
                            <div class="text-start">
                                <p><strong>NIS:</strong> ${nis}</p>
                                <p><strong>Nama:</strong> ${nama}</p>
                                <p><strong>Kelas:</strong> ${kelas}</p>
                                <p><strong>Mata Pelajaran:</strong> ${mapelSelect.options[mapelSelect.selectedIndex].text}</p>
                                <p><strong>Status:</strong> ${data.message}</p>
                                ${data.tanggal_scan ? `<p><strong>Terakhir Scan:</strong> ${data.tanggal_scan}</p>` : ''}
                            </div>
                        `;
                        showModal(alertTitle, duplicateMessage, alertType, true, 5000);
                    } else {
                        showAlert(data.message, alertType);
                    }
                    
                    if (isScannerActive) {
                        scannerStatus.innerHTML = '<i class="fas fa-camera me-2"></i>Scanner aktif - Arahkan kamera ke QR Code';
                        scannerStatus.className = 'alert alert-success text-center';
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('Terjadi kesalahan saat menyimpan data kehadiran', 'danger');
                if (isScannerActive) {
                    scannerStatus.innerHTML = '<i class="fas fa-camera me-2"></i>Scanner aktif - Arahkan kamera ke QR Code';
                    scannerStatus.className = 'alert alert-success text-center';
                }
            });
        }

        // Cleanup ketika halaman ditutup
        window.addEventListener('beforeunload', () => {
            if (isScannerActive) {
                stopScanner();
            }
        });

        // Inisialisasi saat halaman dimuat
        document.addEventListener('DOMContentLoaded', function() {
            if (isMobileDevice()) {
                mobileWarning.style.display = 'block';
                mobileCameraInfo.style.display = 'block';
            }
            
            if (!checkCameraSupport()) {
                startBtn.disabled = true;
            }
        });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>