<?php
// api/server_stats.php - Leitor de Recursos da VPS
require_once '../includes/db.php';
header('Content-Type: application/json');

// 1. DADOS DO BANCO (Canais e Clientes)
try {
    $proxy_count = $pdo->query("SELECT COUNT(*) FROM channels WHERE running = 1")->fetchColumn();
    $direct_count = $pdo->query("SELECT COUNT(*) FROM channels WHERE running = 0")->fetchColumn();
    $online_clients = $pdo->query("SELECT COUNT(*) FROM active_connections")->fetchColumn();
} catch (Exception $e) { $proxy_count = 0; $direct_count = 0; $online_clients = 0; }

// 2. USO DE MEMÓRIA RAM
// Lê o arquivo /proc/meminfo (Padrão Linux)
function getRamUsage() {
    $free = shell_exec('free -m');
    $free = (string)trim($free);
    $arr = explode("\n", $free);
    $mem = preg_split("/\s+/", $arr[1]);
    return [
        'total' => $mem[1], // MB
        'used' => $mem[2],  // MB
        'percent' => round(($mem[2] / $mem[1]) * 100, 1)
    ];
}
$ram = getRamUsage();

// 3. USO DE CPU
// Calcula baseada no Load Average e número de núcleos
function getCpuUsage() {
    $load = sys_getloadavg();
    $cores = 1;
    if (is_file('/proc/cpuinfo')) {
        $cpuinfo = file_get_contents('/proc/cpuinfo');
        preg_match_all('/^processor/m', $cpuinfo, $matches);
        $cores = count($matches[0]);
    }
    // Load de 1 minuto dividido pelos núcleos
    $percent = ($load[0] / $cores) * 100;
    if ($percent > 100) $percent = 100;
    return ['load' => $load[0], 'cores' => $cores, 'percent' => round($percent, 1)];
}
$cpu = getCpuUsage();

// 4. USO DE DISCO
$dt = disk_total_space('/');
$df = disk_free_space('/');
$du = $dt - $df;
$disk = [
    'total_gb' => round($dt / 1073741824, 2),
    'used_gb' => round($du / 1073741824, 2),
    'percent' => round(($du / $dt) * 100, 1)
];

// 5. VELOCIDADE DE INTERNET (Rede)
// Lê bytes recebidos (RX) e enviados (TX), espera 1 segundo e lê de novo para ver a diferença
function getNetworkSpeed() {
    // Tenta achar a interface principal (eth0, ens3, venet0...)
    $interface = 'eth0';
    $possible = glob('/sys/class/net/*');
    foreach ($possible as $p) {
        $name = basename($p);
        if ($name != 'lo') { $interface = $name; break; } // Pega a primeira que não for Loopback
    }

    $rx1 = @file_get_contents("/sys/class/net/$interface/statistics/rx_bytes");
    $tx1 = @file_get_contents("/sys/class/net/$interface/statistics/tx_bytes");
    
    sleep(1); // Pausa de 1 segundo para medir
    
    $rx2 = @file_get_contents("/sys/class/net/$interface/statistics/rx_bytes");
    $tx2 = @file_get_contents("/sys/class/net/$interface/statistics/tx_bytes");

    // Diferença em Bytes
    $rx_diff = $rx2 - $rx1;
    $tx_diff = $tx2 - $tx1;

    // Converte para Mbps (MegaBITS por segundo)
    // Bytes * 8 = Bits / 1024 / 1024 = Mbits
    $rx_mbps = round(($rx_diff * 8) / 1024 / 1024, 2);
    $tx_mbps = round(($tx_diff * 8) / 1024 / 1024, 2);

    return ['rx' => $rx_mbps, 'tx' => $tx_mbps, 'interface' => $interface];
}
$net = getNetworkSpeed();

// RETORNA TUDO
echo json_encode([
    'ram' => $ram,
    'cpu' => $cpu,
    'disk' => $disk,
    'net' => $net,
    'iptv' => [
        'proxy' => $proxy_count,
        'direct' => $direct_count,
        'clients' => $online_clients
    ]
]);
?>
