<?php
// 1. Koneksi Database
include "config/conn.php"; 

// Logika otomatis mendeteksi variabel koneksi
if (isset($conn)) { $db = $conn; }
elseif (isset($koneksi)) { $db = $koneksi; }
else { die("Koneksi gagal: Variabel database tidak ditemukan."); }

// 2. Menangkap Data dari Form Filter (Menerima GET dari cetak_filter.php)
$tgl1  = isset($_GET['tgl_awal']) ? $_GET['tgl_awal'] : date('Y-m-d');
$tgl2  = isset($_GET['tgl_akhir']) ? $_GET['tgl_akhir'] : date('Y-m-d');
$kelas = isset($_GET['kelas']) ? $_GET['kelas'] : 'all';

// Membuat Filter SQL
$filter = "WHERE a.tgl BETWEEN '$tgl1' AND '$tgl2'";
if($kelas != 'all') {
    $filter .= " AND s.idk = '$kelas'";
}

// 3. Panggil Library TCPDF
require_once('tcpdf/tcpdf.php');

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(15, 15, 15);
$pdf->AddPage();

// 4. Judul dan Keterangan Filter
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, 'LAPORAN DATA ABSENSI SISWA', 0, 1, 'C');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 7, 'Periode: '.$tgl1.' s/d '.$tgl2, 0, 1, 'C');
$pdf->Ln(5);

// 5. Tabel Header (Ditambah kolom Tanggal)
$html = '
<table border="1" cellpadding="5">
    <thead>
        <tr style="background-color: #dfdfdf; font-weight: bold;">
            <th width="7%" align="center">No</th>
            <th width="18%" align="center">Tanggal</th>
            <th width="15%" align="center">NIS</th>
            <th width="30%">Nama Siswa</th>
            <th width="12%" align="center">Kelas</th>
            <th width="18%" align="center">Keterangan</th>
        </tr>
    </thead>
    <tbody>';

// 6. QUERY FINAL dengan Filter
$no = 1;
$sql = "SELECT a.*, s.nama, s.nis, k.nama AS nama_kelas 
        FROM absen a 
        JOIN siswa s ON a.ids = s.ids 
        JOIN kelas k ON s.idk = k.idk
        $filter
        ORDER BY a.tgl ASC, k.nama ASC, s.nama ASC";

$query = mysqli_query($db, $sql); 

if($query && mysqli_num_rows($query) > 0) {
    while($data = mysqli_fetch_assoc($query)) {
        // Pemetaan keterangan
        $ket = $data['ket'];
        if($ket == 'M') $ket = 'Masuk';
        elseif($ket == 'S') $ket = 'Sakit';
        elseif($ket == 'I') $ket = 'Izin';
        elseif($ket == 'A') $ket = 'Alpa';

        $html .= '
        <tr>
            <td align="center">'.$no++.'</td>
            <td align="center">'.$data['tgl'].'</td>
            <td align="center">'.$data['nis'].'</td>
            <td>'.$data['nama'].'</td>
            <td align="center">'.$data['nama_kelas'].'</td>
            <td align="center">'.$ket.'</td>
        </tr>';
    }
} else {
    $html .= '<tr><td colspan="6" align="center">Data tidak ditemukan pada periode ini.</td></tr>';
}

$html .= '</tbody></table>';

$pdf->writeHTML($html, true, false, true, false, '');

// 7. Output PDF
$pdf->Output('Laporan_Absensi_Filter.pdf', 'I');
?>