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

/* 7 hari */
$labels = [];
$data   = [];

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

$today_total = 0;

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

    // Hari ini
    $sql = "
        SELECT COALESCE(SUM(pria+wanita+subuh+dzuhur+ashar+maghrib+isya+diluar_waktu_sholat),0) AS total
        FROM jamaah WHERE tanggal=?
    ";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('s',$today);
    $stmt->execute();
    $today_total = (int)$stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();

    // Trend 7 hari
    $start = date('Y-m-d', strtotime('-6 days'));
    $sql = "
        SELECT tanggal,
        COALESCE(SUM(pria+wanita+subuh+dzuhur+ashar+maghrib+isya+diluar_waktu_sholat),0) AS total
        FROM jamaah 
        WHERE tanggal BETWEEN ? AND ?
        GROUP BY tanggal
        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()) {
        $t = $r['tanggal'];
        if (isset($data[$t])) $data[$t] = (int)$r['total'];
    }
    $stmt->close();
}

echo json_encode([
    "today_total" => $today_total,
    "labels"      => $labels,
    "values"      => array_values($data)
]);
