<?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);

$id = isset($input["id"]) ? (int) $input["id"] : 0;
$hasil = trim($input["hasil"] ?? "");
$catatan = trim($input["catatan_validasi"] ?? "");

if ($id <= 0) {
    response(false, "ID laporan tidak valid", null);
}

if (!in_array($hasil, ["sesuai", "tidak_sesuai"])) {
    response(false, "Hasil validasi harus sesuai atau tidak_sesuai", null);
}

$finalStatus = $hasil === "sesuai" ? "tervalidasi" : "tidak_sesuai";

$stmt = $conn->prepare("
    UPDATE menu_harian
    SET
      status = ?,
      catatan_validasi = ?,
      waktu_validasi = NOW()
    WHERE id = ?
");

if (!$stmt) {
    response(false, "Query update validasi gagal disiapkan: " . $conn->error, null);
}

$stmt->bind_param("ssi", $finalStatus, $catatan, $id);

if (!$stmt->execute()) {
    response(false, "Gagal menyimpan validasi: " . $stmt->error, null);
}

response(true, "Validasi laporan berhasil disimpan", [
    "id" => $id,
    "status" => $finalStatus
]);
?>
