<?php
header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Jakarta');

require_once __DIR__ . '/../../../app/config/koneksi.php';
require_once __DIR__ . '/../../../app/helpers/helpers.php';

function tableExists($conn, $table) {
    $t = $conn->real_escape_string($table);
    $q = $conn->query("SHOW TABLES LIKE '$t'");
    return ($q && $q->num_rows > 0);
}

$today = date('Y-m-d');
$pemasukan_today = 0;
$pemasukan_month = 0;

if (tableExists($koneksi,'keuangan')) {

    // Hari ini
    $sql = "
        SELECT COALESCE(SUM(pemasukan),0) AS total
        FROM keuangan 
        WHERE DATE(tanggal)=?
    ";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('s',$today);
    $stmt->execute();
    $pemasukan_today = (float)$stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();

    // Bulan ini
    $m = date('m');
    $y = date('Y');
    $sql = "
        SELECT COALESCE(SUM(pemasukan),0) AS total
        FROM keuangan
        WHERE MONTH(tanggal)=? AND YEAR(tanggal)=?
    ";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('ii',$m,$y);
    $stmt->execute();
    $pemasukan_month = (float)$stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();
}

echo json_encode([
    "today_income" => $pemasukan_today,
    "month_income" => $pemasukan_month
]);
