<?php
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '无权限访问']);
    exit;
}

// 服务器软件
$server_software = $_SERVER['SERVER_SOFTWARE'] ?? '未知';

// PHP版本
$php_version = PHP_VERSION;

// 服务器操作系统
$os = php_uname('s') . ' ' . php_uname('r');

// 服务器时间
$server_time = date('Y-m-d H:i:s');

// MySQL版本
$mysql_version = $db->fetchOne("SELECT VERSION() as ver")['ver'] ?? '未知';

// 数据库大小
$db_size = 0;
$tables = $db->fetchAll("SHOW TABLE STATUS");
foreach ($tables as $table) {
    $db_size += ($table['Data_length'] + $table['Index_length']);
}
$db_size = round($db_size / 1024 / 1024, 2);

// MySQL运行时间
$mysql_uptime = '未知';
$uptime_result = $db->fetchOne("SHOW GLOBAL STATUS LIKE 'Uptime'");
if ($uptime_result) {
    $seconds = $uptime_result['Value'];
    $days = floor($seconds / 86400);
    $hours = floor(($seconds % 86400) / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    $mysql_uptime = "{$days}天 {$hours}小时 {$minutes}分钟";
}

// 获取CPU核心数（不使用shell_exec）
function getCpuCores() {
    if (PHP_OS_FAMILY === 'Linux' && is_readable('/proc/cpuinfo')) {
        $cpuinfo = @file_get_contents('/proc/cpuinfo');
        if ($cpuinfo) {
            preg_match_all('/^processor/m', $cpuinfo, $matches);
            $cores = count($matches[0]);
            if ($cores > 0) return $cores;
        }
    }
    return 2; // 默认2核
}

$cpu_cores = getCpuCores();

// 系统负载
$load = [0, 0, 0];
if (PHP_OS_FAMILY === 'Linux') {
    $load = sys_getloadavg();
}
$load_1min = round($load[0] ?? 0, 2);
$load_5min = round($load[1] ?? 0, 2);
$load_15min = round($load[2] ?? 0, 2);

// CPU使用率（基于负载 / 核心数计算）
$cpu_usage = round(($load_1min / $cpu_cores) * 100, 1);
if ($cpu_usage > 100) $cpu_usage = 100;
if ($cpu_usage < 0) $cpu_usage = 0;

// 磁盘使用
$disk_total = disk_total_space('/');
$disk_free = disk_free_space('/');
$disk_used = $disk_total - $disk_free;
$disk_used_percent = $disk_total > 0 ? round(($disk_used / $disk_total) * 100, 1) : 0;
$disk_total_gb = round($disk_total / 1024 / 1024 / 1024, 2);
$disk_used_gb = round($disk_used / 1024 / 1024 / 1024, 2);
$disk_free_gb = round($disk_free / 1024 / 1024 / 1024, 2);

// 磁盘IO
$io_write_speed = 0;
$test_file = '/tmp/io_test_' . uniqid() . '.tmp';
$test_data = str_repeat('x', 1024 * 1024);
$start = microtime(true);
if (@file_put_contents($test_file, $test_data)) {
    $end = microtime(true);
    @unlink($test_file);
    $io_write_speed = round(1 / ($end - $start), 2);
}

echo json_encode([
    'success' => true,
    'data' => [
        'server_software' => $server_software,
        'php_version' => $php_version,
        'os' => $os,
        'server_time' => $server_time,
        'mysql_version' => $mysql_version,
        'db_size' => $db_size,
        'mysql_uptime' => $mysql_uptime,
        'load_1min' => $load_1min,
        'load_5min' => $load_5min,
        'load_15min' => $load_15min,
        'cpu_usage' => $cpu_usage,
        'cpu_cores' => $cpu_cores,
        'disk_total' => $disk_total_gb,
        'disk_used' => $disk_used_gb,
        'disk_free' => $disk_free_gb,
        'disk_used_percent' => $disk_used_percent,
        'io_write_speed' => $io_write_speed
    ]
]);