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

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

$tanggal = trim($input["tanggal"] ?? "");
$menu_makanan = trim($input["menu_makanan"] ?? "");
$jumlah_porsi = isset($input["jumlah_porsi"]) ? (int) $input["jumlah_porsi"] : 0;
$jumlah_terdistribusi = isset($input["jumlah_terdistribusi"]) ? (int) $input["jumlah_terdistribusi"] : 0;
$kendala = trim($input["kendala"] ?? "");
$catatan = trim($input["catatan"] ?? "");
$status = trim($input["status"] ?? "Draft");

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

if ($jumlah_porsi < 0 || $jumlah_terdistribusi < 0) {
    response(false, "Jumlah porsi tidak boleh negatif", null);
}

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

$sql = "
    UPDATE laporan_operasional
    SET
        tanggal = ?,
        menu_makanan = ?,
        jumlah_porsi = ?,
        jumlah_terdistribusi = ?,
        kendala = ?,
        catatan = ?,
        status = ?
    WHERE id = ?
";

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

$stmt->bind_param(
    "ssiisssi",
    $tanggal,
    $menu_makanan,
    $jumlah_porsi,
    $jumlah_terdistribusi,
    $kendala,
    $catatan,
    $status,
    $id
);

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

response(false, "Gagal memperbarui laporan operasional", null);

?>