<?php
// 开启 Session
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// 引入数据库配置
require_once '../config.php';
// 引入等级计算逻辑 (用于升级检测)
require_once 'level_check.php';

// 自动登录检测：如果未登录但有 Cookie，尝试自动登录
if (!isset($_SESSION['user_logged_in']) && isset($_COOKIE['remember_me_token'])) {
    $token = $_COOKIE['remember_me_token'];
    $stmt = mysqli_prepare($conn, "SELECT id, username, avatar, created_at FROM users WHERE token = ?");
    mysqli_stmt_bind_param($stmt, "s", $token);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);

    if ($user) {
        $_SESSION['user_logged_in'] = true;
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_username'] = $user['username'];
        $_SESSION['user_token'] = $token;
        $_SESSION['user_avatar'] = $user['avatar'] ?? '';
        $_SESSION['user_created_at'] = $user['created_at'] ?? '';
        $_SESSION['login_time'] = date('Y-m-d H:i:s');
    } else {
        // Token 无效，清除 Cookie
        setcookie('remember_me_token', '', time() - 3600, '/');
    }
}

header('Content-Type: application/json; charset=utf-8');
$response = ['status' => 'error', 'message' => '未知错误'];

$action = $_POST['action'] ?? '';

// 验证码检查函数
function check_captcha($code) {
    if (empty($code)) return '请输入验证码';
    if (!isset($_SESSION['vc_code'])) return '验证码已过期';
    if (strtolower($code) !== strtolower($_SESSION['vc_code'])) return '验证码错误';
    return true;
}

// 哈希函数
function fast_hash($password) {
    return password_hash($password, PASSWORD_DEFAULT, ['cost' => 8]);
}

