<?php
header('Content-Type: application/json');
require_once __DIR__ . "/../../../app/config/koneksi.php";
date_default_timezone_set('Asia/Jakarta');

// ======================================
// Saldo Mingguan — 7 hari terakhir
// ======================================
$today = date('Y-m-d');
$weekAgo = date('Y-m-d', strtotime("-6 days")); // total 7 hari

$qWeekly = mysqli_query($koneksi,
    "SELECT SUM(pemasukan - pengeluaran) AS saldo
     FROM keuangan
     WHERE tanggal BETWEEN '$weekAgo' AND '$today'"
);
$weekly = mysqli_fetch_assoc($qWeekly);

$saldo_mingguan = (float)($weekly['saldo'] ?? 0);

// ======================================
// Saldo Bulanan — bulan berjalan
// ======================================
$bulan = date('m');
$tahun = date('Y');

$qMonthly = mysqli_query($koneksi,
    "SELECT SUM(pemasukan - pengeluaran) AS saldo
     FROM keuangan
     WHERE MONTH(tanggal) = '$bulan'
       AND YEAR(tanggal) = '$tahun'"
);
$monthly = mysqli_fetch_assoc($qMonthly);

$saldo_bulanan = (float)($monthly['saldo'] ?? 0);

// ======================================
// Output JSON
// ======================================
echo json_encode([
    "mingguan" => ["saldo" => $saldo_mingguan],
    "bulanan"  => ["saldo" => $saldo_bulanan]
]);
