<?php
// GET /api/dashboard
// Query params:
//   ?compare=date&date=2026-04-07          → compare that date vs previous date
//   ?compare=month&month=04&year=2026      → compare that month vs previous month
//   (no params)                            → default week vs last week

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

$db      = getDB();
$compare = $_GET['compare'] ?? 'week'; // week | date | month

// ─── TOTAL READINGS ──────────────────────────────────────────
$total = $db->query("SELECT COUNT(*) AS cnt FROM meter_readings")->fetch_assoc()['cnt'];

// ─── WEEKLY GRAPH (last 7 days) ───────────────────────────────
$stmt = $db->prepare("
    SELECT DATE_FORMAT(reading_date, '%a') AS day, COUNT(*) AS count
    FROM meter_readings
    WHERE reading_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY reading_date
    ORDER BY reading_date ASC
");
$stmt->execute();
$weeklyRaw = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$days = [];
for ($i = 6; $i >= 0; $i--) {
    $days[date('D', strtotime("-$i days"))] = 0;
}
foreach ($weeklyRaw as $row) {
    $days[$row['day']] = (int)$row['count'];
}
$weeklyGraph = [];
foreach ($days as $day => $count) {
    $weeklyGraph[] = ['day' => $day, 'count' => $count];
}

// ─── MONTHLY GRAPH (12 months of selected year) ──────────────
$graphYear = (int)($_GET['year'] ?? date('Y'));

$stmt = $db->prepare("
    SELECT MONTH(reading_date) AS month, COUNT(*) AS count
    FROM meter_readings
    WHERE YEAR(reading_date) = ?
    GROUP BY MONTH(reading_date)
    ORDER BY MONTH(reading_date) ASC
");
$stmt->bind_param("i", $graphYear);
$stmt->execute();
$monthlyRaw = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$monthlyGraph = [];
foreach ($monthlyRaw as $row) {
    $monthlyGraph[] = [
        'month' => date('M', mktime(0, 0, 0, (int)$row['month'], 1)),
        'count' => (int)$row['count'],
    ];
}

// ─── COMPARISON ──────────────────────────────────────────────
$current = 0;
$previous = 0;
$label_current  = '';
$label_previous = '';

if ($compare === 'date') {
    $date          = $_GET['date'] ?? date('Y-m-d');
    $prevDate      = date('Y-m-d', strtotime($date . ' -1 day'));
    $label_current  = $date;
    $label_previous = $prevDate;

    $stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE reading_date = ?");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $current = (int)$stmt->get_result()->fetch_assoc()['cnt'];
    $stmt->close();

    $stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE reading_date = ?");
    $stmt->bind_param("s", $prevDate);
    $stmt->execute();
    $previous = (int)$stmt->get_result()->fetch_assoc()['cnt'];
    $stmt->close();

} elseif ($compare === 'month') {
    $month = (int)($_GET['month'] ?? date('m'));
    $year  = (int)($_GET['year']  ?? date('Y'));

    // Previous month
    $prevMonth = $month === 1 ? 12 : $month - 1;
    $prevYear  = $month === 1 ? $year - 1 : $year;

    $label_current  = date('F Y', mktime(0, 0, 0, $month, 1, $year));
    $label_previous = date('F Y', mktime(0, 0, 0, $prevMonth, 1, $prevYear));

    $stmt = $db->prepare("
        SELECT COUNT(*) AS cnt FROM meter_readings
        WHERE MONTH(reading_date) = ? AND YEAR(reading_date) = ?
    ");
    $stmt->bind_param("ii", $month, $year);
    $stmt->execute();
    $current = (int)$stmt->get_result()->fetch_assoc()['cnt'];
    $stmt->close();

    $stmt = $db->prepare("
        SELECT COUNT(*) AS cnt FROM meter_readings
        WHERE MONTH(reading_date) = ? AND YEAR(reading_date) = ?
    ");
    $stmt->bind_param("ii", $prevMonth, $prevYear);
    $stmt->execute();
    $previous = (int)$stmt->get_result()->fetch_assoc()['cnt'];
    $stmt->close();

} else {
    // Default: this week vs last week
    $label_current  = 'This Week';
    $label_previous = 'Last Week';

    $current = (int)$db->query("
        SELECT COUNT(*) AS cnt FROM meter_readings
        WHERE reading_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    ")->fetch_assoc()['cnt'];

    $previous = (int)$db->query("
        SELECT COUNT(*) AS cnt FROM meter_readings
        WHERE reading_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 13 DAY) AND DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    ")->fetch_assoc()['cnt'];
}

// ─── DAY COMPARISON (today vs yesterday) ─────────────────────
$today     = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));

$stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE reading_date = ?");
$stmt->bind_param("s", $today);
$stmt->execute();
$dayCurrentCount = (int)$stmt->get_result()->fetch_assoc()['cnt'];
$stmt->close();

$stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE reading_date = ?");
$stmt->bind_param("s", $yesterday);
$stmt->execute();
$dayPreviousCount = (int)$stmt->get_result()->fetch_assoc()['cnt'];
$stmt->close();

$dayIncrease = 0; $dayDecrease = 0;
if ($dayPreviousCount > 0) {
    $dayDiff = $dayCurrentCount - $dayPreviousCount;
    if ($dayDiff > 0) $dayIncrease = round(($dayDiff / $dayPreviousCount) * 100, 1);
    if ($dayDiff < 0) $dayDecrease = round((abs($dayDiff) / $dayPreviousCount) * 100, 1);
}

// ─── MONTH COMPARISON (this month vs last month) ──────────────
$thisMonth  = (int)date('m');
$thisYear   = (int)date('Y');
$lastMonth  = $thisMonth === 1 ? 12 : $thisMonth - 1;
$lastYear   = $thisMonth === 1 ? $thisYear - 1 : $thisYear;

$stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE MONTH(reading_date) = ? AND YEAR(reading_date) = ?");
$stmt->bind_param("ii", $thisMonth, $thisYear);
$stmt->execute();
$monthCurrentCount = (int)$stmt->get_result()->fetch_assoc()['cnt'];
$stmt->close();

$stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM meter_readings WHERE MONTH(reading_date) = ? AND YEAR(reading_date) = ?");
$stmt->bind_param("ii", $lastMonth, $lastYear);
$stmt->execute();
$monthPreviousCount = (int)$stmt->get_result()->fetch_assoc()['cnt'];
$stmt->close();

$monthIncrease = 0; $monthDecrease = 0;
if ($monthPreviousCount > 0) {
    $monthDiff = $monthCurrentCount - $monthPreviousCount;
    if ($monthDiff > 0) $monthIncrease = round(($monthDiff / $monthPreviousCount) * 100, 1);
    if ($monthDiff < 0) $monthDecrease = round((abs($monthDiff) / $monthPreviousCount) * 100, 1);
}

$db->close();

$increase = 0;
$decrease = 0;
if ($previous > 0) {
    $diff = $current - $previous;
    if ($diff > 0) $increase = round(($diff / $previous) * 100, 1);
    if ($diff < 0) $decrease = round((abs($diff) / $previous) * 100, 1);
}

sendSuccess([
    'data' => [
        'total_readings' => (int)$total,
        'weekly_graph'   => $weeklyGraph,
        'monthly_graph'  => $monthlyGraph,
        'week_comparison'     => [
            'type'                => $compare,
            'current_label'       => $label_current,
            'current_count'       => $current,
            'previous_label'      => $label_previous,
            'previous_count'      => $previous,
            'increase_percentage' => $increase,
            'decrease_percentage' => $decrease,
        ],
        'day_comparison' => [
            'current_label'       => $today,
            'current_count'       => $dayCurrentCount,
            'previous_label'      => $yesterday,
            'previous_count'      => $dayPreviousCount,
            'increase_percentage' => $dayIncrease,
            'decrease_percentage' => $dayDecrease,
        ],
        'month_comparison' => [
            'current_label'       => date('F Y', mktime(0, 0, 0, $thisMonth, 1, $thisYear)),
            'current_count'       => $monthCurrentCount,
            'previous_label'      => date('F Y', mktime(0, 0, 0, $lastMonth, 1, $lastYear)),
            'previous_count'      => $monthPreviousCount,
            'increase_percentage' => $monthIncrease,
            'decrease_percentage' => $monthDecrease,
        ],
    ],
]);
