<?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;
$kodeKonfirmasi = strtoupper(trim($input["kode_konfirmasi"] ?? ""));
$jumlahDiterima = isset($input["jumlah_diterima"]) ? (int) $input["jumlah_diterima"] : 0;
$kondisiMakanan = trim($input["kondisi_makanan"] ?? "Baik");
$catatanSekolah = trim($input["catatan_sekolah"] ?? "");

if ($id <= 0) response(false, "ID pengiriman tidak valid", null);
if ($kodeKonfirmasi === "") response(false, "Kode konfirmasi wajib diisi", null);
if ($jumlahDiterima <= 0) response(false, "Jumlah diterima wajib lebih dari 0", null);

$cek = $conn->prepare("SELECT id, kode_konfirmasi FROM tracking_pengiriman WHERE id = ? LIMIT 1");
$cek->bind_param("i", $id);
$cek->execute();
$result = $cek->get_result();

if (!$result || $result->num_rows === 0) response(false, "Data pengiriman tidak ditemukan", null);

$row = $result->fetch_assoc();

if (strtoupper($row["kode_konfirmasi"]) !== $kodeKonfirmasi) response(false, "Kode konfirmasi tidak sesuai", null);

$status = "selesai";

$sql = "UPDATE tracking_pengiriman
SET status = ?, jumlah_diterima = ?, kondisi_makanan = ?, catatan_sekolah = ?, waktu_diterima = NOW(), waktu_selesai = NOW(), updated_at = NOW()
WHERE id = ?";

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

$stmt->bind_param("sissi", $status, $jumlahDiterima, $kondisiMakanan, $catatanSekolah, $id);

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

response(true, "Pengiriman berhasil dikonfirmasi Pihak Sekolah", ["id" => $id, "status" => $status, "jumlah_diterima" => $jumlahDiterima]);
?>
