<?php
session_start();
// Forçar saída limpa sem avisos do PHP que quebram o JSON
error_reporting(0);
ini_set('display_errors', 0);

// Trava de Segurança
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true || strtolower($_SESSION['nivel']) !== 'admin') {
    header('Content-Type: application/json; charset=utf-8');
    die(json_encode(['error' => 'Acesso negado']));
}

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

// --- 1. CPU (MÉTODO MÚLTIPLO) ---
$cpuUsage = 0;
if (function_exists('sys_getloadavg')) {
    $load = sys_getloadavg();
    $cpuUsage = (int)($load[0] * 10); 
} else {
    // Fallback se sys_getloadavg estiver bloqueado
    $stat = @file_get_contents('/proc/loadavg');
    if ($stat) {
        $cpuUsage = (int)(explode(' ', $stat)[0] * 10);
    }
}
if ($cpuUsage > 100) $cpuUsage = 99;

// --- 2. RAM (MÉTODO ROBUSTO) ---
$ramUsage = 0;
$memInfo = @file_get_contents("/proc/meminfo");
if ($memInfo) {
    preg_match('/MemTotal:\s+(\d+)/', $memInfo, $total);
    preg_match('/MemAvailable:\s+(\d+)/', $memInfo, $available);
    if (!$available) { // Fallback para kernels antigos
        preg_match('/MemFree:\s+(\d+)/', $memInfo, $free);
        preg_match('/Buffers:\s+(\d+)/', $memInfo, $buffers);
        preg_match('/Cached:\s+(\d+)/', $memInfo, $cached);
        $available[1] = $free[1] + $buffers[1] + $cached[1];
    }
    if ($total[1] > 0) {
        $used = $total[1] - $available[1];
        $ramUsage = (int)round(($used / $total[1]) * 100);
    }
}

// --- 3. DISCO ---
$diskTotal = @disk_total_space("/");
$diskFree = @disk_free_space("/");
$diskUsage = ($diskTotal > 0) ? (int)round((($diskTotal - $diskFree) / $diskTotal) * 100) : 0;

// --- 4. REDE ---
$txGb = "0.00 GB"; $rxGb = "0.00 GB";
$interface = trim(@shell_exec("ls /sys/class/net | grep -E 'eth|ens|enp' | head -n 1"));
if ($interface) {
    $tx = @file_get_contents("/sys/class/net/$interface/statistics/tx_bytes");
    $rx = @file_get_contents("/sys/class/net/$interface/statistics/rx_bytes");
    if ($tx) $txGb = round($tx / 1073741824, 2) . " GB";
    if ($rx) $rxGb = round($rx / 1073741824, 2) . " GB";
}

// Retornar JSON garantido
echo json_encode([
    'cpu'  => max(1, $cpuUsage), // Retorna pelo menos 1% para animar o gráfico
    'ram'  => max(1, $ramUsage),
    'disk' => max(1, $diskUsage),
    'tx'   => $txGb,
    'rx'   => $rxGb
]);