<?php
ob_start();

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    ob_end_clean();
    exit(0);
}

header('Content-Type: application/json; charset=utf-8');

include "koneksi.php";

if (!isset($koneksi) && isset($conn)) {
    $koneksi = $conn; 
}

$raw_data = file_get_contents("php://input");
$data = json_decode($raw_data, true);

$bulan = isset($data['bulan']) ? intval($data['bulan']) : date('m');
$tahun = isset($data['tahun']) ? intval($data['tahun']) : date('Y');

// Ambil SELURUH riwayat kas keluar (Biaya & Tagihan)
$sql = "SELECT * FROM kas_keluar 
        WHERE MONTH(tgl_transaksi) = '$bulan' 
        AND YEAR(tgl_transaksi) = '$tahun'
        ORDER BY tgl_transaksi DESC, id DESC";

$query = mysqli_query($koneksi, $sql);
$list = [];

if ($query) {
    while ($row = mysqli_fetch_assoc($query)) {
        $list[] = $row;
    }
    ob_end_clean();
    echo json_encode([
        "status" => "success",
        "data" => $list
    ]);
} else {
    ob_end_clean();
    echo json_encode([
        "status" => "error",
        "message" => mysqli_error($koneksi)
    ]);
}
?>