<?php
// === BLOK DEBUGGING: Selalu aktifkan saat pengembangan ===
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// =======================================================

session_start();
require_once 'db.php'; 

// Fungsi untuk menerjemahkan nama hari dari Inggris ke Indonesia (Dibutuhkan untuk Riwayat Kehadiran)
function translate_day_name($english_day) {
    $days = [
        'Sunday' => 'Minggu',
        'Monday' => 'Senin',
        'Tuesday' => 'Selasa',
        'Wednesday' => 'Rabu',
        'Thursday' => 'Kamis',
        'Friday' => 'Jumat',
        'Saturday' => 'Sabtu'
    ];
    return $days[$english_day] ?? $english_day;
}

// Cek login
if (!isset($_SESSION['is_siswa_logged_in']) || $_SESSION['is_siswa_logged_in'] !== true) {
    header("Location: login_siswa.php");
    exit;
}

$siswa_id = $_SESSION['siswa_id'];

// Ambil data siswa
$stmt_siswa = $pdo->prepare("SELECT s.*, k.nama_kelas FROM siswa s JOIN kelas k ON s.kelas_id = k.id WHERE s.siswa_id = ?");
$stmt_siswa->execute([$siswa_id]);
$siswa = $stmt_siswa->fetch(PDO::FETCH_ASSOC);

// === FIX UNTUK WARNING DI LINE 86 (dan kode setelahnya) ===
// Jika siswa tidak ditemukan (fetch mengembalikan false), paksa logout
if (!$siswa) {
    session_destroy();
    // Arahkan kembali ke login dengan pesan error opsional
    header("Location: login_siswa.php?error=siswa_not_found"); 
    exit;
}
// =======================================================

// Ambil data kehadiran bulan ini
$current_month = date('Y-m');
$stmt_kehadiran = $pdo->prepare("SELECT tanggal, status FROM kehadiran WHERE siswa_id = ? AND bulan = ? ORDER BY tanggal DESC");
$stmt_kehadiran->execute([$siswa_id, $current_month]);
$kehadiran = $stmt_kehadiran->fetchAll(PDO::FETCH_ASSOC);

// Hitung statistik
$total_hari = date('t'); // Total hari di bulan ini (misal 30 atau 31)
$hadir = 0; $izin = 0; $sakit = 0; $alpha = 0;
$total_recorded_days = 0; // Jumlah hari yang sudah direkam kehadirannya

foreach ($kehadiran as $k) {
    switch ($k['status']) {
        case 'H': $hadir++; break;
        case 'I': $izin++; break;
        case 'S': $sakit++; break;
        case 'A': $alpha++; break;
    }
    $total_recorded_days++;
}

// Perhitungan persentase yang lebih akurat (berdasarkan hari yang terekam)
$persentase = $total_recorded_days > 0 ? round(($hadir / $total_recorded_days) * 100, 1) : 0;

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";

// Logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header("Location: login_siswa.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Siswa</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <style>
        /* Animasi untuk modal */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        /* Style untuk QR Scanner */
        .scanner-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            padding: 20px;
            color: white;
        }
        #qr-scanner {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            border-radius: 8px;
            overflow: hidden;
        }
    </style>
