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

$input = json_decode(file_get_contents("php://input"), true);
$id = isset($input["id"]) ? (int) $input["id"] : 0;
$status = trim($input["status"] ?? "");
$catatanSppg = trim($input["catatan_sppg"] ?? "");

$allowed = ["persiapan", "packing", "berangkat", "dalam_perjalanan", "tiba_di_sekolah", "diterima_sekolah", "selesai", "bermasalah"];
$timeColumn = [
  "persiapan" => "waktu_persiapan",
  "packing" => "waktu_packing",
  "berangkat" => "waktu_berangkat",
  "dalam_perjalanan" => "waktu_dalam_perjalanan",
  "tiba_di_sekolah" => "waktu_tiba",
  "diterima_sekolah" => "waktu_diterima",
  "selesai" => "waktu_selesai",
  "bermasalah" => "updated_at"
];

if ($id <= 0) response(false, "ID pengiriman tidak valid", null);
if (!in_array($status, $allowed)) response(false, "Status pengiriman tidak valid", null);

$column = $timeColumn[$status];

$sql = "UPDATE tracking_pengiriman SET status = ?, catatan_sppg = ?, $column = NOW(), updated_at = NOW() WHERE id = ?";
$stmt = $conn->prepare($sql);

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

$stmt->bind_param("ssi", $status, $catatanSppg, $id);

if (!$stmt->execute()) response(false, "Gagal memperbarui status pengiriman: " . $stmt->error, null);

response(true, "Status pengiriman berhasil diperbarui", ["id" => $id, "status" => $status]);
?>
