<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');

ini_set('display_errors', 0);
error_reporting(0);

function getSystemStats() {
    $stats = [];

    // ========== UPTIME ==========
    if (file_exists('/proc/uptime')) {
        $uptime = @file_get_contents('/proc/uptime');
        if ($uptime !== false) {
            $uptimeSeconds = floatval(explode(' ', $uptime)[0]);
            $days    = floor($uptimeSeconds / 86400);
            $hours   = floor(($uptimeSeconds % 86400) / 3600);
            $minutes = floor(($uptimeSeconds % 3600) / 60);
            $stats['uptime'] = sprintf('%dd %dh %dm', $days, $hours, $minutes);
        } else {
            $stats['uptime'] = 'N/A';
        }
    } else {
        $stats['uptime'] = 'N/A';
    }

    // ========== CPU USAGE ==========
    if (file_exists('/proc/stat')) {
        $stat1 = @file('/proc/stat');
        if ($stat1 !== false && count($stat1) > 0) {
            usleep(100000);
            $stat2 = @file('/proc/stat');
            if ($stat2 !== false && count($stat2) > 0) {
                $info1 = explode(' ', preg_replace('!cpu +!', '', $stat1[0]));
                $info2 = explode(' ', preg_replace('!cpu +!', '', $stat2[0]));
                $dif = [
                    'user' => floatval($info2[0]) - floatval($info1[0]),
                    'nice' => floatval($info2[1]) - floatval($info1[1]),
                    'sys'  => floatval($info2[2]) - floatval($info1[2]),
                    'idle' => floatval($info2[3]) - floatval($info1[3])
                ];
                $total = array_sum($dif);
                $stats['cpu_usage'] = $total > 0 ? round(100 - ($dif['idle'] / $total * 100), 1) : 0;
            } else {
                $load = sys_getloadavg();
                $stats['cpu_usage'] = round(min($load[0] * 25, 100), 1);
            }
        } else {
            $load = sys_getloadavg();
            $stats['cpu_usage'] = round(min($load[0] * 25, 100), 1);
        }
    } else {
        $stats['cpu_usage'] = 0;
    }

    // ========== MEMORY ==========
    if (file_exists('/proc/meminfo')) {
        $meminfo = @file_get_contents('/proc/meminfo');
        if ($meminfo !== false) {
            preg_match_all('/^(\w+):\s+(\d+)/m', $meminfo, $matches);
            $mem = array_combine($matches[1], $matches[2]);
            $memTotal     = floatval($mem['MemTotal']) / 1024 / 1024;
            $memAvailable = isset($mem['MemAvailable'])
                ? floatval($mem['MemAvailable'])
                : (floatval($mem['MemFree']) + floatval($mem['Buffers']) + floatval($mem['Cached']));
            $memFree = $memAvailable / 1024 / 1024;
            $memUsed = $memTotal - $memFree;
            $stats['ram_total']   = round($memTotal, 1);
            $stats['ram_used']    = round($memUsed, 1);
            $stats['ram_free']    = round($memFree, 1);
            $stats['ram_percent'] = round(($memUsed / $memTotal) * 100, 1);
        } else {
            $stats['ram_total'] = $stats['ram_used'] = $stats['ram_percent'] = 0;
        }
    } else {
        $stats['ram_total'] = $stats['ram_used'] = $stats['ram_percent'] = 0;
    }

    // ========== DISK ==========
    $partitions = ['/', '/var', '/srv'];
    foreach ($partitions as $partition) {
        $key = str_replace('/', '', $partition);
        if ($key === '') $key = 'root';
        $diskTotal = @disk_total_space($partition);
        $diskFree  = @disk_free_space($partition);
        if ($diskTotal !== false && $diskFree !== false) {
            $diskUsed = $diskTotal - $diskFree;
            $stats['disk_' . $key . '_total']   = round($diskTotal / 1024 / 1024 / 1024, 1);
            $stats['disk_' . $key . '_used']    = round($diskUsed  / 1024 / 1024 / 1024, 1);
            $stats['disk_' . $key . '_free']    = round($diskFree  / 1024 / 1024 / 1024, 1);
            $stats['disk_' . $key . '_percent'] = round(($diskUsed / $diskTotal) * 100, 1);
        } else {
            $stats['disk_' . $key . '_total']   = 0;
            $stats['disk_' . $key . '_free']    = 0;
            $stats['disk_' . $key . '_percent'] = 0;
        }
    }

    // ========== LOAD AVERAGE ==========
    $loadavg = sys_getloadavg();
    $stats['load_1']  = round($loadavg[0], 2);
    $stats['load_5']  = round($loadavg[1], 2);
    $stats['load_15'] = round($loadavg[2], 2);

    // ========== PROCESSES ==========
    if (function_exists('shell_exec')) {
        $processes = @shell_exec('ps aux 2>/dev/null | wc -l');
        $stats['processes'] = $processes !== null ? max(intval(trim($processes)) - 1, 0) : 0;
    } else {
        $stats['processes'] = 0;
    }

    $stats['hostname']  = @gethostname() ?: 'Unknown';
    $stats['timestamp'] = time();

    return $stats;
}

try {
    echo json_encode([
        'success' => true,
        'data'    => getSystemStats()
    ], JSON_NUMERIC_CHECK);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error'   => $e->getMessage()
    ]);
}
?>
