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

if (!isset($conn)) {
    die("连接失败：\$conn 未定义");
}

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

    // 查询用户
    $stmt = $conn->prepare("SELECT id, username, password, created_at, level FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $username, $hashed_password, $created_at, $current_level);
    $stmt->fetch();

    if ($stmt->num_rows > 0 && password_verify($password, $hashed_password)) {
        // 如果用户已经是等级5，跳过等级更新
        if ($current_level == 4) {
            $level = 4;
        } else {
            // 计算等级
            $registration_date = new DateTime($created_at);
            $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个月
            }
        }

        // 更新等级到数据库
        if ($level != $current_level) {
            $update_stmt = $conn->prepare("UPDATE users SET level = ? WHERE id = ?");
            $update_stmt->bind_param("ii", $level, $id);
            $update_stmt->execute();
            $update_stmt->close();
        }

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

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

        // 将 Token 存储到数据库
        $stmt = $conn->prepare("UPDATE users SET token = ? WHERE id = ?");
        $stmt->bind_param("si", $token, $id);
        $stmt->execute();

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

        // 跳转到控制台页面并附加参数
        header("Location: ../console/index.php?login=success");
        exit();
    } else {
        echo "用户名或密码错误，请重新输入。";
    }

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