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

// 检查是否登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header("Location: ../auth"); // 未登录时跳转到登录页面
    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 = [];

// 获取用户数据
$ch = curl_init();
$user_search_url = $mcsm_panel_url . "/api/auth/search?apikey=" . urlencode($api_key) . "&userName=" . urlencode($username) . "&page=1&page_size=20&role=";
curl_setopt($ch, CURLOPT_URL, $user_search_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$users_response = curl_exec($ch);
$users_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($users_http_code != 200) {
    echo "<pre>获取用户数据失败: HTTP Code " . $users_http_code . " - " . htmlspecialchars($users_response) . "</pre>";
    exit();
}

$users_data = json_decode($users_response, true);

// 检查是否获取到用户数据
if (empty($users_data['data'])) {
    echo "<pre>未找到与您的用户名关联的实例数据。</pre>";
    exit();
}

// 遍历用户数据，获取 instanceUuid 和 daemonId
foreach ($users_data['data']['data'][0]['instances'] as $instance) {
    $instanceUuid = $instance['instanceUuid'];
    $daemonId = $instance['daemonId'];

    // 获取每个实例的详细信息
    $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);
    $instance_response = curl_exec($ch);
    $instance_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($instance_http_code != 200) {
        echo "<pre>获取实例信息失败 (Instance UUID: $instanceUuid, Daemon ID: $daemonId): HTTP Code " . $instance_http_code . " - " . htmlspecialchars($instance_response) . "</pre>";
        continue;
    }

    $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']['config']['docker']['cpuUsage'], // 提取 CPU 属性
        'memory' => $instance_data['data']['config']['docker']['memory'], // 提取内存属性
        'disk' => $instance_data['data']['processInfo']['disk']
    ];
}

curl_close($ch);

// 获取用户等级对应的描述
$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">
</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>欢迎来到圆周云境!</h1>
    </div>
    <div class="user-info">
        <p>账号: <?php echo htmlspecialchars($username); ?> (UID: <?php echo htmlspecialchars($user_id); ?>) <span class="<?php echo $levelColorClass; ?>"><?php echo htmlspecialchars($userLevelDescription); ?></span></p>
        <p>积分: <?php echo htmlspecialchars($points); ?></p>
    </div>
    <div class="menu">
        <a href="#" class="menu-item">新建实例</a>
        <a href="#" class="menu-item">教程文档</a>
    </div>
    <div class="other-buttons">
        <a href="#" class="button" onclick="showContent('instance1')">实例</a>
        <a href="#" class="button" onclick="showContent('instance2')">公告</a>
        <a href="#" class="button" onclick="showContent('instance3')">记录</a>
        <a href="#" class="button" onclick="showContent('instance4')">友链</a>
        <a href="#" class="button" onclick="showContent('instance5')">其他</a>
    </div>
</div>

<!-- 实例 -->
<div class="instance-container" id="instance1">
        <center><div class="instance">
        <?php if (empty($filtered_servers)): ?>
            <p>没有找到与您的邮箱关联的实例。</p>
        <?php else: ?>
            <center><?php foreach ($filtered_servers as $server): ?>
                <?php $ins_id = $server['instanceUuid'] ?>
                <a href="./ins/instance_info.php?InstanceId=<?php echo $ins_id ?>&daemonId=<?php echo $daemonId ?>" target="_blank" class="instance-button">
                    <div class="instance-content">
                        <div class="instance-item">
                            <p><?php echo htmlspecialchars($server['name']); ?></p>
                            <p>
                                <?php
                                $cpu_cores = $server['cpu'] / 100;
                                $memory = $server['memory'] / 1024;
                                $disk = $server['disk'] / 1024;
                                echo htmlspecialchars('CPU ' . $cpu_cores . ' 核 · ' .
                                    '内存 ' . $memory . 'GB · ' .
                                    '储存 ' . $disk . 'GB');
                                ?>
                            </p>
                        </div>
                    </div>
                </a>
            <?php endforeach; ?></center>
        <?php endif; ?>
    </div></center>
</div>

<!-- 公告 -->
<div class="instance-container" id="instance2" style="display: none;">
    <div class="instance">
        <h3>公告</h3>
        <p>这里是公告内容</p>
    </div>
</div>

<!-- 记录 -->
<div class="instance-container" id="instance3" style="display: none;">
    <div class="instance">
        <h3>记录</h3>
        <p>这里是记录内容</p>
    </div>
</div>

<!-- 友链 -->
<div class="instance-container" id="instance4" style="display: none;">
    <div class="instance">
        <h3>友链</h3>
        <p>这里是友链内容</p>
    </div>
</div>

<!-- 其他 -->
<div class="instance-container" id="instance5" 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');
</script>
</body>
</html>