<?php
session_start();
require '../auth/config.php';

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

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

// 查询用户的等级和积分
$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 => '云核守护者'
];

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

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

// 检查是否是管理员
if ($level != 4) {
    echo "您没有权限访问此页面。";
    exit();
}

// 处理删除用户操作
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_user'])) {
    $delete_id = intval($_POST['delete_id']);
    $stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $stmt->bind_result($delete_username);
    $stmt->fetch();
    $stmt->close();

    // 删除本地用户
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();

    // 调用 Pterodactyl API 删除同名用户
    $pterodactyl_api_url = "https://pterodactyl.app/api/application/users";
    $data = [
        "username" => $delete_username
    ];
    $ch = curl_init($pterodactyl_api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $pterodactyl_api_key
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code == 204) {
        echo "<script>alert('用户删除成功，Pterodactyl 面板中的用户也已删除。');</script>";
    } else {
        echo "<script>alert('用户删除成功，但 Pterodactyl 面板中的用户删除失败。');</script>";
    }

    header("Location: user_management.php");
    exit();
}
?>

<!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="other-buttons">
        <a href="#" class="button" onclick="showContent('instance1')">查看用户</a>
    </div>
</div>

<!-- 用户列表 -->
<div class="instance-container" id="instance1">
    <table class="user-table">
        <thead>
        <tr>
            <th>用户名</th>
            <th>邮箱</th>
            <th>等级</th>
            <th>积分</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <?php
        $stmt = $conn->prepare("SELECT id, username, email, level, points FROM users");
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['username']) . "</td>";
            echo "<td>" . htmlspecialchars($row['email']) . "</td>";
            echo "<td>" . htmlspecialchars($levelDescriptions[$row['level']]) . "</td>";
            echo "<td>" . htmlspecialchars($row['points']) . "</td>";
            echo "<td>
                    <a href='edit_user.php?id=" . $row['id'] . "' class='action-button edit-button'>编辑</a>
                    <form method='post' style='display:inline;'>
                        <input type='hidden' name='delete_id' value='" . $row['id'] . "'>
                        <button type='submit' name='delete_user' class='action-button delete-button' onclick='return confirm(\"确定要删除用户 " . htmlspecialchars($row['username']) . " 吗？\")'>删除</button>
                    </form>
                  </td>";
            echo "</tr>";
        }
        $stmt->close();
        ?>
        </tbody>
    </table>
</div>


<div class="logout-container">
    <a href="./logout.php" class="logout-button menu-item">登出</a>
</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';
        }
    }
</script>
</body>
</html>