<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once 'db_connect.php';

$meter_id = intval($_GET['meter_id'] ?? 0);
if (!$meter_id) {
    echo json_encode(["error" => "Missing meter_id"]);
    exit;
}

$stmt = $conn_power->prepare("SELECT 
    DATE_FORMAT(reading_timestamp, '%Y-%m') AS month,
    MAX(energy_total) - MIN(energy_total) AS energy_kwh
FROM smart_meter_readings
WHERE meter_id = ? AND phase = 1
  AND reading_timestamp >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
GROUP BY month
ORDER BY month ASC");

$stmt->execute([$meter_id]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

$labels = [];
$values = [];
foreach ($results as $row) {
    $labels[] = $row['month'];
    $values[] = round($row['energy_kwh'], 2);
}

echo json_encode([
    'labels' => $labels,
    'values' => $values
]);
