<?php
// api/endpoints/siswa_post.php
$required = ['nis', 'nama', 'kelas', 'jurusan', 'tahunAjaran'];
foreach ($required as $f) {
    if (empty($body[$f])) respond(['status' => 'error', 'message' => "Field '$f' wajib diisi"], 400);
}

// Cek NIS duplikat
$cek = $pdo->prepare("SELECT id FROM siswa WHERE nis = ?");
$cek->execute([$body['nis']]);
if ($cek->fetch()) respond(['status' => 'error', 'message' => 'NIS sudah terdaftar'], 400);

$ins = $pdo->prepare("
    INSERT INTO siswa (nis, nama, kelas, jurusan, tahun_ajaran, no_hp, alamat)
    VALUES (?, ?, ?, ?, ?, ?, ?)
");
$ins->execute([
    $body['nis'],
    $body['nama'],
    $body['kelas'],
    $body['jurusan'],
    $body['tahunAjaran'],
    $body['noHp']   ?? '',
    $body['alamat'] ?? ''
]);
$newId = (int)$pdo->lastInsertId();

// Auto-generate tagihan 12 bulan
$tahun   = (int)date('Y');
$nomStmt = $pdo->query("SELECT nilai FROM pengaturan WHERE kunci='nominal_spp' LIMIT 1");
$nominal = (int)($nomStmt->fetchColumn() ?: 200000);

$insT = $pdo->prepare("
    INSERT IGNORE INTO tagihan_spp (siswa_id, bulan, tahun, nominal, status)
    VALUES (?, ?, ?, ?, 'belum_bayar')
");
for ($b = 1; $b <= 12; $b++) {
    $insT->execute([$newId, $b, $tahun, $nominal]);
}

respond(['status' => 'success', 'id' => (string)$newId], 201);