<?php
// api/endpoints/riwayat_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'
];

$siswaId = $_GET['siswa_id'] ?? null;
$bulan   = isset($_GET['bulan']) ? (int)$_GET['bulan'] : null;
$tahun   = isset($_GET['tahun']) ? (int)$_GET['tahun'] : null;
$siswaNis = $_GET['siswa_nis'] ?? null;
$sql = "SELECT p.id, p.jumlah_bayar, p.metode_bayar, p.no_rekening,
               p.keterangan, p.tanggal_bayar,
               t.bulan, t.tahun, t.nominal, t.status AS status_tagihan,
               s.nama AS nama_siswa, s.nis AS nis_siswa, s.kelas, s.jurusan
        FROM pembayaran p
        JOIN tagihan_spp t ON p.tagihan_id = t.id
        JOIN siswa s ON p.siswa_id = s.id
        WHERE 1=1";
$params = [];

if ($siswaId) { $sql .= " AND p.siswa_id = ?"; $params[] = (int)$siswaId; }
if ($bulan)   { $sql .= " AND t.bulan = ?";    $params[] = $bulan; }
if ($tahun)   { $sql .= " AND t.tahun = ?";    $params[] = $tahun; }
if ($siswaNis) { $sql .= " AND s.nis = ?"; $params[] = $siswaNis; }
$sql .= " ORDER BY p.tanggal_bayar DESC";

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

$result = [];
foreach ($rows as $r) {
    $bulanInt = (int)$r['bulan'];
    $result[] = [
        'id'            => (string)$r['id'],
        'jumlahBayar'   => (float)$r['jumlah_bayar'],
        'metodeBayar'   => $r['metode_bayar'],
        'keterangan'    => $r['keterangan']    ?? '',
        'tanggalBayar'  => $r['tanggal_bayar'],
        'bulan'         => $bulanInt,
        'bulanNama'     => isset($bulanNamaMap[$bulanInt]) ? $bulanNamaMap[$bulanInt] : '',
        'tahun'         => (int)$r['tahun'],
        'nominal'       => (float)$r['nominal'],
        'statusTagihan' => $r['status_tagihan'],
        'namaSiswa'     => $r['nama_siswa'],
        'nisSiswa'      => $r['nis_siswa'],
        'kelas'         => $r['kelas'] . ' ' . $r['jurusan'],
        'jurusan'       => $r['jurusan'],
    ];
}

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