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

$sppg_id = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;

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

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

$sql = "
    SELECT
        COALESCE(SUM(CASE WHEN jenis = 'Pemasukan' THEN jumlah ELSE 0 END), 0) AS total_pemasukan,
        COALESCE(SUM(CASE WHEN jenis = 'Pengeluaran' THEN jumlah ELSE 0 END), 0) AS total_pengeluaran,
        COUNT(*) AS total_transaksi
    FROM transaksi
    $where
";

$stmt = $conn->prepare($sql);

if ($sppg_id > 0) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();

$result = $stmt->get_result();
$row = $result->fetch_assoc();

$totalPemasukan = (int) $row["total_pemasukan"];
$totalPengeluaran = (int) $row["total_pengeluaran"];
$sisaDana = $totalPemasukan - $totalPengeluaran;

response(true, "Ringkasan transaksi berhasil diambil", [
    "total_pemasukan" => $totalPemasukan,
    "total_pengeluaran" => $totalPengeluaran,
    "sisa_dana" => $sisaDana,
    "total_transaksi" => (int) $row["total_transaksi"]
]);

?>