<?php
// water_meter_sync.php
// Flecto Sense Water Meter Integration (Demo Mode, v4.3 — new key map)

// Enable debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// --- CONFIG LOADER ---
require_once 'config.php';

// --- DB SETUP ---
try {
    $pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME", $DB_USER, $DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("DB Connection failed: " . $e->getMessage());
}

// --- FLAGS ---
$CREATE_TABLE = false;
$TRUNCATE_TABLE = false;
$FETCH_DATA = true;
$DEBUG_MODE = true;
$BEARER_TOKEN = RBE_FLECTO_WATER_TOKEN;

// --- TABLE NAME ---
$table = "water_meter_readings";

if ($CREATE_TABLE) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS $table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        serial_number VARCHAR(64),
        reading_datetime DATETIME,
        volume_liters INT,
        burst INT,
        leak INT,
        dry INT,
        tamper INT,
        rssi INT,
        concentrator_id VARCHAR(64),
        description VARCHAR(64),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB;");
    echo "✅ Table created.\n";
    exit;
}

if ($TRUNCATE_TABLE) {
    $pdo->exec("TRUNCATE TABLE $table");
    echo "⚠️ Table truncated.\n";
}

if ($FETCH_DATA) {
    $url = RBE_FLECTO_WATER_API_URL . "?bearer=" . urlencode($BEARER_TOKEN) . "&report=1&pack=1";
    $response = file_get_contents($url);
    $data = json_decode($response, true);

    if (!is_array($data)) {
        echo "❌ Invalid JSON or empty response.\n";
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO $table
        (serial_number, reading_datetime, volume_liters, burst, leak, dry, tamper, rssi, concentrator_id, description)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $count = 0;
    foreach ($data as $entry) {
        $serial     = $entry['msn']    ?? null;
        $datetime   = $entry['ts']     ?? null;
        $volume     = $entry['vol']    ?? null;
        $burst      = $entry['b']      ?? 0;
        $leak       = $entry['l']      ?? 0;
        $dry        = $entry['d']      ?? 0;
        $tamper     = $entry['t']      ?? 0;
        $rssi       = $entry['rssi']   ?? 0;
        $concentrator = $entry['cid']  ?? '';
        $desc       = $entry['desc']   ?? '';

        if (!$serial || !$datetime || $volume === null) continue; // skip invalid rows

        $stmt->execute([
            $serial,
            $datetime,
            (int)$volume,
            (int)$burst,
            (int)$leak,
            (int)$dry,
            (int)$tamper,
            (int)$rssi,
            $concentrator,
            $desc
        ]);
        $count++;
    }

    echo "✅ Imported $count water meter readings.\n";
    if ($DEBUG_MODE && $count > 0) echo print_r($data[0], true);
} 
