<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/auth.php';
function_admin_login_erfordern();

/* ---------- CPU Usage (%) ---------- */
function getCpuUsage(): float
{
    static $prev = null;

    $line = file('/proc/stat')[0];
    $parts = array_values(array_filter(explode(' ', trim($line))));
    array_shift($parts);

    $total = array_sum($parts);
    $idle  = $parts[3] + ($parts[4] ?? 0);

    if ($prev === null) {
        $prev = [$total, $idle];
        return 0.0;
    }

    [$pt, $pi] = $prev;
    $prev = [$total, $idle];

    $dt = $total - $pt;
    $di = $idle - $pi;

    return $dt > 0 ? round((1 - ($di / $dt)) * 100, 1) : 0.0;
}

/* ---------- Load ---------- */
$load = sys_getloadavg();

/* ---------- RAM / Swap (MB) ---------- */
$mem = [];
foreach (file('/proc/meminfo') as $l) {
    [$k, $v] = explode(':', $l);
    $mem[$k] = (int)filter_var($v, FILTER_SANITIZE_NUMBER_INT);
}

$ramTotalMB = round($mem['MemTotal'] / 1024);
$ramUsedMB  = round(($mem['MemTotal'] - $mem['MemAvailable']) / 1024);
$swapTotalMB = round(($mem['SwapTotal'] ?? 0) / 1024);
$swapUsedMB  = round((($mem['SwapTotal'] ?? 0) - ($mem['SwapFree'] ?? 0)) / 1024);

/* ---------- Disk Usage ---------- */
$diskTotal = disk_total_space('/');
$diskFree  = disk_free_space('/');
$diskUsed  = $diskTotal - $diskFree;

/* ---------- Disk IO (MB/s) ---------- */
$ioNow = ['read' => 0, 'write' => 0];

foreach (file('/proc/diskstats', FILE_IGNORE_NEW_LINES) as $line) {
    $p = preg_split('/\s+/', trim($line));

    // Device-Name steht an Index 2
    $dev = $p[2] ?? '';

    // NUR Haupt-NVMe-Disk, keine Partitionen
    if ($dev === 'nvme0n1') {
        $ioNow['read']  += (int)$p[5]; // sectors read
        $ioNow['write'] += (int)$p[9]; // sectors written
    }
}

$stateFile = sys_get_temp_dir() . '/metrics_diskio.json';
$prev = ['read'=>0,'write'=>0,'time'=>microtime(true)];

if (is_readable($stateFile)) {
    $prev = json_decode(file_get_contents($stateFile), true);
}

$now = microtime(true);
$dt  = max($now - $prev['time'], 0.5); // Schutz gegen 0

$readMBs  = (($ioNow['read']  - $prev['read'])  * 512) / 1024 / 1024 / $dt;
$writeMBs = (($ioNow['write'] - $prev['write']) * 512) / 1024 / 1024 / $dt;

file_put_contents($stateFile, json_encode([
    'read'  => $ioNow['read'],
    'write' => $ioNow['write'],
    'time'  => $now
]));


$stateFile = sys_get_temp_dir() . '/metrics_diskio.json';
$ioPrev = ['read'=>0,'write'=>0,'time'=>microtime(true)];

if (file_exists($stateFile)) {
    $ioPrev = json_decode(file_get_contents($stateFile), true);
}

$now = microtime(true);
$dt  = max($now - $ioPrev['time'], 1);

$readMB  = (($ioNow['read']  - $ioPrev['read'])  * 512) / 1024 / 1024 / $dt;
$writeMB = (($ioNow['write'] - $ioPrev['write']) * 512) / 1024 / 1024 / $dt;

file_put_contents($stateFile, json_encode([
    'read'  => $ioNow['read'],
    'write' => $ioNow['write'],
    'time'  => $now
]));

/* ---------- Temperature ---------- */
$temp = null;
if (file_exists('/sys/class/thermal/thermal_zone0/temp')) {
    $temp = round(file_get_contents('/sys/class/thermal/thermal_zone0/temp') / 1000, 1);
}

header('Content-Type: application/json');
echo json_encode([
    'cpu' => [
        'usage' => getCpuUsage(),
        'load'  => $load,
    ],
    'ram' => [
        'used'  => $ramUsedMB,
        'total' => $ramTotalMB,
    ],
    'swap' => [
        'used'  => $swapUsedMB,
        'total' => $swapTotalMB,
    ],
    'disk' => [
        'used'  => $diskUsed,
        'total' => $diskTotal,
    ],
    'io' => [
        'read_mb_s'  => round(max($readMB, 0), 2),
        'write_mb_s' => round(max($writeMB, 0), 2),
    ],
    'temp' => $temp,
    'ts' => date('H:i:s'),
]);
