<?php
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
cekAdminAtauGuru();

$id_rombel = mysqli_real_escape_string($koneksi, $_GET['id_rombel'] ?? '');
$bulan     = mysqli_real_escape_string($koneksi, $_GET['bulan'] ?? date('m'));
$tahun     = mysqli_real_escape_string($koneksi, $_GET['tahun'] ?? date('Y'));
$mode      = $_GET['mode'] ?? ''; // 'blank' untuk blanko kosong

// 1. Ambil info kelas
$q_rombel = mysqli_query($koneksi, "SELECT kelas FROM rombel WHERE id_rombel = '$id_rombel'");
$d_rombel = mysqli_fetch_assoc($q_rombel);

// 2. Ambil Semester Aktif
$q_aktif = mysqli_query($koneksi, "SELECT id_semester FROM semester WHERE status = 'Aktif' LIMIT 1");
$d_aktif = mysqli_fetch_assoc($q_aktif);
$s_id = $d_aktif['id_semester'] ?? '1';

// 3. Ambil data Kepala Sekolah
$q_profil = mysqli_query($koneksi, "SELECT * FROM profil_semester WHERE id_semester = '$s_id' LIMIT 1");
$profil = mysqli_fetch_assoc($q_profil);

// 4. Ambil data Wali Kelas
$guru = ['nama' => '-', 'nip' => '-'];
$q_cek_kolom = mysqli_query($koneksi, "DESCRIBE rombel");
while ($row = mysqli_fetch_array($q_cek_kolom)) {
    if (strpos(strtolower($row['Field']), 'guru') !== false || strpos(strtolower($row['Field']), 'wali') !== false) {
        $kolom_g = $row['Field'];
        $q_ambil_g = mysqli_query($koneksi, "SELECT g.nama, g.nip FROM master_guru g JOIN rombel r ON g.id_guru = r.$kolom_g WHERE r.id_rombel = '$id_rombel'");
        if ($q_ambil_g && mysqli_num_rows($q_ambil_g) > 0) $guru = mysqli_fetch_assoc($q_ambil_g);
        break;
    }
}

// 5. Ambil data siswa
$q_siswa = mysqli_query($koneksi, "SELECT s.id_siswa, s.nama FROM master_siswa s 
            JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa 
            WHERE ar.id_rombel = '$id_rombel' ORDER BY s.nama ASC");
$daftar_siswa = mysqli_fetch_all($q_siswa, MYSQLI_ASSOC);

// 6. Ambil data absensi (Hanya jika bukan mode blank)
$jml_hari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
$data_abs = [];
if ($mode !== 'blank') {
    $res_abs = mysqli_query($koneksi, "SELECT id_siswa, DAY(tanggal) as tgl, keterangan FROM absensi 
                                       WHERE MONTH(tanggal)='$bulan' AND YEAR(tanggal)='$tahun'");
    while($a = mysqli_fetch_assoc($res_abs)) $data_abs[$a['id_siswa']][$a['tgl']] = $a['keterangan'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Cetak Absensi - <?= $d_rombel['kelas'] ?? 'Data' ?></title>
    <style>
        body { font-family: 'Times New Roman', serif; font-size: 12px; }
        .header { text-align: center; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        table, th, td { border: 1px solid #000; }
        th, td { padding: 4px; text-align: center; }
        .nama { text-align: left; padding-left: 10px; width: 200px; }
        .btn-print { margin: 10px 5px; padding: 10px 20px; cursor: pointer; }
        @media print {
            @page { size: landscape; margin: 1cm; }
            .btn-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="header">
        <h2 style="margin:0"><?= ($mode == 'blank') ? 'ABSENSI SISWA' : 'LAPORAN ABSENSI SISWA' ?></h2>
        <h3 style="margin:0">Kelas: <?= $d_rombel['kelas'] ?? '-' ?> | Bulan: <?= date('F', mktime(0,0,0,$bulan,1)) ?> <?= $tahun ?></h3>
    </div>

    <table>
        <thead>
            <tr><th>No</th><th class="nama">Nama Siswa</th>
                <?php for($d=1; $d<=$jml_hari; $d++) echo "<th>$d</th>"; ?>
                <th>S</th><th>I</th><th>A</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $no = 1;
            foreach($daftar_siswa as $s) {
                $sakit = $izin = $alfa = 0;
                echo "<tr><td>{$no}</td><td class='nama'>{$s['nama']}</td>";
                
                // Looping hari
                for($d=1; $d<=$jml_hari; $d++) {
                    if ($mode == 'blank') {
                        $st = ''; // Benar-benar kosong untuk blanko
                    } else {
                        $st = $data_abs[$s['id_siswa']][$d] ?? '-'; // Ada strip jika data tidak ada di laporan
                        if($st == 'S') $sakit++; if($st == 'I') $izin++; if($st == 'A') $alfa++;
                    }
                    echo "<td>" . $st . "</td>";
                }
                
                // Kolom Rekap
                echo "<td>" . ($mode == 'blank' ? '' : $sakit) . "</td>
                      <td>" . ($mode == 'blank' ? '' : $izin) . "</td>
                      <td>" . ($mode == 'blank' ? '' : $alfa) . "</td></tr>";
                $no++;
            }
            ?>
        </tbody>
    </table>

    <table style="border: none; margin-top: 30px; width: 100%;">
        <tr>
            <td style="border: none; width: 50%; text-align: center;">
                Mengetahui,<br>Kepala Sekolah<br><br><br><br>
                <b><u><?= htmlspecialchars($profil['kepala_sekolah'] ?? '-') ?></u></b><br>
                NIP. <?= htmlspecialchars($profil['nip_kepala'] ?? '-') ?>
            </td>
            <td style="border: none; width: 50%; text-align: center;">
                <?= $profil['titi_mangsa'] ?? date('d F Y') ?><br>
                Wali Kelas<br><br><br><br>
                <b><u><?= htmlspecialchars($guru['nama'] ?? '-') ?></u></b><br>
                NIP. <?= htmlspecialchars($guru['nip'] ?? '-') ?>
            </td>
        </tr>
    </table>

    <div style="margin-top: 20px;">
        <button class="btn-print" onclick="window.print()">Cetak Laporan</button>
        <button class="btn-print" onclick="window.location.href='cetak_absensi.php?id_rombel=<?=$id_rombel?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>&mode=blank'">Cetak Laporan Kosong</button>
        <button class="btn-print" onclick="window.close()">Tutup</button>
    </div>

    <script>
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('mode') === 'blank') {
            window.onload = function() { window.print(); };
        }
    </script>
</body>
</html>