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

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

$today = date("Y-m-d");

// =============================================
// HARI INI — ambil dari log_air baru
// =============================================
$sql_today = "
    SELECT status_air, COALESCE(SUM(update_air),0) AS total
    FROM log_air
    WHERE tanggal = ?
    GROUP BY status_air
";
$stmt = $koneksi->prepare($sql_today);
$stmt->bind_param("s", $today);
$stmt->execute();
$resToday = $stmt->get_result();

$today_usage  = 0; // keluar
$today_income = 0; // masuk

while ($row = $resToday->fetch_assoc()) {
    $status = strtolower($row['status_air']);
    $t = (float)$row['total'];

    if ($status === "keluar") $today_usage  = $t;
    if ($status === "masuk")  $today_income = $t;
}

$stmt->close();


// =============================================
// 7 HARI — total masuk & keluar
// =============================================
$labels = [];
$usage  = [];
$income = [];

for ($i = 6; $i >= 0; $i--) {
    $tgl = date("Y-m-d", strtotime("-$i days"));
    $labels[] = date("d M", strtotime($tgl));

    $usage[$tgl]  = 0;
    $income[$tgl] = 0;

    $q = $koneksi->prepare("
        SELECT status_air, COALESCE(SUM(update_air),0) AS total
        FROM log_air
        WHERE tanggal = ?
        GROUP BY status_air
    ");
    $q->bind_param("s", $tgl);
    $q->execute();
    $r = $q->get_result();

    while ($row = $r->fetch_assoc()) {
        $status = strtolower($row['status_air']);
        $t = (float)$row['total'];

        if ($status === "keluar") $usage[$tgl]  = $t;
        if ($status === "masuk")  $income[$tgl] = $t;
    }

    $q->close();
}

echo json_encode([
    "today_usage"  => $today_usage,
    "today_income" => $today_income,
    "labels"       => $labels,
    "last7_usage"  => array_values($usage),
    "last7_income" => array_values($income)
]);
