<?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;
$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 ($sppg_id <= 0) {
    response(false, "ID SPPG tidak valid", null);
}

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

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

$sql = "
    INSERT INTO laporan_operasional
    (
        sppg_id,
        tanggal,
        menu_makanan,
        jumlah_porsi,
        jumlah_terdistribusi,
        kendala,
        catatan,
        status
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
";

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

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

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

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

?>