<?php
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json; charset=utf-8');

try {

    /* ============================================
       TOTAL SISWA
    ============================================ */
    $totalSiswa = (int)$pdo->query("SELECT COUNT(*) FROM siswa")->fetchColumn();
    $today = date('Y-m-d');

    /* ============================================
       TODAY COUNTS
    ============================================ */
    $stmt = $pdo->prepare("SELECT keterangan, COUNT(*) AS cnt 
                           FROM presensi 
                           WHERE tanggal = :today 
                           GROUP BY keterangan");
    $stmt->execute([':today'=>$today]);

    $todayCounts = ['H'=>0,'T'=>0,'A'=>0];
    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $todayCounts[$r['keterangan']] = (int)$r['cnt'];
    }

    /* ============================================
       DISTINCT HADIR HARI INI
    ============================================ */
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT siswa_id) FROM presensi WHERE tanggal = :today");
    $stmt->execute([':today'=>$today]);
    $presentUnique = (int)$stmt->fetchColumn();

    $alphaToday = max(0, $totalSiswa - $presentUnique);

    /* ============================================
       TREND 7 HARI
    ============================================ */
    $days7 = [];
    for ($i=6; $i>=0; $i--) {
        $days7[] = date('Y-m-d', strtotime("-$i days"));
    }

    $hadir7 = $telat7 = $alpha7 = array_fill_keys($days7, 0);

    $stmt = $pdo->prepare("SELECT tanggal, keterangan, COUNT(*) AS cnt
                           FROM presensi
                           WHERE tanggal BETWEEN :start AND :end
                           GROUP BY tanggal, keterangan");
    $stmt->execute([
        ':start'=>$days7[0],
        ':end'=>$days7[6]
    ]);

    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($r['keterangan']==='H') $hadir7[$r['tanggal']] = (int)$r['cnt'];
        if ($r['keterangan']==='T') $telat7[$r['tanggal']] = (int)$r['cnt'];
    }

    /* alpha 7 hari */
    foreach ($days7 as $d) {
        $stmt = $pdo->prepare("SELECT COUNT(DISTINCT siswa_id) 
                               FROM presensi WHERE tanggal = ?");
        $stmt->execute([$d]);
        $present = (int)$stmt->fetchColumn();
        $alpha7[$d] = max(0, $totalSiswa - $present);
    }

    /* ============================================
       TREND 30 HARI
    ============================================ */
    $days30 = [];
    for ($i=29; $i>=0; $i--) {
        $days30[] = date('Y-m-d', strtotime("-$i days"));
    }

    $hadir30 = $telat30 = $alpha30 = array_fill_keys($days30, 0);

    $stmt = $pdo->prepare("SELECT tanggal, keterangan, COUNT(*) AS cnt
                           FROM presensi
                           WHERE tanggal BETWEEN :start AND :end
                           GROUP BY tanggal, keterangan");
    $stmt->execute([
        ':start'=>$days30[0],
        ':end'=>$days30[29]
    ]);

    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($r['keterangan']==='H') $hadir30[$r['tanggal']] = (int)$r['cnt'];
        if ($r['keterangan']==='T') $telat30[$r['tanggal']] = (int)$r['cnt'];
    }

    foreach ($days30 as $d) {
        $stmt = $pdo->prepare("SELECT COUNT(DISTINCT siswa_id) 
                               FROM presensi WHERE tanggal = ?");
        $stmt->execute([$d]);
        $present = (int)$stmt->fetchColumn();
        $alpha30[$d] = max(0, $totalSiswa - $present);
    }

    /* ============================================
       HARI LIBUR NASIONAL (API KEMENAG)
    ============================================ */
    $year = date('Y');
    $cacheFile = __DIR__ . "/holiday_{$year}.json";
    $cacheExpire = 86400; // 24 jam

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpire) {
        $holidays = json_decode(file_get_contents($cacheFile), true);
    } else {
        $json = @file_get_contents("https://api-harilibur.vercel.app/api?year={$year}");
        $holidays = [];
        if ($json !== false) {
            $arr = json_decode($json, true);
            foreach ($arr as $h) {
                if ($h['is_national_holiday']) {
                    $holidays[] = [
                        'date'=>$h['holiday_date'],
                        'name'=>$h['holiday_name']
                    ];
                }
            }
            file_put_contents($cacheFile, json_encode($holidays));
        }
    }

    /* ============================================
       PRESENSI TERBARU
    ============================================ */
    $stmt = $pdo->query("
        SELECT p.*, s.nama, s.nis 
        FROM presensi p
        LEFT JOIN siswa s ON s.id = p.siswa_id
        ORDER BY p.created_at DESC 
        LIMIT 8
    ");

    $recent = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $recent[] = [
            'nama'=>$r['nama'],
            'nis'=>$r['nis'],
            'uid'=>$r['uid'],
            'tanggal'=>$r['tanggal'],
            'waktu'=>$r['waktu'],
            'keterangan'=>$r['keterangan']
        ];
    }

    /* ============================================
       OUTPUT JSON
    ============================================ */
    echo json_encode([
        'total'=>$totalSiswa,
        'today'=>$todayCounts + ['alpha'=>$alphaToday],
        'trend7'=>[
            'labels'=>array_map(fn($d)=>date('d M', strtotime($d)), $days7),
            'hadir'=>array_values($hadir7),
            'telat'=>array_values($telat7),
            'alpha'=>array_values($alpha7)
        ],
        'trend30'=>[
            'labels'=>array_map(fn($d)=>date('d M', strtotime($d)), $days30),
            'hadir'=>array_values($hadir30),
            'telat'=>array_values($telat30),
            'alpha'=>array_values($alpha30)
        ],
        'holidays'=>$holidays,
        'recent'=>$recent
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error'=>$e->getMessage()]);
}
