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

$data = [
    "total_sppg" => 0,
    "total_dana" => 0,
    "total_omprengan" => 0,
    "update_terakhir" => date("Y-m-d H:i:s")
];

$sql = "
    SELECT
        (SELECT COUNT(*) FROM sppg) AS total_sppg,
        (SELECT COALESCE(SUM(total_dana), 0) FROM sppg) AS total_dana,
        (SELECT COALESCE(SUM(jumlah), 0) FROM omprengan) AS total_omprengan,
        GREATEST(
            COALESCE((SELECT MAX(created_at) FROM sppg), '1970-01-01 00:00:00'),
            COALESCE((SELECT MAX(created_at) FROM pengaduan), '1970-01-01 00:00:00'),
            COALESCE((SELECT MAX(created_at) FROM laporan_operasional), '1970-01-01 00:00:00')
        ) AS update_terakhir
";

$result = $conn->query($sql);

if ($result && $row = $result->fetch_assoc()) {
    $data = [
        "total_sppg" => (int) $row["total_sppg"],
        "total_dana" => (float) $row["total_dana"],
        "total_omprengan" => (int) $row["total_omprengan"],
        "update_terakhir" => $row["update_terakhir"]
    ];
}

response(true, "Ringkasan publik berhasil diambil", $data);

?>
