<?php
header('Content-Type: application/json');
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/session.php';
require_once __DIR__ . '/is_admin.php';
require_once __DIR__ . '/autoloader.php';

use phpseclib3\Net\SSH2;

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid server ID']);
    exit;
}

$server_id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM servers WHERE id = ?");
$stmt->execute([$server_id]);
$server = $stmt->fetch();

if (!$server) {
    echo json_encode(['status' => 'error', 'message' => 'Server not found']);
    exit;
}

$response = [
    'status' => 'offline',
    'cpu' => 0,
    'ram' => 0,
    'disk' => 0,
];

try {
    $ssh = new SSH2($server['ip_address'], $server['ssh_port']);
    $ssh->setTimeout(5); // 5 second timeout for connection
    $password = decrypt_data($server['ssh_password']);
    if (!$ssh->login($server['ssh_user'], $password)) {
        throw new Exception('Authentication failed');
    }

    $response['status'] = 'online';

    // CPU Usage
    $cpu_raw = $ssh->exec("top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'");
    $response['cpu'] = round(floatval(trim($cpu_raw)), 1);
    if ($response['cpu'] > 100) $response['cpu'] = 100;

    // RAM Usage
    $ram_raw = $ssh->exec("free | grep -i mem | awk '{print $3/$2 * 100.0}'");
    $response['ram'] = round(floatval(trim($ram_raw)), 1);

    // Disk Usage
    $disk_raw = $ssh->exec("df --output=pcent / | tail -n 1 | tr -d ' %'");
    $response['disk'] = intval(trim($disk_raw));

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>