<?php
session_start();
require './config.php'; // 确保此文件中有数据库连接和 MCSManager 配置

// 检查是否登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header("Location: login.php"); // 未登录时跳转到登录页面
    exit();
}

// 获取当前用户信息
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// 从数据库中获取当前用户的邮箱
$stmt = $conn->prepare("SELECT email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($email);
$stmt->fetch();
$stmt->close();

// 查询用户的等级和积分
$stmt = $conn->prepare("SELECT level, points FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($level, $points);
$stmt->fetch();
$stmt->close();

// 等级描述映射
$levelDescriptions = [
    1 => '云境初探者',
    2 => '云境行者',
    3 => '云智大师',
    4 => '云核守护者'
];

// MCSManager 面板配置
$mcsm_panel_url = 'http://60.214.107.205:30000'; // 替换为实际的MCSManager面板地址
$api_key = $mcsm_api_key;

// 初始化服务器列表
$filtered_servers = [];
$instanceUuid = $_GET['InstanceId'] ?? '';
$daemonId = $_GET['daemonId'] ?? '';
// 检查是否通过GET方法获取了instanceId和daemonId
if ($instanceUuid && $daemonId) {
    // 初始化cURL会话
    $ch = curl_init();
    
    // 获取每个实例的详细信息
    $instance_info_url = $mcsm_panel_url . "/api/instance?apikey=" . urlencode($api_key) . "&uuid=" . urlencode($instanceUuid) . "&daemonId=" . urlencode($daemonId);
    curl_setopt($ch, CURLOPT_URL, $instance_info_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $instance_response = curl_exec($ch);
    $instance_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($instance_http_code != 200) {
        echo "<pre>获取实例信息失败 (Instance UUID: $instanceUuid, Daemon ID: $daemonId): HTTP Code " . $instance_http_code . " - " . htmlspecialchars($instance_response) . "</pre>";
    } else {
        $instance_data = json_decode($instance_response, true);

        // 将实例信息添加到服务器列表
        $filtered_servers[] = [
            'name' => $instance_data['data']['config']['nickname'], // 从 config 数组中的 nickname 提取
            'instanceUuid' => $instanceUuid,
            'daemonId' => $daemonId,
            'cpu' => $instance_data['data']['processInfo']['cpu'], // 提取 CPU 属性
            'memory' => $instance_data['data']['processInfo']['memory'], // 提取内存属性
            'disk' => $instance_data['data']['processInfo']['disk'],
            'ip' => "服务器 IP:" . "play.none.pw:" . $instance_data['data']['config']['pingConfig']['port']
        ];
    }
}

// 获取用户等级对应的描述
$userLevelDescription = $levelDescriptions[$level] ?? '未知等级';

// 等级颜色类
$levelColorClass = "level-$level";

// 检测登录成功标志
$loginSuccess = isset($_GET['login']) && $_GET['login'] === 'success';
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>圆周云境</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="top-bar">
        <div class="top-bar-content">
            <h2>圆周云境</h2>
        </div>
        <div class="blue-bar"></div>
    </div>

    <div class="combined-container">
        <div class="header">
            <h1 id="instance-name"><?php echo htmlspecialchars($filtered_servers[0]['name'] ?? '未知实例'); ?></h1>
            <p id="instance-ip"><?php echo htmlspecialchars($filtered_servers[0]['ip'] ?? '未知ip'); ?></p>
        </div>
        <div class="other-buttons">
            <a href="#" class="button" onclick="showContent('instance1')">实例</a>
            <a href="#" class="button" onclick="showContent('instance2')">其他</a>
        </div>
    </div>
    <!-- 实例 -->
    <div class="instance-container" id="instance1">
        <div class="instance">
            <?php if (!empty($filtered_servers)): ?>
                <div class="info-container" id="info-container">
                    <div class="info-box">
                        <p>CPU 使用量: <span id="cpu-usage"><?php echo $filtered_servers[0]['cpu'] ?? '0'; ?>%</span></p>
                    </div>
                    <div class="info-box">
                        <p>内存使用量: <span id="memory-usage"><?php echo $filtered_servers[0]['memory'] ?? '0'; ?>GB</span></p>
                    </div>
                    <div class="info-box">
                        <p>网络流量</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- 其他 -->
    <div class="instance-container" id="instance2" style="display: none;">
        <div class="instance">
            <?php if ($level == 4): ?>
                <a href="./user_management.php" class="menu-item">进入用户管理系统</a>
            <?php endif; ?>
            <br>
            <div class="logout-container">
                <a href="./logout.php" class="logout-button menu-item">登出</a>
            </div>
        </div>
    </div>
<script>
    function showContent(id) {
        const instances = document.querySelectorAll('.instance-container');
        instances.forEach(instance => instance.style.display = 'none');
        const content = document.getElementById(id);
        if (content) {
            content.style.display = 'block';
        }
    }

    window.onload = () => showContent('instance1');

    function fetchData() {
        $.ajax({
            url: 'fetch_data.php',
            type: 'GET',
            data: {
                instanceUuid: '<?php echo $instanceUuid; ?>',
                daemonId: '<?php echo $daemonId; ?>'
            },
            dataType: 'json', // 明确指定返回的数据类型
            cache: false, // 禁止缓存，确保获取最新数据
            timeout: 10000, // 设置超时时间（10秒）
            success(response) {
                if (response && response.success) {
                    document.getElementById('instance-name').textContent = response.name;
                    document.getElementById('instance-ip').textContent = response.ip;
                    document.getElementById('cpu-usage').textContent = response.cpu + '%';
                    document.getElementById('memory-usage').textContent = response.memory + 'GB';
                } else {
                    console.error('Failed to fetch data:', response);
                }
            },
            error(error) {
                console.log('Error fetching data:', error);
            }
        });
    }

    setInterval(fetchData, 10000); // 每 10 秒调用一次 fetchData 函数
</script>
</body>
</html>