try {
    switch ($action) {
        // =============== 登录 ===============
        case 'login':
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $code = trim($_POST['code'] ?? '');

            $check = check_captcha($code);
            if ($check !== true) {
                $response['message'] = $check;
                break;
            }

            if (empty($username) || empty($password)) {
                $response['message'] = '用户名和密码不能为空';
                break;
            }

            $stmt = mysqli_prepare($conn, "SELECT id, password, avatar, created_at FROM users WHERE username = ?");
            mysqli_stmt_bind_param($stmt, "s", $username);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            $user = mysqli_fetch_assoc($result);

            if ($user && password_verify($password, $user['password'])) {
                unset($_SESSION['vc_code']); 

                $new_token = bin2hex(random_bytes(16));
                $user_id = $user['id'];
                mysqli_query($conn, "UPDATE users SET token = '$new_token' WHERE id = $user_id");

                $_SESSION['user_logged_in'] = true;
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_username'] = $username;
                $_SESSION['user_token'] = $new_token;
                $_SESSION['user_avatar'] = $user['avatar'] ?? '';
                $_SESSION['user_created_at'] = $user['created_at'] ?? '';
                $_SESSION['login_time'] = date('Y-m-d H:i:s');

                // 设置持久化 Cookie (有效期 365 天)
                setcookie('remember_me_token', $new_token, time() + (86400 * 365), "/", "", false, true);

                $response = ['status' => 'success', 'message' => '登录成功'];
            } else {
                $response['message'] = '用户名或密码错误';
            }
            break;

        // =============== 注册 ===============
        case 'register':
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $qq = trim($_POST['qq'] ?? '');
            $code = trim($_POST['code'] ?? '');
            $avatar_data = $_POST['avatar_data'] ?? '';

            $check = check_captcha($code);
            if ($check !== true) {
                unset($_SESSION['vc_code']);
                $response['message'] = $check;
                break;
            }

            if (empty($username)) { $response['message'] = '用户名不能为空'; break; }
            if (strlen($password) < 6) { $response['message'] = '密码太短'; break; }
            if (empty($qq)) { $response['message'] = 'QQ号不能为空'; break; }

            // 检查QQ号注册数量限制 (最多5个)
            $count_stmt = mysqli_prepare($conn, "SELECT COUNT(*) as total FROM users WHERE qq = ?");
            mysqli_stmt_bind_param($count_stmt, "s", $qq);
            mysqli_stmt_execute($count_stmt);
            $count_res = mysqli_stmt_get_result($count_stmt);
            $count_row = mysqli_fetch_assoc($count_res);
            
            if ($count_row['total'] >= 5) {
                $response['message'] = '该QQ号绑定的账号数量已达上限(5个)';
                break;
            }

            // 检查用户名是否存在
            $check_user = mysqli_query($conn, "SELECT id FROM users WHERE username = '$username'");
            if (mysqli_num_rows($check_user) > 0) {
                $response['message'] = '用户名已存在';
                break;
            }

            // 处理头像上传
            $avatar_path = '';
            if (!empty($avatar_data)) {
                $upload_dir = '../uploads/avatars/';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
                
                $img = str_replace('data:image/png;base64,', '', $avatar_data);
                $img = str_replace('data:image/jpeg;base64,', '', $img);
                $img = str_replace(' ', '+', $img);
                $file_name = 'avatar_reg_' . time() . '.jpg';
                $file_path = $upload_dir . $file_name;
                
                if (file_put_contents($file_path, base64_decode($img))) {
                    $avatar_path = 'uploads/avatars/' . $file_name;
                }
            }

            $hash = fast_hash($password);
            $key = md5(uniqid());
            $init_token = bin2hex(random_bytes(16));

            $stmt = mysqli_prepare($conn, "INSERT INTO users (username, password, unique_key, qq, token, avatar) VALUES (?, ?, ?, ?, ?, ?)");
            mysqli_stmt_bind_param($stmt, "ssssss", $username, $hash, $key, $qq, $init_token, $avatar_path);
            
            if (mysqli_stmt_execute($stmt)) {
                $response = ['status' => 'success', 'message' => '注册成功'];
            } else {
                $response['message'] = '注册失败: ' . mysqli_error($conn);
            }
            break;

        // =============== QQ 扫码登录 ===============
        case 'qq_login':
            $qq = trim($_POST['qq'] ?? '');
            if (empty($qq)) {
                $response['message'] = 'QQ号为空';
                break;
            }

            $stmt = mysqli_prepare($conn, "SELECT id, username, avatar, created_at FROM users WHERE qq = ? ORDER BY id ASC");
            mysqli_stmt_bind_param($stmt, "s", $qq);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            
            $accounts = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $accounts[] = $row;
            }

            if (empty($accounts)) {
                $response['message'] = '该QQ未绑定账号，请先去注册';
            } elseif (count($accounts) === 1) {
                // 如果只有1个账号，直接登录
                $user = $accounts[0];
                $new_token = bin2hex(random_bytes(16));
                $user_id = $user['id'];
                mysqli_query($conn, "UPDATE users SET token = '$new_token' WHERE id = $user_id");

                $_SESSION['user_logged_in'] = true;
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_username'] = $user['username'];
                $_SESSION['user_token'] = $new_token;
                $_SESSION['user_avatar'] = $user['avatar'] ?? '';
                $_SESSION['user_created_at'] = $user['created_at'] ?? '';
                $_SESSION['login_time'] = date('Y-m-d H:i:s');

                setcookie('remember_me_token', $new_token, time() + (86400 * 365), "/", "", false, true);

                $response = ['status' => 'success', 'message' => '登录成功'];
            } else {
                // 如果有多于1个账号，返回账号列表
                $response = [
                    'status' => 'multi_accounts',
                    'message' => '检测到多个账号，请选择',
                    'accounts' => $accounts
                ];
            }
            break;

        // =============== 选择账号登录 ===============
        case 'select_account_login':
            $user_id = intval($_POST['user_id'] ?? 0);
            if ($user_id <= 0) {
                $response['message'] = '参数错误';
                break;
            }

            $stmt = mysqli_prepare($conn, "SELECT id, username, avatar, created_at FROM users WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $user_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            $user = mysqli_fetch_assoc($result);

            if ($user) {
                $new_token = bin2hex(random_bytes(16));
                mysqli_query($conn, "UPDATE users SET token = '$new_token' WHERE id = $user_id");

                $_SESSION['user_logged_in'] = true;
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_username'] = $user['username'];
                $_SESSION['user_token'] = $new_token;
                $_SESSION['user_avatar'] = $user['avatar'] ?? '';
                $_SESSION['user_created_at'] = $user['created_at'] ?? '';
                $_SESSION['login_time'] = date('Y-m-d H:i:s');

                setcookie('remember_me_token', $new_token, time() + (86400 * 365), "/", "", false, true);

                $response = ['status' => 'success', 'message' => '登录成功'];
            } else {
                $response['message'] = '用户不存在';
            }
            break;

        // =============== 修改昵称 (含扣费与升级) ===============
        case 'change_username':
            if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
                $response['message'] = '请先登录';
                break;
            }

            $new_name = trim($_POST['username'] ?? '');
            $user_id = $_SESSION['user_id'];
            $cost = 15; // 扣费金额

            // 1. 基础验证
            if (empty($new_name)) {
                $response['message'] = '昵称不能为空';
                break;
            }
            if (mb_strlen($new_name, 'utf-8') > 12) {
                $response['message'] = '昵称太长了，不能超过12个字';
                break;
            }

            // 2. 获取当前用户信息
            $stmt_bal = mysqli_prepare($conn, "SELECT coins, username FROM users WHERE id = ?");
            mysqli_stmt_bind_param($stmt_bal, "i", $user_id);
            mysqli_stmt_execute($stmt_bal);
            $res_bal = mysqli_stmt_get_result($stmt_bal);
            $user_bal = mysqli_fetch_assoc($res_bal);
            $current_coins = $user_bal['coins'];
            $current_name = $user_bal['username'];

            // 3. 检查是否和原昵称一致
            if ($new_name === $current_name) {
                $response['message'] = '新昵称与原昵称一致，无需修改';
                break;
            }

            // 4. 余额验证
            if ($current_coins < $cost) {
                $response['message'] = "小马币不足，修改昵称需要 {$cost} 个币";
                break;
            }

            // 5. 重名验证
            $stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE username = ? AND id != ?");
            mysqli_stmt_bind_param($stmt, "si", $new_name, $user_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            
            if (mysqli_num_rows($result) > 0) {
                $response['message'] = '这个昵称已经被别人用了，换一个吧';
                break;
            }

            // 6. 执行扣费和改名 (事务处理)
            mysqli_begin_transaction($conn);
            try {
                // 扣费并改名
                $new_coins = $current_coins - $cost;
                $update = mysqli_prepare($conn, "UPDATE users SET coins = ?, username = ? WHERE id = ?");
                mysqli_stmt_bind_param($update, "isi", $new_coins, $new_name, $user_id);
                mysqli_stmt_execute($update);

                // 写入消费日志
                $log_desc = '修改昵称消费';
                $stmt_log = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, change_amount, balance_after, type, description) VALUES (?, ?, ?, 'consume', ?)");
                $change_amount = -$cost;
                mysqli_stmt_bind_param($stmt_log, "iiis", $user_id, $change_amount, $new_coins, $log_desc);
                mysqli_stmt_execute($stmt_log);

                mysqli_commit($conn);

                $_SESSION['user_username'] = $new_name; 
                
                // --- 检测升级 ---
                $new_lv = checkAndUpdateLevel($user_id, $conn);
                
                $response = ['status' => 'success', 'message' => '修改成功', 'coins' => $new_coins];
                if ($new_lv) { $response['level_up'] = $new_lv; }

            } catch (Exception $e) {
                mysqli_rollback($conn);
                $response['message'] = '系统错误，请稍后重试';
            }
            break;

        default:
            $response['message'] = '无效请求';
            break;
    }
} catch (Exception $e) {
    $response['message'] = '系统异常: ' . $e->getMessage();
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
