<?php
/**
 * Controller Dashboard
 */
class DashboardController {

    public function index() {
        $db = getDB();

        // Statistik utama — Aktif + Gaib dihitung sebagai siswa terdaftar
        $totalSiswa = $db->query(
            "SELECT COUNT(*) as c FROM siswa WHERE status IN ('Aktif','Gaib')"
        )->fetch_assoc()['c'];

        $totalSiswaAktif = $db->query(
            "SELECT COUNT(*) as c FROM siswa WHERE status='Aktif'"
        )->fetch_assoc()['c'];

        $totalSiswaGaib = $db->query(
            "SELECT COUNT(*) as c FROM siswa WHERE status='Gaib'"
        )->fetch_assoc()['c'];

        $totalGuru  = (query_fetch_assoc($db, "SELECT COUNT(*) as c FROM guru WHERE status='Aktif'") ?? [])['c'] ?? 0;
        $totalKelas = (query_fetch_assoc($db, "SELECT COUNT(*) as c FROM kelas") ?? [])['c'] ?? 0;
        $totalMapel = (query_fetch_assoc($db, "SELECT COUNT(*) as c FROM mata_pelajaran") ?? [])['c'] ?? 0;

        // Siswa per kelas (Aktif + Gaib)
        $siswaPerKelas = query_fetch_all($db,
            "SELECT k.nama_kelas,
                    COUNT(s.id) as total,
                    SUM(CASE WHEN s.status='Aktif' THEN 1 ELSE 0 END) as total_aktif,
                    SUM(CASE WHEN s.status='Gaib'  THEN 1 ELSE 0 END) as total_gaib
             FROM kelas k
             LEFT JOIN siswa s ON k.id = s.kelas_id AND s.status IN ('Aktif','Gaib')
             GROUP BY k.id
             ORDER BY k.tingkat, k.nama_kelas"
        );

        // Siswa per jenis kelamin (Aktif + Gaib)
        $siswaJK = query_fetch_all($db,
            "SELECT jenis_kelamin, COUNT(*) as total
             FROM siswa WHERE status IN ('Aktif','Gaib')
             GROUP BY jenis_kelamin"
        );

        // Siswa per status (semua status)
        $siswaStatus = query_fetch_all($db,
            "SELECT status, COUNT(*) as total FROM siswa GROUP BY status ORDER BY total DESC"
        );

        // Siswa terbaru
        $siswaTerbaru = query_fetch_all($db,
            "SELECT s.id, s.nama, s.nis, s.status, k.nama_kelas, s.created_at
             FROM siswa s LEFT JOIN kelas k ON s.kelas_id = k.id
             ORDER BY s.created_at DESC LIMIT 5"
        );

        // Guru per status kepegawaian
        $guruStatus = query_fetch_all($db,
            "SELECT status_kepegawaian, COUNT(*) as total FROM guru GROUP BY status_kepegawaian"
        );

        $pageTitle = 'Dashboard';
        include __DIR__ . '/../views/dashboard/index.php';
    }
}
