<?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 bahan tidak valid", null);
}

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

$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 ($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 = "
    UPDATE bahan_makanan
    SET
        nama_bahan = ?,
        kategori = ?,
        satuan = ?,
        stok = ?,
        harga_satuan = ?,
        tanggal_masuk = ?
    WHERE id = ?
";

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

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

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

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

?> 