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

require_once __DIR__ . '/db_connect.php';
$api_token = RBE_IAMMETER_TOKEN;
$conn = $conn_rbe;

$stmt = $conn->query("SELECT id, serial FROM smart_meters");
$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$meters) {
    die("❌ No meters found.");
}

$total_synced = 0;

foreach ($meters as $meter) {
    $meter_id = $meter['id'];
    $device_sn = $meter['serial'];

    $api_url = "https://www.iammeter.com/api/v1/site/meterdata/$device_sn";
    $ch = curl_init($api_url);
    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 "❌ Failed to connect to IAMMETER for meter $device_sn (HTTP $httpcode)\n";
        continue;
    }

    $data = json_decode($response, true);
    if (!$data['successful'] || !isset($data['data']['values'])) {
        echo "❌ Invalid response for meter $device_sn\n";
        continue;
    }

    $timestamp_raw = $data['data']['localTime'] ?? '';
    $timestamp = date('Y-m-d H:i:s', strtotime($timestamp_raw));
    $values = $data['data']['values'];
    if (!is_array($values)) {
        echo "❌ No valid data for meter $device_sn\n";
        continue;
    }

    $insert = $conn->prepare("
        INSERT INTO smart_meter_readings_kva 
        (meter_id, phase, power, power_factor, reading_timestamp, created_at, sync_batch_id)
        VALUES (?, ?, ?, ?, ?, NOW(), ?)
    ");

    $sync_batch_id = uniqid("kva_", true);
    $count = 0;

    foreach ($values as $index => $phase) {
        if (!is_array($phase)) continue;

        [$voltage, $current, $power, $import_energy, $export_energy, $frequency, $power_factor] = $phase;
        $phase_num = $index + 1;

        // Check if already inserted for this timestamp and phase
        $check = $conn->prepare("SELECT COUNT(*) FROM smart_meter_readings_kva WHERE meter_id = ? AND phase = ? AND reading_timestamp = ?");
        $check->execute([$meter_id, $phase_num, $timestamp]);
        if ($check->fetchColumn() > 0) continue;

        $insert->execute([$meter_id, $phase_num, $power, $power_factor, $timestamp, $sync_batch_id]);
        $count++;
    }

    echo "✅ Synced $count reading(s) for meter $device_sn at $timestamp\n";
    $total_synced += $count;
}

echo "🎉 Total KVA readings synced: $total_synced\n";
?>
