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

$required = ['tagihanId', 'siswaId', 'jumlahBayar', 'metodeBayar'];
foreach ($required as $f) {
    if (!isset($body[$f]) || $body[$f] === '') {
        respond(['status' => 'error', 'message' => "Field '$f' wajib diisi"], 400);
    }
}

$tagihanId  = (int)$body['tagihanId'];
$siswaId    = (int)$body['siswaId'];
$jumlah     = (float)$body['jumlahBayar'];
$metode     = $body['metodeBayar'];
$noRek      = $body['noRekening']  ?? '';
$keterangan = $body['keterangan']  ?? '';

// Cek tagihan ada & belum lunas
$t = $pdo->prepare("SELECT * FROM tagihan_spp WHERE id=? AND siswa_id=?");
$t->execute([$tagihanId, $siswaId]);
$tagihan = $t->fetch();
if (!$tagihan) respond(['status' => 'error', 'message' => 'Tagihan tidak ditemukan'], 404);
if ($tagihan['status'] === 'lunas') respond(['status' => 'error', 'message' => 'Tagihan sudah lunas'], 400);

// Hitung sisa tagihan
$q = $pdo->prepare("SELECT COALESCE(SUM(jumlah_bayar),0) AS total FROM pembayaran WHERE tagihan_id=?");
$q->execute([$tagihanId]);
$row        = $q->fetch();
$sudahBayar = (float)$row['total'];
$sisaNominal = (float)$tagihan['nominal'] - $sudahBayar;

if ($jumlah <= 0)            respond(['status' => 'error', 'message' => 'Jumlah bayar harus lebih dari 0'], 400);
if ($jumlah > $sisaNominal)  respond(['status' => 'error', 'message' => "Melebihi sisa tagihan Rp $sisaNominal"], 400);

// Ambil admin_id pertama
$adminStmt = $pdo->query("SELECT id FROM admin LIMIT 1");
$adminRow  = $adminStmt->fetch();
$adminId   = (int)($adminRow['id'] ?? 1);

// Simpan pembayaran
$ins = $pdo->prepare("
    INSERT INTO pembayaran (tagihan_id, siswa_id, admin_id, jumlah_bayar, metode_bayar, no_rekening, keterangan, tanggal_bayar)
    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
");
$ins->execute([$tagihanId, $siswaId, $adminId, $jumlah, $metode, $noRek, $keterangan]);

// Update status tagihan
$totalBayar = $sudahBayar + $jumlah;
$statusBaru = ($totalBayar >= (float)$tagihan['nominal']) ? 'lunas' : 'cicilan';
$pdo->prepare("UPDATE tagihan_spp SET status=? WHERE id=?")->execute([$statusBaru, $tagihanId]);

$bulanInt  = (int)$tagihan['bulan'];
$bulanNama = isset($bulanNamaMap[$bulanInt]) ? $bulanNamaMap[$bulanInt] : '';

respond([
    'status'        => 'success',
    'statusTagihan' => $statusBaru,
    'sisaBayar'     => (float)$tagihan['nominal'] - $totalBayar,
    'bulanNama'     => $bulanNama,
], 201);