<?php

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

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

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

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;

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

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

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

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 sekolah WHERE id = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $id);
$checkStmt->execute();

$checkResult = $checkStmt->get_result();

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

$sql = "
    UPDATE sekolah
    SET
        nama_sekolah = ?,
        jenjang = ?,
        jumlah_siswa = ?
    WHERE id = ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "ssii",
    $nama_sekolah,
    $jenjang,
    $jumlah_siswa,
    $id
);

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

response(false, "Gagal memperbarui data sekolah", null);

?>