<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

// Toggle attendance status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['absensi_id'])) {
    if (!validateCsrf()) { setFlash('error', 'CSRF error.'); header('Location: ' . url('/admin/absensi.php')); exit; }
    $absensiId = (int)$_POST['absensi_id'];
    $newStatus = $_POST['new_status'] === 'hadir' ? 'hadir' : 'tidak_hadir';
    $pdo->prepare("UPDATE absensi SET status = ? WHERE id = ?")->execute([$newStatus, $absensiId]);
    setFlash('success', 'Status absensi diperbarui.');
    header('Location: ' . url('/admin/absensi.php' . (isset($_POST['kelas_filter']) ? '?kelas_id=' . (int)$_POST['kelas_filter'] : '')));
    exit;
}

// Filters
$kelasFilter = (int)($_GET['kelas_id'] ?? 0);

// Build query
$sql = "SELECT a.*, u.nama, u.email, k.nama_kelas, k.hari, k.jam_mulai, k.jam_selesai FROM absensi a JOIN users u ON a.user_id = u.id JOIN kelas k ON a.kelas_id = k.id";
$params = [];
if ($kelasFilter > 0) { $sql .= " WHERE a.kelas_id = ?"; $params[] = $kelasFilter; }
$sql .= " ORDER BY k.nama_kelas, u.nama";

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

$totalHadir = count(array_filter($absensiList, fn($a) => $a['status'] === 'hadir'));

// Get kelas list for filter
$kelasList = $pdo->query("SELECT id, nama_kelas FROM kelas ORDER BY nama_kelas")->fetchAll();

require_once __DIR__ . '/../includes/header.php';
?>
<div class="max-w-6xl mx-auto px-4 py-8">
    <div class="mb-8 animate-fadeUp"><h1 class="text-3xl font-black mb-2">Laporan <span class="text-volt">Absensi</span></h1><p class="text-muted text-sm">Kelola daftar hadir per kelas</p></div>

    <!-- Filter -->
    <div class="flex flex-wrap gap-4 mb-6 animate-fadeUp d1">
        <form method="GET" class="flex gap-3">
            <select name="kelas_id" class="form-input w-auto" onchange="this.form.submit()">
                <option value="0">Semua Kelas</option>
                <?php foreach ($kelasList as $k): ?>
                <option value="<?= $k['id'] ?>" <?= $kelasFilter == $k['id'] ? 'selected' : '' ?>><?= htmlspecialchars($k['nama_kelas']) ?></option>
                <?php endforeach; ?>
            </select>
        </form>
        <button onclick="window.print()" class="px-4 py-2 border border-border rounded-lg text-sm text-muted hover:text-white hover:border-volt transition-all">🖨 Print</button>
    </div>

    <div class="card animate-fadeUp d2">
        <div class="overflow-x-auto">
            <table class="data-table">
                <thead><tr><th>No</th><th>Nama</th><th>Email</th><th>Kelas</th><th>Hari/Jam</th><th>Status</th><th>Aksi</th></tr></thead>
                <tbody>
                <?php foreach ($absensiList as $i => $a): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td class="font-bold"><?= htmlspecialchars($a['nama']) ?></td>
                    <td class="text-muted text-sm"><?= htmlspecialchars($a['email']) ?></td>
                    <td><?= htmlspecialchars($a['nama_kelas']) ?></td>
                    <td class="text-sm text-muted"><?= $a['hari'] ?> <?= date('H:i', strtotime($a['jam_mulai'])) ?>-<?= date('H:i', strtotime($a['jam_selesai'])) ?></td>
                    <td><span class="badge-<?= $a['status']==='hadir'?'tervalidasi':'ditolak' ?>"><?= $a['status']==='hadir'?'Hadir':'Tidak Hadir' ?></span></td>
                    <td>
                        <form method="POST" class="inline">
                            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                            <input type="hidden" name="absensi_id" value="<?= $a['id'] ?>">
                            <input type="hidden" name="new_status" value="<?= $a['status']==='hadir'?'tidak_hadir':'hadir' ?>">
                            <input type="hidden" name="kelas_filter" value="<?= $kelasFilter ?>">
                            <button type="submit" class="text-xs text-volt font-bold hover:underline">Toggle</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($absensiList)): ?>
                <tr><td colspan="7" class="text-center text-muted py-8">Tidak ada data absensi</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php if (!empty($absensiList)): ?>
        <div class="mt-4 pt-4 border-t border-border flex justify-between text-sm">
            <span class="text-muted">Total: <?= count($absensiList) ?> data</span>
            <span class="font-bold text-volt">Hadir: <?= $totalHadir ?> / <?= count($absensiList) ?></span>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
