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

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    die('Akses ditolak.');
}

require_once '../vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;

// === LIBRARY QR CODE OFFLINE ===
require_once '../vendor/phpqrcode/qrlib.php'; // pastikan sudah ada!

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'DejaVu Sans');
$options->set('dpi', 96);
$options->set('isPhpEnabled', true); // Penting untuk base64 images

$dompdf = new Dompdf($options);

$type = $_GET['type'] ?? '';
$kelas = $_GET['kelas'] ?? '';

// Handle different types
if ($type === 'single') {
    // Cetak per siswa
    $nis = $_GET['nis'] ?? '';
    $nama = $_GET['nama'] ?? '';
    $kelas_siswa = $_GET['kelas'] ?? '';
    
    if (empty($nis) || empty($nama) || empty($kelas_siswa)) {
        die('Data siswa tidak lengkap.');
    }
    
    $siswaData = [[
        'nis' => $nis,
        'nama' => $nama,
        'kelas' => $kelas_siswa
    ]];
    
    $judul = "QR Code - $nama";
    
} elseif ($type === 'kelas') {
    // Cetak per kelas
    $siswaData = json_decode($_GET['data'] ?? '[]', true);
    if (empty($siswaData)) die('Data kelas kosong');
    
    $judul = "QR Code Kelas $kelas";
    
} elseif ($type === 'all') {
    // Cetak semua siswa
    $siswaData = json_decode($_GET['data'] ?? '[]', true);
    if (empty($siswaData)) die('Data kosong');
    
    $judul = "QR Code Semua Siswa";
    
} else {
    die('Tipe cetak tidak valid.');
}

// Buat direktori temporary untuk QR code jika belum ada
$tempDir = __DIR__ . '/../temp_qr/';
if (!is_dir($tempDir)) {
    mkdir($tempDir, 0755, true);
}

// Bersihkan file temporary yang lama (lebih dari 1 jam)
$files = glob($tempDir . '*.png');
foreach ($files as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}

$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>' . $judul . '</title>
<style>
    body { 
        font-family: "DejaVu Sans", Arial, sans-serif; 
        margin: 2mm; 
    }
    .header { 
        text-align: center; 
        margin-bottom: 1px;
        margin-bottom: 1px; 
    }
    table { 
        width: 100%; 
        border-collapse: separate; 
        border-spacing: 9px 12px; 
        table-layout: fixed; 
    }
    td { 
        width: 25%; 
        padding: 0; 
        vertical-align: top; 
        page-break-inside: avoid; 
    }
    .item {
        border: 2.6px solid #000; 
        border-radius: 12px;
        height: 205px; 
        text-align: center; 
        background: #fff; 
        overflow: hidden;
        box-sizing: border-box; 
        padding: 12px 8px 8px 8px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
    .qr-img { 
        width: 120px; 
        height: 120px; 
        margin: 0 auto 8px; 
        display: block; 
        flex-shrink: 0;
    }
    .nama-container {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 35px;
        max-height: 45px;
        overflow: hidden;
        padding: 0 5px;
        margin-bottom: 5px;
    }
    .nama { 
        font-weight: bold; 
        line-height: 1.2; 
        word-wrap: break-word;
        text-align: center;
        width: 100%;
        margin: 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .footer-info { 
        font-size: 11px; 
        line-height: 1.3; 
        padding: 0 5px;
        flex-shrink: 0;
    }
    .page-footer { 
        text-align: center; 
        margin-top: 20px; 
        font-size: 10px; 
        color: #555; 
    }
    @page { 
        margin: 10mm; 
        margin-top: 2mm; 
    }
    @media print { 
        .item { 
            border: 2.6px solid #000; 
        } 
    }
</style>
</head>
<body>
<div class="header">
    <h2>' . $judul . '</h2>
    <p>Total: ' . count($siswaData) . ' siswa • Dicetak: ' . date('d/m/Y H:i') . '</p>
</div>
<table><tbody>';

$i = 0;
foreach ($siswaData as $s) {
    if ($i % 4 == 0) {
        $html .= ($i > 0 ? '</tr>' : '') . '<tr>';
    }

    $qrData = $s['nis'] . ':' . $s['nama'] . ':' . $s['kelas'];
    
    // Generate QR code dan simpan ke file temporary
    $filename = $tempDir . 'qr_' . md5($qrData . time() . $i) . '.png';
    QRcode::png($qrData, $filename, QR_ECLEVEL_H, 5, 0);
    
    // Konversi ke base64
    $qrImageData = file_get_contents($filename);
    $qrBase64 = 'data:image/png;base64,' . base64_encode($qrImageData);

    // Hitung font-size untuk nama berdasarkan panjang karakter
    $len = strlen($s['nama']);
    if ($len > 30)      $fs = '9.5px';
    elseif ($len > 25)  $fs = '10px';
    elseif ($len > 20)  $fs = '11px';
    elseif ($len > 15)  $fs = '12px';
    else                $fs = '13px';

    $html .= '
    <td>
        <div class="item">
            <img src="' . $qrBase64 . '" class="qr-img" alt="QR Code">
            <div class="nama-container">
                <div class="nama" style="font-size: ' . $fs . ';">
                    ' . htmlspecialchars($s['nama']) . '
                </div>
            </div>
            <div class="footer-info">
                <div>NIS: ' . htmlspecialchars($s['nis']) . '</div>
                <div>Kelas: ' . htmlspecialchars($s['kelas']) . '</div>
            </div>
        </div>
    </td>';

    $i++;
}

// Tambah sel kosong untuk melengkapi baris terakhir
while ($i % 4 != 0) { 
    $html .= '<td></td>'; 
    $i++; 
}

$html .= '</tr></tbody></table>
<div class="page-footer">Sistem Kehadiran Ujian © ' . date('Y') . '</div>
</body></html>';

$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Hapus file temporary setelah render
$files = glob($tempDir . '*.png');
foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    }
}

// Tentukan nama file berdasarkan tipe
$filename = '';
if ($type === 'single') {
    $filename = 'QR_' . $siswaData[0]['nama'] . '_' . date('Ymd_Hi') . '.pdf';
} elseif ($type === 'kelas') {
    $filename = 'QR_Kelas_' . $kelas . '_' . date('Ymd_Hi') . '.pdf';
} else {
    $filename = 'QR_Semua_Siswa_' . date('Ymd_Hi') . '.pdf';
}

$dompdf->stream($filename, ['Attachment' => false]);
?>