<?php
// 1. BACKEND LOGIC: Intercept API requests before sending any HTML
if (isset($_GET['api']) && $_GET['api'] === 'metrics') {
    header('Content-Type: application/json');
    
    // Fetch CPU Load Average (Linux)
    $cpuLoad = function_exists('sys_getloadavg') ? sys_getloadavg()[0] : 'N/A';
    $ramTotal = 'N/A';
    $ramUsed = 'N/A';
    
    // Fetch RAM usage from /proc/meminfo
    if (is_readable('/proc/meminfo')) {
        $meminfo = file_get_contents('/proc/meminfo');
        preg_match('/MemTotal:\s+(\d+)\s+kB/', $meminfo, $totalMatch);
        preg_match('/MemAvailable:\s+(\d+)\s+kB/', $meminfo, $availMatch);
        
        if (isset($totalMatch[1]) && isset($availMatch[1])) {
            $totalKb = $totalMatch[1];
            $availKb = $availMatch[1];
            $usedKb = $totalKb - $availKb;
            
            $ramTotal = round($totalKb / (1024 * 1024), 2) . ' GB';
            $ramUsed = round($usedKb / (1024 * 1024), 2) . ' GB';
        }
    }
    
    echo json_encode([
        'cpu' => $cpuLoad,
        'ramTotal' => $ramTotal,
        'ramUsed' => $ramUsed
    ]);
    
    // Terminate script so the HTML below is not appended to the JSON response
    exit; 
}
?>

<!-- 2. FRONTEND LOGIC: HTML, CSS, and JavaScript -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Server Resource Monitor</title>
    <style>
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background-color: #1e1e2e; 
            color: #cdd6f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .monitor-card { 
            background: #313244; 
            padding: 30px; 
            border-radius: 12px; 
            box-shadow: 0 10px 15px rgba(0,0,0,0.3); 
            width: 300px; 
        }
        h2 { 
            margin-top: 0; 
            color: #89b4fa; 
            border-bottom: 2px solid #45475a;
            padding-bottom: 10px;
        }
        .metric { 
            margin: 15px 0; 
            font-size: 16px; 
            display: flex;
            justify-content: space-between;
        }
        .value { 
            font-weight: bold; 
            color: #a6e3a1; 
        }
    </style>
</head>
<body>
    <div class="monitor-card">
        <h2>Live Server Metrics</h2>
        <div class="metric"><span>CPU Load:</span> <span id="cpu" class="value">Loading...</span></div>
        <div class="metric"><span>Total RAM:</span> <span id="total-ram" class="value">Loading...</span></div>
        <div class="metric"><span>Used RAM:</span> <span id="used-ram" class="value">Loading...</span></div>
    </div>

    <script>
        async function fetchServerResources() {
            try {
                // The JS calls its own file with the ?api=metrics parameter
                const response = await fetch(window.location.pathname + '?api=metrics');
                const data = await response.json();
                
                document.getElementById('cpu').innerText = data.cpu;
                document.getElementById('total-ram').innerText = data.ramTotal;
                document.getElementById('used-ram').innerText = data.ramUsed;
            } catch (error) {
                console.error('Failed to fetch metrics:', error);
            }
        }

        fetchServerResources();
        setInterval(fetchServerResources, 5000);
    </script>
</body>
</html>