<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

$input = json_decode(file_get_contents("php://input"), true);

$nama = trim($input["nama"] ?? "");
$provinsi = trim($input["provinsi"] ?? "");
$kabupaten = trim($input["kabupaten"] ?? "");
$alamat = trim($input["alamat"] ?? "");
$total_dana = isset($input["total_dana"]) ? (int) $input["total_dana"] : 0;
$jumlah_siswa = isset($input["jumlah_siswa"]) ? (int) $input["jumlah_siswa"] : 0;
$status = trim($input["status"] ?? "Aktif");

if ($nama === "") {
    response(false, "Nama SPPG wajib diisi", null);
}

if ($total_dana < 0) {
    response(false, "Total dana tidak boleh negatif", null);
}

if ($jumlah_siswa < 0) {
    response(false, "Jumlah siswa tidak boleh negatif", null);
}

$sql = "
    INSERT INTO sppg 
    (
        nama,
        provinsi,
        kabupaten,
        alamat,
        total_dana,
        jumlah_siswa,
        status
    )
    VALUES (?, ?, ?, ?, ?, ?, ?)
";

$stmt = $conn->prepare($sql);

$stmt->bind_param(
    "ssssiis",
    $nama,
    $provinsi,
    $kabupaten,
    $alamat,
    $total_dana,
    $jumlah_siswa,
    $status
);

if ($stmt->execute()) {
    response(true, "Data SPPG berhasil ditambahkan", [
        "id" => $stmt->insert_id
    ]);
}

response(false, "Gagal menambahkan data SPPG", null);

?>