<?php
// api/endpoints/dashboard_get.php
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : (int)date('n');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : (int)date('Y');

// Total siswa aktif
$totalSiswa = (int)$pdo->query("SELECT COUNT(*) FROM siswa WHERE status='aktif'")->fetchColumn();

// Tagihan bulan ini per status
$q = $pdo->prepare("SELECT status, COUNT(*) AS n FROM tagihan_spp WHERE bulan=? AND tahun=? GROUP BY status");
$q->execute([$bulan, $tahun]);
$lunas = $belumBayar = $cicilan = 0;
foreach ($q->fetchAll() as $r) {
    if ($r['status'] === 'lunas')            $lunas      = (int)$r['n'];
    elseif ($r['status'] === 'belum_bayar')  $belumBayar = (int)$r['n'];
    elseif ($r['status'] === 'cicilan')      $cicilan    = (int)$r['n'];
}

// Total pemasukan bulan ini
$qp = $pdo->prepare("
    SELECT COALESCE(SUM(p.jumlah_bayar), 0) AS total
    FROM pembayaran p
    JOIN tagihan_spp t ON p.tagihan_id = t.id
    WHERE t.bulan = ? AND t.tahun = ?
");
$qp->execute([$bulan, $tahun]);
$totalPemasukan = (int)$qp->fetchColumn();

// Ambil nominal SPP dari pengaturan
$nominalStmt = $pdo->query("SELECT nilai FROM pengaturan WHERE kunci='nominal_spp' LIMIT 1");
$nominalSpp  = (int)($nominalStmt->fetchColumn() ?: 200000);

respond(['status' => 'success', 'data' => [
    'totalSiswa'      => $totalSiswa,
    'totalLunas'      => $lunas,
    'totalBelumBayar' => $belumBayar,
    'totalCicilan'    => $cicilan,
    'totalPemasukan'  => $totalPemasukan,
    'nominalSpp'      => $nominalSpp,
    'bulan'           => $bulan,
    'tahun'           => $tahun,
]]);