<?php
require_once __DIR__ . '/../config/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$allowed = ['superadmin', 'operator', 'guru'];
if (!isset($_SESSION['user']) || !in_array($_SESSION['user']['role'], $allowed)) {
    header("Location: /presensi_v1/preview.php");
    exit;
}

require_once __DIR__ . '/../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/* ================================
   FILTER
================================ */
$from = $_GET["from"] ?? date("Y-m-01");
$to   = $_GET["to"] ?? date("Y-m-d");

$kelas_combo = $_GET["kelas_combo"] ?? "";
$kelas = $jurusan = $rombel = "";

if ($kelas_combo !== "") {
    $p = explode("-", $kelas_combo);
    if (count($p) === 3) {
        $kelas = $p[0];
        $jurusan = $p[1];
        $rombel = $p[2];
    }
}

/* ================================
   QUERY FILTER
================================ */
$where = ["p.tanggal BETWEEN :from AND :to"];
$params = [":from"=>$from, ":to"=>$to];

if ($kelas)   { $where[] = "s.kelas = :kelas";     $params[":kelas"]   = $kelas; }
if ($jurusan) { $where[] = "s.jurusan = :jurusan"; $params[":jurusan"] = $jurusan; }
if ($rombel)  { $where[] = "s.rombel = :rombel";   $params[":rombel"]  = $rombel; }

$where_sql = implode(" AND ", $where);

/* ================================
   GET DATA
================================ */
$sql = "
SELECT p.*, s.nama, s.nis, s.kelas, s.jurusan, s.rombel
FROM presensi p
JOIN siswa s ON s.id = p.siswa_id
WHERE $where_sql
ORDER BY tanggal, waktu
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

/* ================================
   SPREADSHEET
================================ */
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Rekap");

/* Header */
$sheet->fromArray(["Tanggal","Jam","NIS","Nama","Kelas","Ket"], NULL, "A1");

/* Data */
$rowNum = 2;
foreach ($rows as $r) {
    $sheet->setCellValue("A$rowNum", date("d/m/Y", strtotime($r["tanggal"])));
    $sheet->setCellValue("B$rowNum", substr($r["waktu"], 0, 5));
    $sheet->setCellValue("C$rowNum", $r["nis"]);
    $sheet->setCellValue("D$rowNum", $r["nama"]);
    $sheet->setCellValue("E$rowNum", $r["kelas"]." ".$r["jurusan"]." - ".$r["rombel"]);
    $sheet->setCellValue("F$rowNum", $r["keterangan"]);
    $rowNum++;
}

/* Column Auto Width */
foreach (range('A','F') as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

$filename = "rekap_{$from}_{$to}.xlsx";

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"$filename\"");

$writer = new Xlsx($spreadsheet);
$writer->save("php://output");
exit;
