<?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, phase_count FROM smart_meters");
$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$meters) {
    die("❌ No meters found in smart_meters table.");
}

$total_synced = 0;

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

    $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 or unsuccessful 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'];
    $temperature = $data['data']['temperature'] ?? null;
    $sync_batch_id = uniqid("sync_", true);
    $count = 0;

    // DEBUG: print_r($values);
    if (!is_array($values)) {
        echo "❌ No valid data for meter $device_sn\n";
        continue;
    }

    $insert = $conn->prepare("
        INSERT INTO smart_meter_readings 
        (meter_id, phase, voltage, current, power, energy_total, export_energy, frequency, power_factor, reading_timestamp, temperature, created_at, reading_source, sync_batch_id, flag, note)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), 'api', ?, 0, NULL)
    ");

    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;

        // Optional: you can log phase counts from DB vs. API
        // echo "Meter $device_sn phase $phase_num/$phase_count\n";

        // Insert (no limit to phase count)
        $check = $conn->prepare("SELECT COUNT(*) FROM smart_meter_readings 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,
            $voltage,
            $current,
            $power,
            $import_energy,
            $export_energy,
            $frequency,
            $power_factor,
            $timestamp,
            $temperature,
            $sync_batch_id
        ]);

        $count++;
    }

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

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