<?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();
$deviceId = (int)($_GET['device_id'] ?? 0);
if (!$deviceId) { echo json_encode(['error' => 'device_id required']); exit; }

// Verifica ownership
$dev = $pdo->prepare("SELECT id FROM nms_devices WHERE id=? AND user_id=?");
$dev->execute([$deviceId, $user['id']]);
if (!$dev->fetch()) { http_response_code(403); echo json_encode(['error' => 'forbidden']); exit; }

$stmt = $pdo->prepare("
    SELECT if_name, if_alias, last_status, last_in_bps, last_out_bps, if_speed_bps, last_polled_at
    FROM nms_interfaces
    WHERE device_id = ? AND monitored = 1
    ORDER BY (COALESCE(last_in_bps,0)+COALESCE(last_out_bps,0)) DESC
    LIMIT 50
");
$stmt->execute([$deviceId]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$result = array_map(fn($r) => [
    'name'     => $r['if_name'],
    'alias'    => $r['if_alias'],
    'status'   => $r['last_status'],
    'in_bps'   => (int)($r['last_in_bps']  ?? 0),
    'out_bps'  => (int)($r['last_out_bps'] ?? 0),
    'in_fmt'   => format_bps((int)($r['last_in_bps']  ?? 0)),
    'out_fmt'  => format_bps((int)($r['last_out_bps'] ?? 0)),
    'speed_bps'=> (int)($r['if_speed_bps'] ?? 0),
    'polled'   => $r['last_polled_at'],
], $rows);

echo json_encode(['interfaces' => $result, 'ts' => date('H:i:s')]);
