<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../config.php';
require_once __DIR__ . '/../../../db.php';
require_once __DIR__ . '/../../../includes/auth.php';
require_once __DIR__ . '/../../../includes/functions.php';
require_once __DIR__ . '/../../includes/bandwidth.php';

require_login();
$user = current_user();
$pdo  = db();

// Devices posicionados no mapa com tráfego agregado
$stmt = $pdo->prepare("
    SELECT d.*,
           COALESCE(SUM(ni.last_in_bps),  0) AS total_in_bps,
           COALESCE(SUM(ni.last_out_bps), 0) AS total_out_bps
    FROM nms_devices d
    LEFT JOIN nms_interfaces ni ON ni.device_id = d.id AND ni.monitored = TRUE
    WHERE d.user_id = ?
      AND d.map_lat IS NOT NULL
      AND d.map_lng IS NOT NULL
    GROUP BY d.id
    ORDER BY d.last_status ASC, d.name ASC
");
$stmt->execute([$user['id']]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$devices = array_map(fn($d) => [
    'id'       => (int)$d['id'],
    'name'     => $d['name'],
    'hostname' => $d['hostname'],
    'type'     => $d['type'],
    'location' => $d['location'] ?? '',
    'status'   => $d['last_status'] ?? 'unknown',
    'cpu'      => isset($d['last_cpu'])        ? (float)$d['last_cpu']        : null,
    'ram'      => isset($d['last_memory_pct']) ? (float)$d['last_memory_pct'] : null,
    'uptime'   => isset($d['uptime_seconds'])  ? (int)$d['uptime_seconds']    : null,
    'in_bps'   => (int)($d['total_in_bps']  ?? 0),
    'out_bps'  => (int)($d['total_out_bps'] ?? 0),
    'lat'      => (float)$d['map_lat'],
    'lng'      => (float)$d['map_lng'],
    'url'      => NMS_URL . '?page=nms_device_detail&id=' . (int)$d['id'],
    'edit_url' => NMS_URL . '?page=nms_device_form&id='   . (int)$d['id'],
], $rows);

// Totais (inclui devices sem coordenadas)
$totRow = $pdo->prepare("
    SELECT
        COUNT(*)                                                       AS total,
        COALESCE(SUM(CASE WHEN last_status='online'  THEN 1 END), 0) AS online,
        COALESCE(SUM(CASE WHEN last_status='offline' THEN 1 END), 0) AS offline
    FROM nms_devices WHERE user_id = ?
");
$totRow->execute([$user['id']]);
$tot = $totRow->fetch(PDO::FETCH_ASSOC);

echo json_encode([
    'devices'        => $devices,
    'total_devices'  => (int)$tot['total'],
    'total_on_map'   => count($devices),
    'total_online'   => (int)$tot['online'],
    'total_offline'  => (int)$tot['offline'],
    'ts'             => date('H:i:s'),
], JSON_UNESCAPED_UNICODE);
