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

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    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>Generate QR Code - Admin Dashboard</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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <style>
        .navbar-brand {
            font-weight: bold;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        .user-info {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .qr-card {
            text-align: center;
            padding: 20px;
        }
        .qr-grid .card {
            margin-bottom: 15px;
        }
        .btn-print {
            margin-top: 15px;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-tachometer-alt me-2"></i>Admin Dashboard
            </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="dashboard.php">
                            <i class="fas fa-home me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="mata_pelajaran.php">
                            <i class="fas fa-book me-1"></i>Mata Pelajaran
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="kelola_siswa.php">
                            <i class="fas fa-users me-1"></i>Kelola Siswa
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="generate_qr.php">
                            <i class="fas fa-qrcode me-1"></i>Generate QR
                        </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>

    <div class="container mt-4">
        <!-- Info Pengguna -->
        <div class="user-info no-print">
            <h5><i class="fas fa-user-shield me-2"></i>Selamat Datang, <?= htmlspecialchars($current_user['nama_lengkap']); ?></h5>
            <p class="mb-0">Anda login sebagai <strong>Administrator</strong> - Halaman Generate QR Code</p>
        </div>

        <h2 class="mb-4"><i class="fas fa-qrcode me-2"></i>Generate QR Code Siswa</h2>
        
        <div class="row">
            <div class="col-md-4 no-print">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-cog me-2"></i>Pilihan Generate</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Pilih Siswa</label>
                            <select class="form-select" id="siswa-select">
                                <option value="">-- Pilih Siswa --</option>
                                <?php
                                $sql = "SELECT * FROM ujn_siswa ORDER BY nama";
                                $result = $conn->query($sql);
                                if ($result && $result->num_rows > 0) {
                                    while($row = $result->fetch_assoc()) {
                                        echo "<option value='{$row['nis']}:{$row['nama']}:{$row['kelas']}'>{$row['nama']} - {$row['kelas']}</option>";
                                    }
                                } else {
                                    echo "<option value=''>Tidak ada data siswa</option>";
                                }
                                ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Pilih Kelas</label>
                            <select class="form-select" id="kelas-select">
                                <option value="">-- Pilih Kelas --</option>
                                <?php
                                $sql_kelas = "SELECT DISTINCT kelas FROM ujn_siswa ORDER BY kelas";
                                $result_kelas = $conn->query($sql_kelas);
                                if ($result_kelas && $result_kelas->num_rows > 0) {
                                    while($row_kelas = $result_kelas->fetch_assoc()) {
                                        echo "<option value='{$row_kelas['kelas']}'>{$row_kelas['kelas']}</option>";
                                    }
                                } else {
                                    echo "<option value=''>Tidak ada data kelas</option>";
                                }
                                ?>
                            </select>
                        </div>
                        
                        <button id="generate-single" class="btn btn-primary w-100 mb-2">
                            <i class="fas fa-user me-2"></i>Generate Per Siswa
                        </button>
                        <button id="generate-kelas" class="btn btn-info w-100 mb-2">
                            <i class="fas fa-users me-2"></i>Generate Per Kelas
                        </button>
                        <button id="generate-all" class="btn btn-success w-100">
                            <i class="fas fa-users me-2"></i>Generate Semua Siswa
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="card no-print">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-qrcode me-2"></i>QR Code</h5>
                    </div>
                    <div class="card-body text-center" id="qr-container">
                        <p class="text-muted">Pilih siswa untuk menampilkan QR Code</p>
                    </div>
                </div>
                
                <div id="all-qr-codes" class="mt-4" style="display: none;">
                    <!-- QR Code semua siswa akan ditampilkan di sini -->
                </div>
                
                <div id="kelas-qr-codes" class="mt-4" style="display: none;">
                    <!-- QR Code per kelas akan ditampilkan di sini -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentSiswaData = null;
        let allSiswaData = [];
        let kelasSiswaData = [];

        // Generate QR Code per siswa
        document.getElementById('generate-single').addEventListener('click', function() {
            const siswaData = document.getElementById('siswa-select').value;
            if (!siswaData) {
                alert('Pilih siswa terlebih dahulu!');
                return;
            }
            
            currentSiswaData = siswaData;
            const qrContainer = document.getElementById('qr-container');
            qrContainer.innerHTML = '';
            
            // Buat QR Code
            new QRCode(qrContainer, {
                text: siswaData,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
            
            // Tampilkan info siswa
            const dataParts = siswaData.split(':');
            const infoDiv = document.createElement('div');
            infoDiv.className = 'mt-3';
            infoDiv.innerHTML = `
                <p><strong>NIS:</strong> ${dataParts[0]}</p>
                <p><strong>Nama:</strong> ${dataParts[1]}</p>
                <p><strong>Kelas:</strong> ${dataParts[2]}</p>
                <button class="btn btn-sm btn-outline-primary mt-2" onclick="printSingleQR()">
                    <i class="fas fa-print me-1"></i>Cetak QR Code (PDF)
                </button>
            `;
            qrContainer.appendChild(infoDiv);
            
            // Sembunyikan QR Code lainnya
            document.getElementById('all-qr-codes').style.display = 'none';
            document.getElementById('kelas-qr-codes').style.display = 'none';
        });
        
        // Generate QR Code per kelas
        document.getElementById('generate-kelas').addEventListener('click', function() {
            const kelas = document.getElementById('kelas-select').value;
            if (!kelas) {
                alert('Pilih kelas terlebih dahulu!');
                return;
            }
            
            const kelasQrContainer = document.getElementById('kelas-qr-codes');
            kelasQrContainer.innerHTML = `<h4 class="mb-3">QR Code Kelas ${kelas}</h4><div class="row qr-grid" id="kelas-qr-grid"></div>`;
            
            const siswaOptions = document.getElementById('siswa-select').options;
            const kelasQrGrid = document.getElementById('kelas-qr-grid');
            
            kelasSiswaData = [];
            let siswaDitemukan = false;
            
            // Loop melalui semua siswa dan filter berdasarkan kelas
            for (let i = 1; i < siswaOptions.length; i++) {
                const siswaData = siswaOptions[i].value;
                const dataParts = siswaData.split(':');
                
                // Cek apakah siswa termasuk dalam kelas yang dipilih
                if (dataParts[2] === kelas) {
                    siswaDitemukan = true;
                    
                    kelasSiswaData.push({
                        nis: dataParts[0],
                        nama: dataParts[1],
                        kelas: dataParts[2],
                        data: siswaData
                    });
                    
                    const colDiv = document.createElement('div');
                    colDiv.className = 'col-md-3 mb-4 text-center';
                    
                    const qrDiv = document.createElement('div');
                    qrDiv.id = `qr-kelas-${dataParts[0]}`;
                    
                    colDiv.innerHTML = `
                        <div class="card">
                            <div class="card-body">
                                <div id="qr-kelas-${dataParts[0]}"></div>
                                <p class="mt-2 mb-1"><small><strong>${dataParts[1]}</strong></small></p>
                                <p class="mb-1"><small>${dataParts[0]}</small></p>
                                <p class="mb-0"><small>${dataParts[2]}</small></p>
                            </div>
                        </div>
                    `;
                    
                    kelasQrGrid.appendChild(colDiv);
                    
                    // Generate QR Code untuk setiap siswa dalam kelas
                    new QRCode(`qr-kelas-${dataParts[0]}`, {
                        text: siswaData,
                        width: 120,
                        height: 120,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                }
            }
            
            if (!siswaDitemukan) {
                kelasQrContainer.innerHTML = '<div class="alert alert-warning">Tidak ada siswa dalam kelas ini.</div>';
            } else {
                kelasQrContainer.style.display = 'block';
                
                // Tambahkan tombol cetak
                const printBtn = document.createElement('button');
                printBtn.className = 'btn btn-info mt-3 btn-print no-print';
                printBtn.innerHTML = '<i class="fas fa-print me-2"></i>Cetak QR Code Kelas (PDF)';
                printBtn.onclick = function() { printKelasQR(kelas); };
                kelasQrContainer.appendChild(printBtn);
            }
            
            // Sembunyikan QR Code lainnya
            document.getElementById('all-qr-codes').style.display = 'none';
        });
        
        // Generate QR Code semua siswa
        document.getElementById('generate-all').addEventListener('click', function() {
            const allQrContainer = document.getElementById('all-qr-codes');
            allQrContainer.innerHTML = '<h4 class="mb-3">QR Code Semua Siswa</h4><div class="row qr-grid" id="qr-grid"></div>';
            
            const siswaOptions = document.getElementById('siswa-select').options;
            const qrGrid = document.getElementById('qr-grid');
            
            allSiswaData = [];
            
            // Mulai dari index 1 untuk melewati option pertama ("-- Pilih Siswa --")
            for (let i = 1; i < siswaOptions.length; i++) {
                const siswaData = siswaOptions[i].value;
                const dataParts = siswaData.split(':');
                
                allSiswaData.push({
                    nis: dataParts[0],
                    nama: dataParts[1],
                    kelas: dataParts[2],
                    data: siswaData
                });
                
                const colDiv = document.createElement('div');
                colDiv.className = 'col-md-3 mb-4 text-center';
                
                const qrDiv = document.createElement('div');
                qrDiv.id = `qr-${dataParts[0]}`;
                
                colDiv.innerHTML = `
                    <div class="card">
                        <div class="card-body">
                            <div id="qr-${dataParts[0]}"></div>
                            <p class="mt-2 mb-1"><small><strong>${dataParts[1]}</strong></small></p>
                            <p class="mb-1"><small>${dataParts[0]}</small></p>
                            <p class="mb-0"><small>${dataParts[2]}</small></p>
                        </div>
                    </div>
                `;
                
                qrGrid.appendChild(colDiv);
                
                // Generate QR Code untuk setiap siswa
                new QRCode(`qr-${dataParts[0]}`, {
                    text: siswaData,
                    width: 120,
                    height: 120,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
            }
            
            allQrContainer.style.display = 'block';
            
            // Tambahkan tombol cetak
            const printBtn = document.createElement('button');
            printBtn.className = 'btn btn-primary mt-3 btn-print no-print';
            printBtn.innerHTML = '<i class="fas fa-print me-2"></i>Cetak Semua QR Code (PDF)';
            printBtn.onclick = function() { printAllQR(); };
            allQrContainer.appendChild(printBtn);
            
            // Sembunyikan QR Code lainnya
            document.getElementById('kelas-qr-codes').style.display = 'none';
        });
        
        function printSingleQR() {
            if (!currentSiswaData) {
                alert('Tidak ada QR Code yang dipilih!');
                return;
            }
            
            const dataParts = currentSiswaData.split(':');
            const url = `cetak_qr_pdf.php?type=single&nis=${encodeURIComponent(dataParts[0])}&nama=${encodeURIComponent(dataParts[1])}&kelas=${encodeURIComponent(dataParts[2])}`;
            window.open(url, '_blank');
        }
        
        function printKelasQR(kelas) {
            if (kelasSiswaData.length === 0) {
                alert('Tidak ada data siswa untuk kelas ini!');
                return;
            }
            
            // Kirim data siswa kelas ke PDF generator
            const siswaDataJSON = JSON.stringify(kelasSiswaData);
            const url = `cetak_qr_pdf.php?type=kelas&kelas=${encodeURIComponent(kelas)}&data=${encodeURIComponent(siswaDataJSON)}`;
            window.open(url, '_blank');
        }
        
        function printAllQR() {
            if (allSiswaData.length === 0) {
                alert('Tidak ada data siswa!');
                return;
            }
            
            // Kirim data semua siswa ke PDF generator
            const siswaDataJSON = JSON.stringify(allSiswaData);
            const url = `cetak_qr_pdf.php?type=all&data=${encodeURIComponent(siswaDataJSON)}`;
            window.open(url, '_blank');
        }
    </script>
</body>
</html>
<?php $conn->close(); ?>