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

/* ============================================================
   DATA MODE (?data=1)
   ============================================================ */
if (isset($_GET['data'])) {

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

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

        $total = array_sum($p);
        $idle  = $p[3] + ($p[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', FILE_IGNORE_NEW_LINES) as $l) {
        [$k, $v] = explode(':', $l);
        $mem[$k] = (int)filter_var($v, FILTER_SANITIZE_NUMBER_INT);
    }

    $ramTotal = round($mem['MemTotal'] / 1024);
    $ramUsed  = round(($mem['MemTotal'] - $mem['MemAvailable']) / 1024);
    $swapTotal = round(($mem['SwapTotal'] ?? 0) / 1024);
    $swapUsed  = round((($mem['SwapTotal'] ?? 0) - ($mem['SwapFree'] ?? 0)) / 1024);

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

    /* ---------- Disk IO (NVMe, MB/s) ---------- */
    $ioNow = ['read'=>0,'write'=>0];
    foreach (file('/proc/diskstats', FILE_IGNORE_NEW_LINES) as $l) {
        $p = preg_split('/\s+/', trim($l));
        if (($p[2] ?? '') === 'nvme0n1') {
            $ioNow['read']  += (int)$p[5];
            $ioNow['write'] += (int)$p[9];
        }
    }

    $stateFile = sys_get_temp_dir() . '/metrics_diskio.json';
    $prevIO = ['read'=>0,'write'=>0,'time'=>microtime(true)];
    if (is_readable($stateFile)) {
        $prevIO = json_decode(file_get_contents($stateFile), true);
    }

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

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

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

    /* ---------- Temp ---------- */
    $temp = file_exists('/sys/class/thermal/thermal_zone0/temp')
        ? round(file_get_contents('/sys/class/thermal/thermal_zone0/temp') / 1000, 1)
        : null;

    header('Content-Type: application/json');
    echo json_encode([
        'cpu' => [
            'usage' => getCpuUsage(),
            'load'  => $load,
        ],
        'ram' => ['used'=>$ramUsed,'total'=>$ramTotal],
        'swap'=> ['used'=>$swapUsed,'total'=>$swapTotal],
        'disk'=> ['used'=>$diskUsed,'total'=>$diskTotal],
        'io'   => [
            'read_mb_s'  => round(max($readMBs,0),2),
            'write_mb_s' => round(max($writeMBs,0),2),
        ],
        'temp'=>$temp,
        'ts'=>date('H:i:s'),
    ]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Live Metrics</title>

<style>
:root{
    --bg:#0f1115;--panel:#151922;--border:#2a2f3a;
    --text:#e6e6e6;--accent:#4da3ff;
}
*{box-sizing:border-box}
body{
    margin:0;background:var(--bg);color:var(--text);
    font-family:system-ui,sans-serif;padding:24px
}
h2{color:var(--accent);margin-top:0}
.grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:16px
}
.tile{
    background:var(--panel);
    border:1px solid var(--border);
    padding:14px
}
.tile h3{margin:0 0 6px;font-size:14px;color:var(--accent)}
.value{font-size:22px}
.small{opacity:.7;font-size:12px}
</style>
</head>
<body>

<h2>Live Metrics</h2>

<div class="grid">
    <div class="tile"><h3>CPU</h3><div id="cpu" class="value">–</div></div>
    <div class="tile"><h3>RAM</h3><div id="ram" class="value">–</div></div>
    <div class="tile"><h3>Swap</h3><div id="swap" class="value">–</div></div>
    <div class="tile"><h3>Disk /</h3><div id="disk" class="value">–</div></div>
    <div class="tile"><h3>Disk IO</h3><div id="io" class="value">–</div></div>
    <div class="tile"><h3>CPU Temp</h3><div id="temp" class="value">–</div></div>
</div>

<script>
function fmt(b){
    const u=['B','KB','MB','GB','TB'];let i=0;
    while(b>1024&&i<u.length-1){b/=1024;i++}
    return b.toFixed(1)+' '+u[i];
}
function tick(){
    fetch('metrics.php?data=1')
        .then(r=>r.json())
        .then(d=>{
            cpu.textContent =
              `${d.cpu.usage}% | ${d.cpu.load.join(' ')}`;
            ram.textContent =
              `${d.ram.used} MB / ${d.ram.total} MB`;
            swap.textContent =
              `${d.swap.used} MB / ${d.swap.total} MB`;
            disk.textContent =
              `${fmt(d.disk.used)} / ${fmt(d.disk.total)}`;
            io.textContent =
              `R ${d.io.read_mb_s} MB/s | W ${d.io.write_mb_s} MB/s`;
            temp.textContent =
              d.temp!==null ? d.temp+' °C' : 'n/a';
        });
}
tick();
setInterval(tick,1000);
</script>

</body>
</html>
