<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") exit;
require "../../config/database.php";
require "../../helpers/response.php";

$periode = trim($_GET["periode"] ?? "mingguan");
$sppgId = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;

if (!in_array($periode, ["mingguan", "bulanan"])) $periode = "mingguan";

if ($periode === "mingguan") {
    $tanggalMulai = date("Y-m-d", strtotime("monday this week"));
    $tanggalSelesai = date("Y-m-d", strtotime("sunday this week"));
} else {
    $tanggalMulai = date("Y-m-01");
    $tanggalSelesai = date("Y-m-t");
}

$where = ["DATE(created_at) BETWEEN ? AND ?"];
$params = [$tanggalMulai, $tanggalSelesai];
$types = "ss";

if ($sppgId > 0) {
    $where[] = "sppg_id = ?";
    $params[] = $sppgId;
    $types .= "i";
}

$whereSql = implode(" AND ", $where);

$sql = "SELECT
COUNT(*) AS total_pengiriman,
COALESCE(SUM(jumlah_porsi),0) AS total_porsi,
SUM(CASE WHEN status = 'selesai' THEN 1 ELSE 0 END) AS total_tervalidasi,
SUM(CASE WHEN status = 'bermasalah' THEN 1 ELSE 0 END) AS total_bermasalah,
SUM(CASE WHEN foto_omprengan IS NOT NULL THEN 1 ELSE 0 END) AS bukti_omprengan,
SUM(CASE WHEN foto_menu IS NOT NULL THEN 1 ELSE 0 END) AS bukti_menu,
SUM(CASE WHEN foto_penerimaan IS NOT NULL THEN 1 ELSE 0 END) AS bukti_penerimaan
FROM tracking_pengiriman
WHERE $whereSql";

$stmt = $conn->prepare($sql);
if (!$stmt) response(false, "Query gagal disiapkan: " . $conn->error, null);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$summary = $result->fetch_assoc();

response(true, "Rekap pengiriman berhasil diambil", [
  "periode" => $periode,
  "tanggal_mulai" => $tanggalMulai,
  "tanggal_selesai" => $tanggalSelesai,
  "summary" => [
    "total_pengiriman" => (int) ($summary["total_pengiriman"] ?? 0),
    "total_porsi" => (int) ($summary["total_porsi"] ?? 0),
    "total_tervalidasi" => (int) ($summary["total_tervalidasi"] ?? 0),
    "total_bermasalah" => (int) ($summary["total_bermasalah"] ?? 0),
    "bukti_omprengan" => (int) ($summary["bukti_omprengan"] ?? 0),
    "bukti_menu" => (int) ($summary["bukti_menu"] ?? 0),
    "bukti_penerimaan" => (int) ($summary["bukti_penerimaan"] ?? 0)
  ]
]);
?>
