<?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 t.sppg_id = ?";
    $params[] = $sppg_id;
    $types .= "i";
}

$sql = "
    SELECT
        t.id,
        t.sppg_id,
        s.nama AS sppg_nama,
        t.tanggal,
        t.kategori,
        t.deskripsi,
        t.supplier,
        t.jenis,
        t.jumlah,
        t.created_at
    FROM transaksi t
    LEFT JOIN sppg s ON s.id = t.sppg_id
    $where
    ORDER BY t.tanggal DESC, t.id DESC
";

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

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

$stmt->execute();

$result = $stmt->get_result();

$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

response(true, "Data transaksi berhasil diambil", $data);

?>