<?php
require './config.php';

if (!isset($conn, $mcsm_api_key, $mcsm_api_url)) {
    die("连接失败：\$conn 或 MCSM API 配置未定义");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm-password'];

    // 输入验证逻辑
    if (empty($email)) {
        echo "邮箱不能为空，请填写邮箱地址。";
        exit();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "邮箱格式不正确，请输入有效的邮箱地址。";
        exit();
    }

    if ($password !== $confirm_password) {
        echo "密码不一致，请重新输入。";
        exit();
    }

    // 密码必须包含大小写字母
    if (!preg_match('/[a-z]/', $password) || !preg_match('/[A-Z]/', $password)) {
        echo "密码必须包含大小写字母。";
        exit();
    }

    // 检查用户名是否已存在
    $stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        echo "用户名已存在，请选择其他用户名。";
        exit();
    }

    // 检查邮箱是否已存在
    $stmt = $conn->prepare("SELECT email FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        echo "邮箱已被注册，请使用其他邮箱。";
        exit();
    }

    // 密码散列
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // 设置默认等级和积分
    $level = 1;
    $points = 100;

    // 调用 MCSM API 创建用户
    $mcsm_api_url = $mcsm_api_url . "/api/auth"; // 确认这是正确的路径
    $data = [
        "username" => $username,
        "password" => $password,
        "email" => $email,
        "permission" => 1
    ];

    // 初始化 cURL
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $mcsm_api_url . "?apikey=" . urlencode($mcsm_api_key),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Accept: */*',
            'Connection: keep-alive'
        ),
    ));

    // 执行 cURL 请求
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($http_code == 200 || $http_code == 201) {
        // MCSM 用户创建成功
        $stmt = $conn->prepare("INSERT INTO users (username, email, password, level, points) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssis", $username, $email, $hashed_password, $level, $points);
        if ($stmt->execute()) {
            echo "注册成功！请登录。";
        } else {
            echo "本地数据库创建用户失败。";
        }
    } else {
        // MCSM 用户创建失败
        echo "MCSM 用户创建失败：";
        if ($response) {
            $response_data = json_decode($response, true);
            if (isset($response_data['data'])) {
                echo $response_data['data'];
            } else {
                echo "未知错误，请联系管理员。";
            }
        } else {
            echo "未返回任何响应，请检查网络或 API 配置。";
        }
    }

    $stmt->close();
}
$conn->close();