<?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_bahan = trim($input["nama_bahan"] ?? "");
$kategori = trim($input["kategori"] ?? "");
$satuan = trim($input["satuan"] ?? "");
$stok = isset($input["stok"]) ? (float) $input["stok"] : 0;
$harga_satuan = isset($input["harga_satuan"]) ? (float) $input["harga_satuan"] : 0;
$tanggal_masuk = trim($input["tanggal_masuk"] ?? "");

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

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

if ($stok < 0 || $harga_satuan < 0) {
    response(false, "Stok dan harga tidak boleh negatif", null);
}

$sql = "
    INSERT INTO bahan_makanan
    (
        sppg_id,
        nama_bahan,
        kategori,
        satuan,
        stok,
        harga_satuan,
        tanggal_masuk
    )
    VALUES (?, ?, ?, ?, ?, ?, ?)
";

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

$stmt->bind_param(
    "isssdds",
    $sppg_id,
    $nama_bahan,
    $kategori,
    $satuan,
    $stok,
    $harga_satuan,
    $tanggal_masuk
);

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

response(false, "Gagal menambahkan bahan makanan", null);

?>