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

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

$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 ($nama_barang === "") {
    response(false, "Nama barang wajib diisi", null);
}

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

$checkSql = "SELECT id FROM omprengan 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 omprengan tidak ditemukan", null);
}

$sql = "
    UPDATE omprengan
    SET
        nama_barang = ?,
        kategori = ?,
        jumlah = ?,
        kondisi = ?,
        keterangan = ?
    WHERE id = ?
";

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

$stmt->bind_param(
    "ssissi",
    $nama_barang,
    $kategori,
    $jumlah,
    $kondisi,
    $keterangan,
    $id
);

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

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

?>