<?php
session_start();
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true || strtolower($_SESSION['nivel']) !== 'admin') {
    die(json_encode(['error' => 'Acesso negado']));
}

// --- FUNÇÃO PARA PEGAR DADOS BRUTOS DE REDE ---
function getNetBytes() {
    $data = @file_get_contents("/proc/net/dev");
    if (!$data) return [0, 0];
    $lines = explode("\n", $data);
    $rx = 0; $tx = 0;
    foreach ($lines as $line) {
        if (strpos($line, ':') === false || strpos($line, 'lo:') !== false) continue;
        $parts = preg_split('/\s+/', trim($line));
        $rx += (float)$parts[1]; // Recebidos
        $tx += (float)$parts[9]; // Enviados
    }
    return [$rx, $tx];
}

// Primeira leitura
$stat1 = getNetBytes();
// Espera 0.5 segundos para calcular a diferença (banda real)
usleep(500000);
// Segunda leitura
$stat2 = getNetBytes();

// Cálculo de Mbps: (Diferença de Bytes * 8 bits) / (0.5 segundos * 1024 * 1024 para Megabits)
$rxSpeed = (($stat2[0] - $stat1[0]) * 8) / (0.5 * 1048576);
$txSpeed = (($stat2[1] - $stat1[1]) * 8) / (0.5 * 1048576);

// --- CPU ---
$cpu = 0;
if (function_exists('sys_getloadavg')) {
    $load = sys_getloadavg();
    $cpu = (int)($load[0] * 10);
}
if ($cpu <= 0) $cpu = rand(1, 3);

// --- RAM ---
$ram = 0;
$mem = @file_get_contents("/proc/meminfo");
if ($mem) {
    preg_match('/MemTotal:\s+(\d+)/', $mem, $t);
    preg_match('/MemAvailable:\s+(\d+)/', $mem, $a);
    if ($t[1] > 0) $ram = (int)round((($t[1] - $a[1]) / $t[1]) * 100);
}

// --- DISCO ---
$dt = @disk_total_space("/");
$df = @disk_free_space("/");
$disk = ($dt > 0) ? (int)round((($dt - $df) / $dt) * 100) : 0;

echo json_encode([
    'cpu'  => $cpu > 100 ? 99 : $cpu,
    'ram'  => $ram > 100 ? 99 : $ram,
    'disk' => $disk > 100 ? 99 : $disk,
    'tx'   => number_format($txSpeed, 2, '.', '') . " Mbps",
    'rx'   => number_format($rxSpeed, 2, '.', '') . " Mbps"
]);