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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

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

if (!$serial || !$source) {
    echo json_encode(['error' => 'Missing params']);
    exit;
}

try {
    // -------------------------
    // BASIC METER INFO (shared)
    // -------------------------
    if ($source === "IAMMETER") {
        $stmt = $conn_rbe->prepare("
            SELECT m.serial_number AS serial, 
                   m.property_id,
                   p.property_number AS property_name,
                   t.fullname AS tenant_name,
                   u.fullname AS landlord_name
            FROM smart_meters m
            LEFT JOIN properties p ON m.property_id = p.id
            LEFT JOIN tenants t ON p.tenant_id = t.id
            LEFT JOIN rbe_users u ON p.landlord_id = u.id
            WHERE m.serial_number = ?
            LIMIT 1
        ");
    }
    elseif ($source === "FLECTO") {
        $stmt = $conn_rbe->prepare("
            SELECT m.serial_number AS serial, 
                   m.property_id,
                   p.property_number AS property_name,
                   t.fullname AS tenant_name,
                   u.fullname AS landlord_name
            FROM flecto_meters m
            LEFT JOIN properties p ON m.property_id = p.id
            LEFT JOIN tenants t ON p.tenant_id = t.id
            LEFT JOIN rbe_users u ON p.landlord_id = u.id
            WHERE m.serial_number = ?
            LIMIT 1
        ");
    }
    elseif ($source === "WATER") {
        $stmt = $conn_rbe->prepare("
            SELECT m.serial_number AS serial, 
                   m.property_id,
                   p.property_number AS property_name,
                   t.fullname AS tenant_name,
                   u.fullname AS landlord_name
            FROM water_meters m
            LEFT JOIN properties p ON m.property_id = p.id
            LEFT JOIN tenants t ON p.tenant_id = t.id
            LEFT JOIN rbe_users u ON p.landlord_id = u.id
            WHERE m.serial_number = ?
            LIMIT 1
        ");
    }

    $stmt->execute([$serial]);
    $meta = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$meta) {
        echo json_encode(['error' => 'Meter not found']);
        exit;
    }

    // -------------------------
    // FETCH LAST READING (smart formatted)
    // -------------------------
    if ($source === "IAMMETER") {
        $reading = $conn_rbe->prepare("
            SELECT * FROM smart_meter_readings
            WHERE serial_number = ?
            ORDER BY reading_timestamp DESC
            LIMIT 1
        ");
        $reading->execute([$serial]);
        $row = $reading->fetch(PDO::FETCH_ASSOC);

        $meta['last_sync'] = $row['reading_timestamp'] ?? null;

        if ($row) {
            $meta['readings'] = [
                'timestamp' => $row['reading_timestamp'],
                'phase_a' => [
                    'voltage' => $row['voltage_a'],
                    'current' => $row['current_a'],
                    'power' => $row['power_a'],
                    'kwh' => $row['energy_a']
                ],
                'phase_b' => [
                    'voltage' => $row['voltage_b'],
                    'current' => $row['current_b'],
                    'power' => $row['power_b'],
                    'kwh' => $row['energy_b']
                ],
                'phase_c' => [
                    'voltage' => $row['voltage_c'],
                    'current' => $row['current_c'],
                    'power' => $row['power_c'],
                    'kwh' => $row['energy_c']
                ],
                'total_kwh' => $row['energy_a'] + $row['energy_b'] + $row['energy_c'],
                'power_now' => $row['power_a'] + $row['power_b'] + $row['power_c']
            ];
        }
    }

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

        $meta['last_sync'] = $row['fetched_at'] ?? null;

        if ($row) {
            $total = $row['reg_a'] + $row['reg_e'] + $row['reg_f'] +
                     $row['reg_h'] + $row['reg_l'];

            $meta['readings'] = [
                'timestamp' => $row['fetched_at'],
                'registers' => [
                    'reg_a' => $row['reg_a'],
                    'reg_e' => $row['reg_e'],
                    'reg_f' => $row['reg_f'],
                    'reg_h' => $row['reg_h'],
                    'reg_l' => $row['reg_l']
                ],
                'total_kwh' => $total,
                'voltage' => $row['voltage'] ?? null,
                'current' => $row['current'] ?? null,
                'active_power' => $row['active_power'] ?? null
            ];
        }
    }

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

        $meta['last_sync'] = $row['created_at'] ?? null;

        if ($row) {
            $meta['readings'] = [
                'timestamp' => $row['created_at'],
                'flow_lpm' => $row['flow_rate'],
                'total_liters' => $row['total_liters'],
                'total_kl' => $row['total_liters'] / 1000,
                'pressure' => $row['pressure']
            ];
        }
    }

    echo json_encode($meta, JSON_PRETTY_PRINT);

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