<?php
// /api/admin/get_meter_logs.php
session_start();
require_once __DIR__ . '/../../core/db_connect.php';

header('Content-Type: application/json');

$serial = $_GET['serial'] ?? '';
$source = strtoupper($_GET['source'] ?? '');

if (!$serial || !$source) {
    echo json_encode([]);
    exit;
}

try {
    if ($source === "IAMMETER") {
        $stmt = $conn_rbe->prepare("
            SELECT * FROM smart_meter_readings
            WHERE serial_number = ?
            ORDER BY reading_timestamp DESC
            LIMIT 20
        ");
        $stmt->execute([$serial]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $logs = [];
        foreach ($rows as $r) {
            $logs[] = [
                'timestamp' => $r['reading_timestamp'],
                'total_kwh' => $r['energy_a'] + $r['energy_b'] + $r['energy_c'],
                'power_now' => $r['power_a'] + $r['power_b'] + $r['power_c'],
                'phases' => [
                    'a' => $r['power_a'],
                    'b' => $r['power_b'],
                    'c' => $r['power_c']
                ]
            ];
        }
    }

    if ($source === "FLECTO") {
        $stmt = $conn_rbe->prepare("
            SELECT * FROM flecto_meter_readings
            WHERE serial_number = ?
            ORDER BY fetched_at DESC
            LIMIT 20
        ");
        $stmt->execute([$serial]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $logs = [];
        foreach ($rows as $r) {
            $total = $r['reg_a'] + $r['reg_e'] + $r['reg_f'] +
                     $r['reg_h'] + $r['reg_l'];

            $logs[] = [
                'timestamp' => $r['fetched_at'],
                'total_kwh' => $total,
                'active_power' => $r['active_power']
            ];
        }
    }

    if ($source === "WATER") {
        $stmt = $conn_rbe->prepare("
            SELECT * FROM water_meter_readings
            WHERE serial_number = ?
            ORDER BY created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$serial]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $logs = [];
        foreach ($rows as $r) {
            $logs[] = [
                'timestamp' => $r['created_at'],
                'total_kl' => $r['total_liters'] / 1000,
                'flow_lpm' => $r['flow_rate']
            ];
        }
    }

    echo json_encode($logs, JSON_PRETTY_PRINT);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
