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

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

$sppg_id = isset($input["sppg_id"]) ? (int) $input["sppg_id"] : 0;
$tanggal = trim($input["tanggal"] ?? "");
$kategori = trim($input["kategori"] ?? "");
$deskripsi = trim($input["deskripsi"] ?? "");
$supplier = trim($input["supplier"] ?? "");
$jenis = trim($input["jenis"] ?? "Pengeluaran");
$jumlah = isset($input["jumlah"]) ? (int) $input["jumlah"] : 0;

if ($sppg_id <= 0) {
    response(false, "SPPG wajib dipilih", null);
}

if ($tanggal === "") {
    response(false, "Tanggal wajib diisi", null);
}

if ($kategori === "") {
    response(false, "Kategori wajib diisi", null);
}

if (!in_array($jenis, ["Pemasukan", "Pengeluaran"])) {
    response(false, "Jenis transaksi tidak valid", null);
}

if ($jumlah <= 0) {
    response(false, "Jumlah transaksi harus lebih dari 0", null);
}

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

$query = "
    UPDATE transaksi
    SET
        sppg_id = ?,
        tanggal = ?,
        kategori = ?,
        deskripsi = ?,
        supplier = ?,
        jenis = ?,
        jumlah = ?
    WHERE id = ?
";

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

$stmt->bind_param(
    "isssssii",
    $sppg_id,
    $tanggal,
    $kategori,
    $deskripsi,
    $supplier,
    $jenis,
    $jumlah,
    $id
);

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

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

?>