<?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();

$ifaceId = (int)($_GET['interface_id'] ?? 0);
$period  = $_GET['period'] ?? '1h';

if (!$ifaceId) { echo json_encode(['error' => 'interface_id required']); exit; }

// Verifica ownership via join
$own = $pdo->prepare("SELECT ni.id FROM nms_interfaces ni JOIN nms_devices nd ON nd.id=ni.device_id WHERE ni.id=? AND nd.user_id=?");
$own->execute([$ifaceId, $user['id']]);
if (!$own->fetch()) { http_response_code(403); echo json_encode(['error'=>'forbidden']); exit; }

$intervals = ['5min' => ["INTERVAL '5 minutes'", 'H:i'], '1h' => ["INTERVAL '1 hour'", 'H:i'], '24h' => ["INTERVAL '24 hours'", 'd/m H:i']];
[$interval, $fmt] = $intervals[$period] ?? $intervals['1h'];

$stmt = $pdo->prepare("SELECT in_bps, out_bps, recorded_at FROM nms_bandwidth_history WHERE interface_id=? AND recorded_at >= NOW() - {$interval} ORDER BY recorded_at ASC LIMIT 1440");
$stmt->execute([$ifaceId]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Filtra leituras impossíveis (primeiros polls com delta enorme do contador acumulado)
$MAX_BPS = 400_000_000_000; // 400 Gbps
$labels  = [];
$in_bps  = [];
$out_bps = [];
foreach ($rows as $r) {
    $in  = (int)$r['in_bps'];
    $out = (int)$r['out_bps'];
    if ($in > $MAX_BPS || $out > $MAX_BPS) continue; // descarta outlier
    $labels[]  = (new DateTimeImmutable($r['recorded_at']))->format($fmt);
    $in_bps[]  = $in;
    $out_bps[] = $out;
}

echo json_encode(compact('labels', 'in_bps', 'out_bps'));
