<?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_barang = trim($input["nama_barang"] ?? "");
$kategori = trim($input["kategori"] ?? "");
$jumlah = isset($input["jumlah"]) ? (int) $input["jumlah"] : 0;
$kondisi = trim($input["kondisi"] ?? "Baik");
$keterangan = trim($input["keterangan"] ?? "");

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

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

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

$sql = "
    INSERT INTO omprengan
    (
        sppg_id,
        nama_barang,
        kategori,
        jumlah,
        kondisi,
        keterangan
    )
    VALUES (?, ?, ?, ?, ?, ?)
";

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

$stmt->bind_param(
    "ississ",
    $sppg_id,
    $nama_barang,
    $kategori,
    $jumlah,
    $kondisi,
    $keterangan
);

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

response(false, "Gagal menambahkan omprengan", null);

?>