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

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

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

$servers = [];
$apiUrl = 'https://api.none.pw/mcserver/index.php'; // 替换为实际的 API 地址

// 使用 cURL 获取节点列表
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'User-Agent: Your-App-Name/1.0'
]);

$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($response !== false) {
    $apiData = json_decode($response, true);
    if (isset($apiData['servers']) && is_array($apiData['servers'])) {
        $servers = $apiData['servers'];
    } else {
        $servers = []; // 如果解析失败或格式不正确，设置为空数组
    }
} else {
    $servers = []; // 如果请求失败，设置为空数组
}

$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">
    <style>
        .create-player-container {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
        }

        .form-group select, .form-group input, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .form-group button {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .form-group button:hover {
            background-color: #0056b3;
        }

        .error {
            color: red;
            margin-bottom: 15px;
        }

        .success {
            color: green;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>

<div class="create-player-container">
    <h2>创建玩家</h2>
    <div id="response-message"></div>
    <form id="create-player-form">
        <div class="form-group">
            <label for="player_name">玩家名字</label>
            <input type="text" id="player_name" name="player_name" placeholder="请输入玩家名字" required>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
        </div>
        <div class="form-group">
            <label for="server_id">选择服务器</label>
            <select id="server_id" name="server_id" required>
                <option value="">请选择服务器</option>
                <?php foreach ($servers as $server): ?>
                    <option value="<?php echo htmlspecialchars($server['id']); ?>">
                        <?php echo htmlspecialchars($server['name']); ?> (<?php echo htmlspecialchars($server['location']); ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <button type="submit">创建玩家</button>
        </div>
    </form>
    <p>已有玩家？<a href="../index.php" class="menu-item">返回用户后台</a></p>
</div>

<script>
    document.getElementById('create-player-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        fetch('process_form.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text(); // 先获取原始文本
        })
        .then(text => {
            try {
                const data = JSON.parse(text);
                const responseMessage = document.getElementById('response-message');
                if (data.success) {
                    responseMessage.innerHTML = `<p class="success">${data.message}</p>`;
                    // 如果创建成功，可以跳转到玩家列表页面
                    setTimeout(() => {
                        window.location.href = '../index.php?login=success';
                    }, 2000);
                } else {
                    // 显示详细的错误信息
                    let errorMessage = data.message;
                    if (data.sql) {
                        errorMessage += `<br><br>SQL: ${data.sql}`;
                    }
                    if (data.player_name) {
                        errorMessage += `<br><br>玩家名称: ${data.player_name}`;
                    }
                    if (data.data) {
                        errorMessage += `<br><br>数据: ${data.data}`;
                    }
                    responseMessage.innerHTML = `<p class="error">${errorMessage}</p>`;
                    
                    // 输出到控制台
                    console.error('后端返回的错误信息:', data);
                }
            } catch (e) {
                // 如果解析 JSON 失败，显示原始文本
                console.error('解析 JSON 失败:', e);
                console.error('后端返回的原始文本:', text);
                document.getElementById('response-message').innerHTML = `<p class="error">创建玩家失败，请稍后重试！错误信息: ${text}</p>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            // 检查 error 是否包含 response
            if (error.response) {
                error.response.text().then(text => {
                    console.error('Response text:', text);
                    document.getElementById('response-message').innerHTML = `<p class="error">创建玩家失败，请稍后重试！错误信息: ${text}</p>`;
                });
            } else {
                document.getElementById('response-message').innerHTML = '<p class="error">创建玩家失败，请稍后重试！</p>';
            }
        });
    });
</script>
</body>
</html>