<?php
// FILE: cetak_barcode.php - Cetak Barcode/QR Code dengan NISN
session_start();
require_once 'db.php';

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

// Ambil daftar kelas
$kelas_list = $pdo->query("SELECT * FROM kelas ORDER BY nama_kelas ASC")->fetchAll(PDO::FETCH_ASSOC);

// Tentukan kelas aktif
$current_class_id = $_GET['class_id'] ?? ($kelas_list[0]['id'] ?? null);

// Ambil data siswa berdasarkan kelas
$siswa_list = [];
if ($current_class_id) {
    $stmt = $pdo->prepare("SELECT * FROM siswa WHERE kelas_id = ? ORDER BY nama ASC");
    $stmt->execute([$current_class_id]);
    $siswa_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Include library QR Code
require_once 'phpqrcode/qrlib.php';

// Buat folder temp jika belum ada
if (!file_exists('temp_qr')) {
    mkdir('temp_qr', 0777, true);
}

// Proses generate QR Code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_qr'])) {
    $siswa_id = $_POST['siswa_id'];
    
    // Ambil data siswa
    $stmt = $pdo->prepare("SELECT * FROM siswa WHERE siswa_id = ?");
    $stmt->execute([$siswa_id]);
    $siswa = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($siswa) {
        // Gunakan NISN sebagai identifier QR Code
        $nisn = $siswa['nisn'];
        
        if (empty($nisn)) {
            $error = "Siswa ini tidak memiliki NISN. Silakan tambahkan NISN terlebih dahulu.";
        } else {
            // URL untuk scan QR code - menggunakan parameter nisn
            $qr_data = "https://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/qr_process.php?nisn=" . $nisn;
            
            // Nama file QR code
            $filename = 'temp_qr/' . $siswa['nama'] . '_' . $nisn . '.png';
            
            // Generate QR Code
            QRcode::png($qr_data, $filename, QR_ECLEVEL_L, 8);
            
            $success = "QR Code berhasil digenerate untuk " . $siswa['nama'] . " (NISN: $nisn)";
            $qr_image = $filename;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cetak Barcode/QR Code</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">
</head>
<body class="bg-gray-50">
    <div class="container mx-auto p-6">
        <h1 class="text-3xl font-bold text-gray-800 mb-6">Cetak Barcode/QR Code</h1>
        
        <!-- Pilih Kelas -->
        <div class="bg-white p-6 rounded-lg shadow mb-6">
            <h2 class="text-xl font-semibold mb-4">Pilih Kelas</h2>
            <form method="GET" class="flex gap-4">
                <select name="class_id" onchange="this.form.submit()" class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                    <?php foreach ($kelas_list as $k): ?>
                        <option value="<?= $k['id'] ?>" <?= $k['id'] == $current_class_id ? 'selected' : '' ?>>
                            <?= htmlspecialchars($k['nama_kelas']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>

        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <?php if (isset($success)): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
                <?= htmlspecialchars($success) ?>
            </div>
        <?php endif; ?>

        <!-- Daftar Siswa -->
        <div class="bg-white p-6 rounded-lg shadow">
            <h2 class="text-xl font-semibold mb-4">Daftar Siswa - <?= $kelas_list[array_search($current_class_id, array_column($kelas_list, 'id'))]['nama_kelas'] ?? '' ?></h2>
            
            <?php if (empty($siswa_list)): ?>
                <p class="text-gray-500">Tidak ada siswa di kelas ini.</p>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <?php foreach ($siswa_list as $siswa): ?>
                        <div class="border rounded-lg p-4 bg-white shadow-sm">
                            <div class="text-center">
                                <h3 class="font-semibold text-lg"><?= htmlspecialchars($siswa['nama']) ?></h3>
                                <p class="text-sm text-gray-600">
                                    ID: #<?= $siswa['siswa_id'] ?> 
                                    <?php if ($siswa['nisn']): ?>
                                        | NISN: <?= htmlspecialchars($siswa['nisn']) ?>
                                    <?php else: ?>
                                        | <span class="text-red-500">Belum ada NISN</span>
                                    <?php endif; ?>
                                </p>
                                
                                <?php if ($siswa['nisn']): ?>
                                    <form method="POST" class="mt-3">
                                        <input type="hidden" name="siswa_id" value="<?= $siswa['siswa_id'] ?>">
                                        <button type="submit" name="generate_qr" 
                                                class="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition">
                                            <i class="fas fa-qrcode mr-2"></i>Generate QR Code
                                        </button>
                                    </form>
                                    
                                    <!-- Tampilkan QR Code jika baru digenerate -->
                                    <?php if (isset($qr_image) && $_POST['siswa_id'] == $siswa['siswa_id']): ?>
                                        <div class="mt-4 text-center">
                                            <img src="<?= $qr_image ?>" alt="QR Code" class="mx-auto border rounded">
                                            <p class="text-xs text-gray-500 mt-2">Scan QR code untuk absensi</p>
                                            <p class="text-xs text-gray-400">NISN: <?= htmlspecialchars($siswa['nisn']) ?></p>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <p class="text-red-500 text-sm mt-2">Tambah NISN terlebih dahulu untuk generate QR Code</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>