<?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');

$labels = [];
$usage  = [];
$income = [];

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

$today_usage  = 0;
$today_income = 0;

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

    $start = date('Y-m-d', strtotime('-6 days'));

    $sql = "
        SELECT tanggal, status_air, COALESCE(SUM(update_air),0) AS total
        FROM log_air
        WHERE tanggal BETWEEN ? AND ?
        GROUP BY tanggal, status_air
        ORDER BY tanggal ASC
    ";

    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('ss', $start, $today);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($r = $res->fetch_assoc()) {
        $tgl = $r['tanggal'];
        $status = strtolower($r['status_air']);
        $total = (float)$r['total'];

        if ($status === 'keluar') {
            $usage[$tgl] = $total;
        } elseif ($status === 'masuk') {
            $income[$tgl] = $total;
        }
    }

    // Today
    $today_usage  = $usage[$today] ?? 0;
    $today_income = $income[$today] ?? 0;
}

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