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

$api_token = RBE_IAMMETER_TOKEN;
$device_sn = $_GET['sn'] ?? '86139380';

if (!$device_sn) {
    echo json_encode(["error" => "Missing SN"]);
    exit;
}

$endpoint = "http://open.iammeter.com/api/v1/site/energydata/$device_sn?type=1&period=4"; 

$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "token: $api_token"
]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpcode !== 200 || !$response) {
    echo json_encode(["error" => "Failed to fetch IAMMETER API", "http" => $httpcode]);
    exit;
}

$data = json_decode($response, true);

if (!$data['successful'] || !isset($data['data']['labels'])) {
    echo json_encode(["error" => "Invalid response from IAMMETER"]);
    exit;
}

$labels = $data['data']['labels'] ?? [];
$datasets = $data['data']['datasets'][0]['data'] ?? []; // Assuming only 1 dataset (import energy)

$results = [
    'labels' => $labels,
    'values' => array_map('floatval', $datasets)
];

echo json_encode($results);
