<?php
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'])) {
    header('Location: monitoring.php');
    exit;
}

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

if (!$server) {
    header('Location: monitoring.php');
    exit;
}

$page_title = 'مانیتورینگ سرور: ' . htmlspecialchars($server['name']);

$ssh_status = 'ok';
$server_stats = [
    'cpu' => 0,
    'ram' => 0,
    'disk' => 0,
    'uptime' => 'N/A',
    'net_speed_down' => '0 B/s',
    'net_speed_up' => '0 B/s',
    'net_total_rx' => '0 B',
    'net_total_tx' => '0 B',
    'error' => null
];

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

    // Uptime
    $uptime_raw = $ssh->exec('uptime -p');
    $server_stats['uptime'] = trim(str_replace('up', '', $uptime_raw));

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

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

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

    // Network Stats
    $interface = trim($ssh->exec("ip route | grep default | awk '{print $5}' | head -n1"));
    if ($interface) {
        // Total Usage
        $total_rx = trim($ssh->exec("cat /sys/class/net/{$interface}/statistics/rx_bytes"));
        $total_tx = trim($ssh->exec("cat /sys/class/net/{$interface}/statistics/tx_bytes"));
        $server_stats['net_total_rx'] = formatBytes($total_rx);
        $server_stats['net_total_tx'] = formatBytes($total_tx);

        // Real-time Speed
        $stat1_str = $ssh->exec("cat /proc/net/dev | grep '{$interface}:'");
        sleep(1);
        $stat2_str = $ssh->exec("cat /proc/net/dev | grep '{$interface}:'");

        preg_match_all('/\d+/', $stat1_str, $matches1);
        preg_match_all('/\d+/', $stat2_str, $matches2);

        if (!empty($matches1[0]) && !empty($matches2[0])) {
            $rx_speed_bps = intval($matches2[0][0]) - intval($matches1[0][0]);
            $tx_speed_bps = intval($matches2[0][8]) - intval($matches1[0][8]);
            $server_stats['net_speed_down'] = formatBytes($rx_speed_bps) . '/s';
            $server_stats['net_speed_up'] = formatBytes($tx_speed_bps) . '/s';
        }
    }

} catch (Exception $e) {
    $ssh_status = 'error';
    $server_stats['error'] = 'خطا در اتصال به سرور: ' . $e->getMessage();
}

$server_stats['cpu'] = $server_stats['cpu'] ?: 0;
$server_stats['ram'] = $server_stats['ram'] ?: 0;
$server_stats['disk'] = $server_stats['disk'] ?: 0;

require_once __DIR__ . '/../includes/header.php';
?>

<div class="row mb-3">
    <div class="col-12">
        <h4 class="mb-sm-0 font-size-18">مانیتورینگ سرور: <?= htmlspecialchars($server['name']) ?> <span class="text-muted">(<?= htmlspecialchars($server['ip_address']) ?>)</span></h4>
    </div>
</div>

<?php if ($ssh_status === 'error'): ?>
<div class="alert alert-danger">
    <i class="bi bi-exclamation-triangle-fill me-2"></i>
    <?= $server_stats['error'] ?>
    <br>
    <small>لطفاً مطمئن شوید اطلاعات سرور (IP, Port, User, Password) صحیح است و دسترسی SSH از طریق سرور وب امکان‌پذیر است.</small>
</div>
<?php else: ?>
<div class="row">
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center">
                <div id="cpu-chart"></div>
                <h5 class="mt-3 mb-0">پردازنده (CPU)</h5>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center">
                <div id="ram-chart"></div>
                <h5 class="mt-3 mb-0">حافظه (RAM)</h5>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center">
                <div id="disk-chart"></div>
                <h5 class="mt-3 mb-0">دیسک (Disk)</h5>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center align-items-center">
                 <i class="bi bi-clock-history text-primary" style="font-size: 3.5rem;"></i>
                 <h5 class="font-size-18 mt-3 mb-1">Uptime</h5>
                 <p class="text-muted mb-0 font-size-16"><?= htmlspecialchars($server_stats['uptime']) ?: 'N/A' ?></p>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center align-items-center">
                 <i class="bi bi-arrow-down-up text-success" style="font-size: 3.5rem;"></i>
                 <h5 class="font-size-18 mt-3 mb-1">پهنای باند لحظه‌ای</h5>
                 <p class="text-muted mb-0 w-100"><i class="bi bi-arrow-down"></i> دریافت: <span class="font-weight-bold"><?= $server_stats['net_speed_down'] ?></span></p>
                 <p class="text-muted mb-0 w-100"><i class="bi bi-arrow-up"></i> ارسال: <span class="font-weight-bold"><?= $server_stats['net_speed_up'] ?></span></p>
            </div>
        </div>
    </div>
    <div class="col-lg-4 col-md-6 mb-4">
        <div class="card text-center h-100">
            <div class="card-body d-flex flex-column justify-content-center align-items-center">
                 <i class="bi bi-hdd-network-fill text-info" style="font-size: 3.5rem;"></i>
                 <h5 class="font-size-18 mt-3 mb-1">حجم کل مصرفی</h5>
                 <p class="text-muted mb-0 w-100"><i class="bi bi-arrow-down"></i> دریافت: <span class="font-weight-bold"><?= $server_stats['net_total_rx'] ?></span></p>
                 <p class="text-muted mb-0 w-100"><i class="bi bi-arrow-up"></i> ارسال: <span class="font-weight-bold"><?= $server_stats['net_total_tx'] ?></span></p>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php
$footer_scripts = "<script src=\"https://cdn.jsdelivr.net/npm/apexcharts@3.35.5/dist/apexcharts.min.js\"></script>\n";
if ($ssh_status !== 'error') {
    $footer_scripts .= "<script>
    function createRadialChart(selector, series, color) {
        var options = {
            chart: {
                height: 200,
                type: 'radialBar',
            },
            series: [series],
            colors: [color],
            plotOptions: {
                radialBar: {
                    hollow: {
                        margin: 0,
                        size: \"70%\",
                        background: \"#2a3042\"
                    },
                    track: {
                        background: '#3c445c',
                        dropShadow: {
                            enabled: true,
                            top: 2,
                            left: 0,
                            blur: 4,
                            opacity: 0.15
                        }
                    },
                    dataLabels: {
                        name: {
                            show: false,
                        },
                        value: {
                            color: \"#fff\",
                            fontSize: \"28px\",
                            show: true,
                            formatter: function (val) {
                                return val + '%'
                            }
                        }
                    }
                }
            },
            stroke: {
                lineCap: \"round\"
            },
        };
        var chart = new ApexCharts(document.querySelector(selector), options);
        chart.render();
    }

    createRadialChart('#cpu-chart', [{$server_stats['cpu']}], '#556ee6');
    createRadialChart('#ram-chart', [{$server_stats['ram']}], '#34c38f');
    createRadialChart('#disk-chart', [{$server_stats['disk']}], '#f1b44c');

    </script>";
}

require_once __DIR__ . '/../includes/footer.php';
?>