</head>
<body class="bg-gray-50">
    <header class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center">
                    <i class="fas fa-user-graduate text-2xl text-indigo-600 mr-3"></i>
                    <h1 class="text-2xl font-bold text-gray-900">Dashboard Siswa</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-gray-700">Halo, <?= htmlspecialchars($siswa['nama']) ?></span>
                    <a href="?action=logout" class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition">
                        <i class="fas fa-sign-out-alt mr-2"></i>Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div class="px-4 py-6 sm:px-0">
            <div class="bg-white overflow-hidden shadow rounded-lg mb-6">
                <div class="px-4 py-5 sm:px-6 bg-indigo-600">
                    <h3 class="text-lg leading-6 font-medium text-white">Profil Siswa</h3>
                </div>
                <div class="border-t border-gray-200">
                    <dl>
                        <div class="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                            <dt class="text-sm font-medium text-gray-500">Nama Lengkap</dt>
                            <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2"><?= htmlspecialchars($siswa['nama']) ?></dd>
                        </div>
                        <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                            <dt class="text-sm font-medium text-gray-500">NISN</dt>
                            <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2"><?= htmlspecialchars($siswa['nisn'] ?? 'Belum diisi') ?></dd>
                        </div>
                        <div class="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                            <dt class="text-sm font-medium text-gray-500">Kelas</dt>
                            <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2"><?= htmlspecialchars($siswa['nama_kelas']) ?></dd>
                        </div>
                        <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                            <dt class="text-sm font-medium text-gray-500">Jenis Kelamin</dt>
                            <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                <?= $siswa['jenis_kelamin'] == 'L' ? 'Laki-laki' : ($siswa['jenis_kelamin'] == 'P' ? 'Perempuan' : 'Belum diisi') ?>
                            </dd>
                        </div>
                    </dl>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <div class="bg-white shadow rounded-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Statistik Kehadiran <?= date('F Y') ?></h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                        <div class="bg-green-100 p-4 rounded-lg text-center">
                            <p class="text-green-800 font-bold text-2xl"><?= $hadir ?></p>
                            <p class="text-green-600 font-medium">Hadir</p>
                        </div>
                        <div class="bg-yellow-100 p-4 rounded-lg text-center">
                            <p class="text-yellow-800 font-bold text-2xl"><?= $izin ?></p>
                            <p class="text-yellow-600 font-medium">Izin</p>
                        </div>
                        <div class="bg-blue-100 p-4 rounded-lg text-center">
                            <p class="text-blue-800 font-bold text-2xl"><?= $sakit ?></p>
                            <p class="text-blue-600 font-medium">Sakit</p>
                        </div>
                        <div class="bg-red-100 p-4 rounded-lg text-center">
                            <p class="text-red-800 font-bold text-2xl"><?= $alpha ?></p>
                            <p class="text-red-600 font-medium">Alpha</p>
                        </div>
                    </div>
                    <div class="bg-indigo-50 p-4 rounded-lg">
                        <p class="text-indigo-800 text-center">
                            <span class="font-bold">Persentase Kehadiran: <?= $persentase ?>%</span><br>
                            <span class="text-sm">(<?= $hadir ?> dari <?= $total_recorded_days ?> hari terekam)</span>
                            <span class="text-xs text-gray-500 block mt-1">(Total hari kalender bulan ini: <?= $total_hari ?>)</span>
                        </p>
                    </div>
                </div>

                <!-- ================================================ -->
                <!-- BAGIAN BARU: SCAN QR KANTOR -->
                <!-- ================================================ -->
                <div class="scanner-container text-center fade-in">
                    <h3 class="text-xl font-bold mb-4">📱 Scan QR Kantor</h3>
                    <p class="text-sm opacity-90 mb-4">Gunakan kamera untuk scan QR Code di lokasi kantor</p>
                    
                    <div id="qr-scanner" class="mb-4"></div>
                    
                    <div class="flex flex-col space-y-3">
                        <button id="start-scanner" class="bg-green-600 text-white px-6 py-3 rounded-lg font-bold hover:bg-green-700 transition">
                            <i class="fas fa-camera mr-2"></i> Buka Kamera
                        </button>
                        
                        <button id="stop-scanner" class="bg-red-600 text-white px-6 py-3 rounded-lg font-bold hover:bg-red-700 transition hidden">
                            <i class="fas fa-stop mr-2"></i> Stop Kamera
                        </button>
                        
                        <div id="scanner-status" class="text-sm"></div>
                    </div>
                    
                    <div id="scan-result" class="mt-4 hidden">
                        <div class="bg-white text-gray-800 p-4 rounded-lg">
                            <h4 class="font-bold mb-2">Hasil Scan:</h4>
                            <p id="result-message" class="text-sm"></p>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6 mb-6">
                    <h3 class="text-xl font-semibold text-gray-800 mb-4">Kartu Pelajar</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-center">
                        <div class="border-2 border-blue-200 rounded-lg p-4">
                            <div class="text-4xl mb-2">🆔</div>
                            <h4 class="font-bold text-blue-600 mb-2">Kartu KTP</h4>
                            <p class="text-sm text-gray-600 mb-3">Ukuran compact seperti KTP, mudah dibawa</p>
                            <a href="kartu_pelajar.php" 
                            class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition text-sm inline-block">
                                📄 Lihat KTP
                            </a>
                            <br>
                            <a href="kartu_pelajar.php?print=true" 
                            class="text-blue-600 hover:underline text-xs mt-1 inline-block">
                                🖨️ Langsung Cetak
                            </a>
                        </div>
                        
                        <div class="border-2 border-purple-200 rounded-lg p-4">
                            <div class="text-4xl mb-2">📄</div>
                            <h4 class="font-bold text-purple-600 mb-2">Kartu Besar</h4>
                            <p class="text-sm text-gray-600 mb-3">Ukuran A4, lebih banyak informasi</p>
                            <a href="kartu_pelajar_besar.php" 
                            class="bg-purple-500 text-white px-4 py-2 rounded hover:bg-purple-600 transition text-sm inline-block">
                                📄 Lihat Besar
                            </a>
                        </div>
                    </div>
                </div>

                <div class="bg-white shadow rounded-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">QR Code Absensi</h3>
                    <?php if (!empty($siswa['nisn'])): ?>
                        <div class="text-center">
                            <?php
                            $qr_lib_path = 'phpqrcode/qrlib.php';
                            $qr_lib_available = file_exists($qr_lib_path);
                            $filename = 'temp_qr/siswa_' . $siswa_id . '.png';
                            $qr_success = false;
                            
                            if ($qr_lib_available) {
                                require_once $qr_lib_path;
                                
                                // Coba buat folder temp. Gunakan @ untuk meredam error izin
                                if (!file_exists('temp_qr')) {
                                    @mkdir('temp_qr', 0777, true); 
                                }
                                
                                $qr_data = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/qr_process.php?nisn=" . $siswa['nisn'];
                                
                                if (class_exists('QRcode')) {
                                    // Coba buat file QR Code. Gunakan @ untuk meredam error pembuatan file
                                    @QRcode::png($qr_data, $filename, QR_ECLEVEL_L, 8);
                                    if (file_exists($filename) && filesize($filename) > 0) {
                                        $qr_success = true;
                                    }
                                }
                            }

                            if ($qr_success): 
                            ?>
                                <img src="<?= $filename ?>" alt="QR Code Absensi" class="mx-auto border rounded-lg shadow-md mb-4 max-w-xs">
                                
                                <p class="text-sm text-gray-600 mb-4">
                                    Scan QR code ini untuk absensi harian<br>
                                    <span class="font-mono text-xs">NISN: <?= htmlspecialchars($siswa['nisn']) ?></span>
                                </p>
                                
                                <div class="flex flex-col space-y-3">
                                    <a href="<?= $filename ?>" download="QR_Absensi_<?= htmlspecialchars($siswa['nama']) ?>.png" 
                                        class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition inline-flex items-center justify-center">
                                        <i class="fas fa-download mr-2"></i> Download QR Code
                                    </a>
                                </div>
                                
                            <?php else: ?>
                                <div class="bg-red-50 p-8 rounded-lg">
                                    <i class="fas fa-exclamation-circle text-red-500 text-4xl mb-4"></i>
                                    <p class="text-red-700 font-semibold">Gagal membuat/menampilkan QR Code</p>
                                    <p class="text-red-600 text-sm mt-2">
                                        **Langkah Perbaikan:** 1) File **`phpqrcode/qrlib.php`** tidak ditemukan atau 2) Direktori **`temp_qr`** tidak memiliki izin tulis (0777).
                                    </p>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center p-8 bg-yellow-50 rounded-lg">
                            <i class="fas fa-exclamation-triangle text-yellow-500 text-4xl mb-4"></i>
                            <p class="text-yellow-700 font-semibold">NISN belum terisi</p>
                            <p class="text-yellow-600 text-sm mt-2">Hubungi administrator untuk mengisi NISN agar bisa generate QR Code</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:px-6 bg-indigo-600 rounded-t-lg">
                    <h3 class="text-lg leading-6 font-medium text-white">Riwayat Kehadiran <?= date('F Y') ?></h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Hari</th>
                                <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if (!empty($kehadiran)): ?>
                                <?php foreach ($kehadiran as $k): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?= date('d/m/Y', strtotime($k['tanggal'])) ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?= translate_day_name(date('l', strtotime($k['tanggal']))) ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-center">
                                            <?php
                                            $status_class = [
                                                'H' => 'bg-green-100 text-green-800',
                                                'I' => 'bg-yellow-100 text-yellow-800', 
                                                'S' => 'bg-blue-100 text-blue-800',
                                                'A' => 'bg-red-100 text-red-800'
                                            ];
                                            $status_text = [
                                                'H' => 'Hadir', 'I' => 'Izin', 'S' => 'Sakit', 'A' => 'Alpha'
                                            ];
                                            ?>
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium <?= $status_class[$k['status']] ?? 'bg-gray-100 text-gray-800' ?>">
                                                <?= $status_text[$k['status']] ?? $k['status'] ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="px-6 py-4 text-center text-sm text-gray-500">
                                        Belum ada data kehadiran untuk bulan ini.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal untuk hasil scan -->
    <div id="scan-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm transform transition-all duration-300">
            <div class="p-6 text-center">
                <div id="modal-icon" class="text-6xl mb-4"></div>
                <h3 id="modal-title" class="text-xl font-bold mb-2"></h3>
                <p id="modal-message" class="text-gray-700 mb-4"></p>
                <button onclick="closeModal()" class="bg-indigo-600 text-white px-6 py-2 rounded-lg font-semibold hover:bg-indigo-700 transition">
                    Tutup
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let html5QrcodeScanner = null;
            const startButton = document.getElementById('start-scanner');
            const stopButton = document.getElementById('stop-scanner');
            const scannerStatus = document.getElementById('scanner-status');
            const scanResult = document.getElementById('scan-result');
            const resultMessage = document.getElementById('result-message');
            const scannerContainer = document.getElementById('qr-scanner');

            // Modal elements
            const modal = document.getElementById('scan-modal');
            const modalIcon = document.getElementById('modal-icon');
            const modalTitle = document.getElementById('modal-title');
            const modalMessage = document.getElementById('modal-message');

            // Fungsi untuk menampilkan modal
            function showModal(icon, title, message) {
                modalIcon.className = `text-6xl mb-4 ${icon}`;
                modalTitle.textContent = title;
                modalMessage.textContent = message;
                modal.classList.remove('hidden');
            }

            // Fungsi untuk menutup modal
            window.closeModal = function() {
                modal.classList.add('hidden');
            }

            // Fungsi untuk memulai scanner
            startButton.addEventListener('click', function() {
                startScanner();
            });

            // Fungsi untuk menghentikan scanner
            stopButton.addEventListener('click', function() {
                stopScanner();
            });

            async function startScanner() {
                try {
                    scannerStatus.textContent = 'Menginisialisasi kamera...';
                    scannerStatus.className = 'text-yellow-500';

                    // Buat instance scanner
                    html5QrcodeScanner = new Html5Qrcode("qr-scanner");

                    // Konfigurasi kamera
                    const config = {
                        fps: 10,
                        qrbox: { width: 250, height: 250 },
                        aspectRatio: 1.0
                    };

                    // Dapatkan kamera belakang (jika ada)
                    const cameras = await Html5Qrcode.getCameras();
                    let cameraId = null;
                    
                    if (cameras && cameras.length > 0) {
                        // Cari kamera belakang
                        const rearCamera = cameras.find(camera => 
                            camera.label.toLowerCase().includes('back') || 
                            camera.label.toLowerCase().includes('rear')
                        );
                        cameraId = rearCamera ? rearCamera.id : cameras[0].id;
                    }

                    // Mulai scanning
                    await html5QrcodeScanner.start(
                        cameraId,
                        config,
                        onScanSuccess,
                        onScanFailure
                    );

                    // Update UI
                    startButton.classList.add('hidden');
                    stopButton.classList.remove('hidden');
                    scannerStatus.textContent = 'Kamera aktif - Arahkan ke QR Code';
                    scannerStatus.className = 'text-green-500';
                    scanResult.classList.add('hidden');

                } catch (error) {
                    console.error('Error starting scanner:', error);
                    scannerStatus.textContent = 'Gagal mengakses kamera: ' + error.message;
                    scannerStatus.className = 'text-red-500';
                    
                    if (error.message.includes('Permission')) {
                        showModal('fas fa-exclamation-triangle text-red-500', 
                                 'Izin Kamera Ditolak', 
                                 'Silakan berikan izin akses kamera di browser Anda untuk menggunakan fitur scan QR.');
                    } else {
                        showModal('fas fa-exclamation-triangle text-red-500', 
                                 'Error Kamera', 
                                 'Tidak dapat mengakses kamera: ' + error.message);
                    }
                }
            }

            function stopScanner() {
                if (html5QrcodeScanner) {
                    html5QrcodeScanner.stop().then(() => {
                        console.log('Scanner stopped');
                    }).catch((error) => {
                        console.error('Error stopping scanner:', error);
                    });
                }

                // Update UI
                startButton.classList.remove('hidden');
                stopButton.classList.add('hidden');
                scannerStatus.textContent = 'Kamera dihentikan';
                scannerStatus.className = 'text-gray-500';
                scannerContainer.innerHTML = ''; // Clear scanner view
            }

            function onScanSuccess(decodedText, decodedResult) {
                console.log('QR Code scanned:', decodedText);
                
                // Tampilkan hasil scan
                resultMessage.textContent = `QR Code terdeteksi: ${decodedText}`;
                scanResult.classList.remove('hidden');
                
                // Proses QR Code yang di-scan
                processScannedQR(decodedText);
                
                // Otomatis stop scanner setelah berhasil scan
                setTimeout(() => {
                    stopScanner();
                }, 2000);
            }

            function onScanFailure(error) {
                // Error handling bisa diisi jika diperlukan
                // Biarkan kosong agar tidak mengganggu UX
            }

            async function processScannedQR(qrData) {
    try {
        scannerStatus.textContent = 'Memproses QR Code...';
        scannerStatus.className = 'text-blue-500';

        // Cek jika QR Code adalah URL token dari sistem kita
        if (qrData.includes('qr_token=')) {
            const url = new URL(qrData);
            const qrToken = url.searchParams.get('qr_token');
            
            if (qrToken) {
                // Redirect ke proses absensi khusus untuk siswa
                window.location.href = `proses_qr_dinamis.php?qr_token=${qrToken}`;
                return;
            }
        }

        // Jika QR code tidak dikenali
        showModal('fas fa-question-circle text-yellow-500', 
                 'QR Code Tidak Dikenali', 
                 'QR Code ini bukan untuk sistem absensi. Pastikan Anda scan QR Code yang benar.');

    } catch (error) {
        console.error('Error processing QR:', error);
        showModal('fas fa-times-circle text-red-500', 
                 'Error', 
                 'Terjadi kesalahan saat memproses QR Code: ' + error.message);
    }
}

            // Cleanup saat halaman ditutup
            window.addEventListener('beforeunload', function() {
                if (html5QrcodeScanner) {
                    stopScanner();
                }
            });
        });
    </script>
</body>
</html>