<?php
session_start(); // 确保会话启动
require './config.php';

if (!isset($conn)) {
    die(json_encode(['success' => false, 'message' => "连接失败：\$conn 未定义"]));
}

// 初始化响应数组
$response = [
    'success' => false,
    'message' => ''
];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $turnstile_response = isset($_POST['cf-turnstile-response']) ? $_POST['cf-turnstile-response'] : '';

    if (empty($username) || empty($password)) {
        $response['message'] = "用户名、密码或验证码不能为空，请重新输入。";
        echo json_encode($response);
        exit();
    }

    // 验证 Turnstile 验证码
    $turnstile_secret = "0x4AAAAAABj3qDy9ZHnEE_FGoXQN6RwAzJQ"; // 替换为你的 Turnstile Secret Key
    $turnstile_url = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
    $turnstile_data = [
        'secret' => $turnstile_secret,
        'response' => $turnstile_response
    ];
    $turnstile_options = [
        'http' => [
            'method'  => 'POST',
            'content' => http_build_query($turnstile_data)
        ]
    ];
    $turnstile_context = stream_context_create($turnstile_options);
    $turnstile_result = file_get_contents($turnstile_url, false, $turnstile_context);

    if ($turnstile_result === FALSE) {
        $response['message'] = "无法连接到 Turnstile 验证服务，请检查网络连接或稍后再试。";
        echo json_encode($response);
        exit();
    }

    $turnstile_verification = json_decode($turnstile_result);
    if (!$turnstile_verification->success) {
        $response['message'] = "验证码验证失败，请重新尝试。";
        echo json_encode($response);
        exit();
    }

    // 如果验证码通过，继续验证用户名和密码
    $stmt = $conn->prepare("SELECT id, username, password, register_time, level FROM users WHERE username = ?");
    if (!$stmt) {
        $response['message'] = "数据库查询准备失败: " . $conn->error;
        echo json_encode($response);
        exit();
    }
    $stmt->bind_param("s", $username);
    if (!$stmt->execute()) {
        $response['message'] = "数据库查询执行失败: " . $stmt->error;
        $stmt->close();
        echo json_encode($response);
        exit();
    }
    $stmt->store_result();
    $stmt->bind_result($id, $db_username, $hashed_password, $register_time, $current_level);
    $stmt->fetch();

    if ($stmt->num_rows > 0 && password_verify($password, $hashed_password)) {
        // 如果用户已经是等级 4，跳过等级更新
        if ($current_level == 4) {
            $level = 4;
        } else {
            // 计算等级，将 created_at 替换为 register_time
            try {
                $registration_date = new DateTime($register_time);
                $now = new DateTime();
                $interval = $registration_date->diff($now);

                if ($interval->m >= 6) {
                    $level = 3; // 6 个月到 1 年
                } elseif ($interval->m >= 1) {
                    $level = 2; // 1 个月到 6 个月
                } else {
                    $level = 1; // 不足 1 个月
                }
            } catch (Exception $e) {
                $response['message'] = "日期计算出错: " . $e->getMessage();
                $stmt->close();
                echo json_encode($response);
                exit();
            }
        }

        // 更新等级到数据库
        if ($level != $current_level) {
            $update_stmt = $conn->prepare("UPDATE users SET level = ? WHERE id = ?");
            if (!$update_stmt) {
                $response['message'] = "数据库更新准备失败: " . $conn->error;
                $stmt->close();
                echo json_encode($response);
                exit();
            }
            $update_stmt->bind_param("ii", $level, $id);
            if (!$update_stmt->execute()) {
                $response['message'] = "数据库更新执行失败: " . $update_stmt->error;
                $update_stmt->close();
                $stmt->close();
                echo json_encode($response);
                exit();
            }
            $update_stmt->close();
        }

        // 存储用户信息到会话
        $_SESSION['user_id'] = $id;
        $_SESSION['username'] = $db_username;

        // 生成 Token
        $token = bin2hex(random_bytes(32)); // 生成一个唯一的 Token

        // 将 Token 存储到数据库
        $stmt = $conn->prepare("UPDATE users SET token = ? WHERE id = ?");
        if (!$stmt) {
            $response['message'] = "数据库更新 Token 准备失败: " . $conn->error;
            echo json_encode($response);
            exit();
        }
        $stmt->bind_param("si", $token, $id);
        if (!$stmt->execute()) {
            $response['message'] = "数据库更新 Token 执行失败: " . $stmt->error;
            $stmt->close();
            echo json_encode($response);
            exit();
        }

        // 设置 Token 到 Cookie
        setcookie('auth_token', $token, time() + 3600, '/', '', false, true); // 设置 Cookie，有效期为 1 小时

        // 登录成功
        $response['success'] = true;
        $response['message'] = "登录成功";
        echo json_encode($response);
        exit();
    } else {
        $response['message'] = "用户名或密码错误，请重新输入。";
        echo json_encode($response);
        exit();
    }

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