<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

/* ================================
   CEK LOGIN
================================ */
if (!isset($_SESSION['user'])) {
    header("Location: /presensi_v1/auth/login.php");
    exit;
}

/* ================================
   CEK ROLE YANG DIIZINKAN
================================ */
$allowed = ['superadmin', 'operator', 'guru'];

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

/* ================================
   LOAD HEADER SESUAI ROLE
================================ */
if ($_SESSION['user']['role'] === 'guru') {
    require_once __DIR__ . '/../includes/header_guru.php';
} else {
    require_once __DIR__ . '/../includes/header_admin.php';
}

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

$kelas_combo = $_GET["kelas_combo"] ?? "";

$limit  = intval($_GET["limit"] ?? 10);
$page   = max(1, intval($_GET["p"] ?? 1));
$offset = ($page - 1) * $limit;

/* ================================
   LOAD DROPDOWN KELAS 
================================ */
$comboStmt = $pdo->query("
    SELECT DISTINCT kelas, jurusan, rombel 
    FROM siswa 
    ORDER BY kelas, jurusan, rombel
");
$combos = $comboStmt->fetchAll(PDO::FETCH_ASSOC);

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

if ($kelas_combo !== "") {
    $parts = explode("-", $kelas_combo);
    if (count($parts) === 3) {
        $where[] = "s.kelas = :kls";
        $where[] = "s.jurusan = :jrs";
        $where[] = "s.rombel = :rmb";
        $params[":kls"] = $parts[0];
        $params[":jrs"] = $parts[1];
        $params[":rmb"] = $parts[2];
    }
}

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

/* ================================
   HITUNG TOTAL DATA
================================ */
$stmt_total = $pdo->prepare("
    SELECT COUNT(*)
    FROM presensi p
    JOIN siswa s ON s.id = p.siswa_id
    WHERE $where_sql
");
$stmt_total->execute($params);

$total = $stmt_total->fetchColumn();
$total_pages = max(1, ceil($total / $limit));

/* ================================
   FETCH DATA PRESENSI
================================ */
$stmt = $pdo->prepare("
    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 p.tanggal DESC, p.waktu DESC
    LIMIT :limit OFFSET :offset
");

foreach ($params as $k=>$v) {
    $stmt->bindValue($k, $v);
}

$stmt->bindValue(":limit", $limit, PDO::PARAM_INT);
$stmt->bindValue(":offset", $offset, PDO::PARAM_INT);

$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- ================================ -->
<!-- FILTER BAR -->
<!-- ================================ -->
<div class="card shadow-sm mb-4">
    <div class="card-body p-3">

        <form method="GET" class="row g-2 align-items-end">

            <div class="col-md-3">
                <label class="form-label small">Dari Tanggal</label>
                <input type="date" name="from" value="<?= $from ?>" class="form-control">
            </div>

            <div class="col-md-3">
                <label class="form-label small">Sampai</label>
                <input type="date" name="to" value="<?= $to ?>" class="form-control">
            </div>

            <div class="col-md-4">
                <label class="form-label small">Filter Kelas</label>
                <select name="kelas_combo" class="form-select">
                    <option value="">Semua Kelas</option>

                    <?php foreach ($combos as $c):
                        $val = "{$c['kelas']}-{$c['jurusan']}-{$c['rombel']}";
                        $sel = ($kelas_combo === $val) ? "selected" : "";
                    ?>
                        <option value="<?= $val ?>" <?= $sel ?>>
                            <?= "{$c['kelas']} {$c['jurusan']} - {$c['rombel']}" ?>
                        </option>
                    <?php endforeach; ?>

                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label small">Data / Page</label>
                <select name="limit" class="form-select">
                    <?php foreach ([10,25,50] as $l): ?>
                        <option value="<?= $l ?>" <?= $l==$limit?"selected":"" ?>>
                            <?= $l ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-12 d-flex gap-2 mt-2">

                <button class="btn btn-primary">Terapkan</button>

                <!-- EXPORT -->
                <div class="dropdown">
                    <button class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown">
                        Export
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item" target="_blank"
                               href="/presensi_v1/process/export_pdf.php?from=<?= $from ?>&to=<?= $to ?>&kelas_combo=<?= $kelas_combo ?>">
                                Export PDF
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item"
                               href="/presensi_v1/process/export_xlsx.php?from=<?= $from ?>&to=<?= $to ?>&kelas_combo=<?= $kelas_combo ?>">
                                Export XLSX
                            </a>
                        </li>
                    </ul>
                </div>

            </div>

        </form>

    </div>
</div>

<!-- ================================ -->
<!-- TABEL REKAP PRESENSI -->
<!-- ================================ -->

<div class="card shadow-sm mb-4">
    <div class="card-header bg-primary text-white fw-bold">
        Rekap Presensi
    </div>

    <div class="card-body p-0">

        <table class="table table-hover table-striped align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th width="90">Tanggal</th>
                    <th width="80">Jam</th>
                    <th width="90">NIS</th>
                    <th>Nama</th>
                    <th width="170">Kelas</th>
                    <th width="70" class="text-center">Ket</th>
                </tr>
            </thead>

            <tbody>
            <?php if (!$rows): ?>
                <tr>
                    <td colspan="6" class="text-center text-muted py-3">
                        Tidak ada data presensi.
                    </td>
                </tr>

            <?php else: foreach ($rows as $r): ?>
                <tr>
                    <td><?= date("d/m/Y", strtotime($r["tanggal"])) ?></td>
                    <td><?= substr($r["waktu"], 0, 5) ?></td>
                    <td><?= $r["nis"] ?></td>
                    <td><?= $r["nama"] ?></td>
                    <td><?= "{$r['kelas']} {$r['jurusan']} - {$r['rombel']}" ?></td>

                    <td class="text-center">
                        <?php if ($r["keterangan"] === "H"): ?>
                            <span class="badge bg-success">H</span>
                        <?php elseif ($r["keterangan"] === "T"): ?>
                            <span class="badge bg-warning text-dark">T</span>
                        <?php else: ?>
                            <span class="badge bg-danger">A</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>

    </div>

    <!-- PAGINATION -->
    <div class="p-3">
        <nav>
            <ul class="pagination mb-0">
                <?php for ($i=1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= ($page==$i)?"active":"" ?>">
                        <a class="page-link"
                           href="?from=<?= $from ?>&to=<?= $to ?>&kelas_combo=<?= $kelas_combo ?>&limit=<?= $limit ?>&p=<?= $i ?>">
                            <?= $i ?>
                        </a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
    </div>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
