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

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

$stmt = $conn->prepare("
  SELECT phase, power, reading_timestamp 
  FROM smart_meter_readings 
  WHERE meter_id = ? 
    AND reading_timestamp >= NOW() - INTERVAL 24 HOUR
  ORDER BY reading_timestamp ASC
");
$stmt->execute([$meter_id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$data = [1 => [], 2 => [], 3 => [], 'labels' => []];

foreach ($rows as $row) {
    $phase = $row['phase'];
    $power = floatval($row['power']);
    $time = date('H:i', strtotime($row['reading_timestamp']));
    if (!in_array($time, $data['labels'])) {
        $data['labels'][] = $time;
    }
    $data[$phase][] = $power;
}

echo json_encode($data);
