<?php
// api/endpoints/tagihan_get.php
$bulanNamaMap = [
    1=>'Januari', 2=>'Februari', 3=>'Maret',     4=>'April',
    5=>'Mei',     6=>'Juni',     7=>'Juli',       8=>'Agustus',
    9=>'September',10=>'Oktober',11=>'November',  12=>'Desember'
];

$tahun   = isset($_GET['tahun'])    ? (int)$_GET['tahun']    : (int)date('Y');
$siswaId = $_GET['siswa_id']        ?? null;
$bulan   = isset($_GET['bulan'])    ? (int)$_GET['bulan']    : null;
$status  = $_GET['status']          ?? null;

$sql = "SELECT t.id, t.siswa_id, t.bulan, t.tahun, t.nominal, t.status,
               s.nama AS nama_siswa, s.nis AS nis_siswa, s.kelas, s.jurusan
        FROM tagihan_spp t
        JOIN siswa s ON t.siswa_id = s.id
        WHERE t.tahun = ? AND s.status = 'aktif'";
$params = [$tahun];
$types  = [PDO::PARAM_INT];
// Tambah setelah baris: $siswaId = $_GET['siswa_id'] ?? null;
$siswaNis = $_GET['siswa_nis'] ?? null;

// Tambah di bagian filter SQL setelah: if ($siswaId) { ... }
if ($siswaNis) {
    $sql .= " AND s.nis = ?";
    $params[] = $siswaNis;
    $types[]  = PDO::PARAM_STR;
}

if ($siswaId) { $sql .= " AND t.siswa_id = ?"; $params[] = (int)$siswaId; $types[] = PDO::PARAM_INT; }
if ($bulan)   { $sql .= " AND t.bulan = ?";    $params[] = $bulan;        $types[] = PDO::PARAM_INT; }
if ($status)  { $sql .= " AND t.status = ?";   $params[] = $status;       $types[] = PDO::PARAM_STR; }
$sql .= " ORDER BY s.nama ASC, t.bulan ASC";

$stmt = $pdo->prepare($sql);
foreach ($params as $i => $val) {
    $stmt->bindValue($i + 1, $val, $types[$i]);
}
$stmt->execute();
$rows = $stmt->fetchAll();

$result = [];
foreach ($rows as $r) {
    $result[] = [
        'id'        => (string)$r['id'],
        'siswaId'   => (string)$r['siswa_id'],
        'bulan'     => (int)$r['bulan'],
        'bulanNama' => isset($bulanNamaMap[(int)$r['bulan']]) ? $bulanNamaMap[(int)$r['bulan']] : '',
        'tahun'     => (int)$r['tahun'],
        'nominal'   => (float)$r['nominal'],
        'status'    => $r['status'],
        'namaSiswa' => $r['nama_siswa'],
        'nisSiswa'  => $r['nis_siswa'],
        'kelas'     => $r['kelas'] . ' ' . $r['jurusan'],
        'jurusan'   => $r['jurusan'],
    ];
}

respond(['status' => 'success', 'data' => $result]);