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

$id = isset($_POST["id"]) ? (int) $_POST["id"] : 0;
if ($id <= 0) response(false, "ID pengiriman tidak valid", null);

$uploadDir = "../../uploads/pengiriman/";
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

function uploadFile($fieldName, $uploadDir) {
    if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]["error"] !== UPLOAD_ERR_OK) return null;
    $allowed = ["jpg", "jpeg", "png", "webp"];
    $ext = strtolower(pathinfo($_FILES[$fieldName]["name"], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) response(false, "Format file harus jpg, jpeg, png, atau webp", null);
    $newName = $fieldName . "_" . time() . "_" . mt_rand(1000, 9999) . "." . $ext;
    $target = $uploadDir . $newName;
    if (!move_uploaded_file($_FILES[$fieldName]["tmp_name"], $target)) response(false, "Gagal upload file", null);
    return "uploads/pengiriman/" . $newName;
}

$fotoOmprengan = uploadFile("foto_omprengan", $uploadDir);
$fotoMenu = uploadFile("foto_menu", $uploadDir);

if (!$fotoOmprengan && !$fotoMenu) response(false, "Minimal upload foto omprengan atau foto menu", null);

$fields = [];
$params = [];
$types = "";

if ($fotoOmprengan) { $fields[] = "foto_omprengan = ?"; $params[] = $fotoOmprengan; $types .= "s"; }
if ($fotoMenu) { $fields[] = "foto_menu = ?"; $params[] = $fotoMenu; $types .= "s"; }

$fields[] = "updated_at = NOW()";
$sql = "UPDATE tracking_pengiriman SET " . implode(", ", $fields) . " WHERE id = ?";
$params[] = $id;
$types .= "i";

$stmt = $conn->prepare($sql);
if (!$stmt) response(false, "Query gagal disiapkan: " . $conn->error, null);
$stmt->bind_param($types, ...$params);
if (!$stmt->execute()) response(false, "Gagal menyimpan bukti SPPG: " . $stmt->error, null);

response(true, "Bukti SPPG berhasil diupload", [
  "id" => $id,
  "foto_omprengan" => $fotoOmprengan,
  "foto_menu" => $fotoMenu
]);
?>
