<?php
// Flecto TL300 Electric Meter Sync Script

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';

try {
    $pdo = new PDO(DB_DSN, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Fetch latest bearer token
$stmt = $pdo->query("SELECT token FROM flecto_tokens ORDER BY created_at DESC LIMIT 1");
$token = $stmt->fetchColumn();

if (!$token) {
    die("No bearer token found.");
}

// Build API URL
$baseUrl = RBE_FLECTO_ELECTRIC_API_URL;
$url = $baseUrl . '?bearer=' . urlencode($token) . '&last=30';

// Make request
$response = file_get_contents($url);
if ($response === false) {
    die("Failed to fetch data from Flecto API.");
}

$data = json_decode($response, true);
if (!is_array($data)) {
    die("Invalid JSON response.");
}

// Insert readings (store all pulls)
$insert = $pdo->prepare("INSERT IGNORE INTO flecto_meter_readings (
    serial, reg_a, reg_b, reg_c, reg_d, reg_e, reg_f, reg_g, reg_h, reg_i, reg_j, reg_k, reg_l, reg_m, reg_n, reg_o,
    log, rtc, created_at
) VALUES (
    :serial, :reg_a, :reg_b, :reg_c, :reg_d, :reg_e, :reg_f, :reg_g, :reg_h, :reg_i, :reg_j, :reg_k, :reg_l, :reg_m, :reg_n, :reg_o,
    :log, :rtc, :created_at
)");

$inserted = 0;
$skipped = 0;

foreach ($data as $row) {
    $result = $insert->execute([
        ':serial' => $row['serial'] ?? null,
        ':reg_a' => $row['reg_A'] ?? null,
        ':reg_b' => $row['reg_B'] ?? null,
        ':reg_c' => $row['reg_C'] ?? null,
        ':reg_d' => $row['reg_D'] ?? null,
        ':reg_e' => $row['reg_E'] ?? null,
        ':reg_f' => $row['reg_F'] ?? null,
        ':reg_g' => $row['reg_G'] ?? null,
        ':reg_h' => $row['reg_H'] ?? null,
        ':reg_i' => $row['reg_I'] ?? null,
        ':reg_j' => $row['reg_J'] ?? null,
        ':reg_k' => $row['reg_K'] ?? null,
        ':reg_l' => $row['reg_L'] ?? null,
        ':reg_m' => $row['reg_M'] ?? null,
        ':reg_n' => $row['reg_N'] ?? null,
        ':reg_o' => $row['reg_O'] ?? null,
        ':log' => $row['log'] ?? null,
        ':rtc' => $row['rtc'] ?? null,
        ':created_at' => $row['created_at'] ?? null
    ]);

    if ($insert->rowCount() > 0) {
        $inserted++;
    } else {
        $skipped++;
    }
}

// Optional logging
file_put_contents(
    __DIR__ . '/flecto_sync.log',
    "Imported $inserted | Skipped $skipped at " . date('Y-m-d H:i:s') . "\n",
    FILE_APPEND
);

echo "Imported $inserted new Flecto readings. Skipped $skipped duplicates.\n";
