<?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);

$sppg_id = isset($input["sppg_id"]) ? (int) $input["sppg_id"] : 0;
$nama_sekolah = trim($input["nama_sekolah"] ?? "");
$jenjang = trim($input["jenjang"] ?? "");
$jumlah_siswa = isset($input["jumlah_siswa"]) ? (int) $input["jumlah_siswa"] : 0;

if ($sppg_id <= 0) {
    response(false, "ID SPPG tidak valid", null);
}

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

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

$checkSql = "SELECT id FROM sppg WHERE id = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $sppg_id);
$checkStmt->execute();

$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows === 0) {
    response(false, "Data SPPG tidak ditemukan", null);
}

$query = "
    INSERT INTO sekolah
    (
        sppg_id,
        nama_sekolah,
        jenjang,
        jumlah_siswa
    )
    VALUES (?, ?, ?, ?)
";

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

$stmt->bind_param(
    "issi",
    $sppg_id,
    $nama_sekolah,
    $jenjang,
    $jumlah_siswa
);

if ($stmt->execute()) {
    response(true, "Data sekolah berhasil ditambahkan", [
        "id" => $stmt->insert_id
    ]);
} else {
    response(false, "Gagal menambahkan data sekolah", null);
}

?>