<?php
// bd_action.php - 处理绑定操作
session_start();
require_once '../config.php';

header('Content-Type: application/json; charset=utf-8');

$action = $_POST['action'] ?? '';
$user_id = intval($_POST['user_id'] ?? 0);
$qq = trim($_POST['qq'] ?? '');

$response = ['status' => 'error', 'message' => '参数错误'];

if ($user_id <= 0 || empty($qq)) {
    echo json_encode($response);
    exit;
}

// 验证QQ号格式
if (!preg_match('/^[1-9][0-9]{4,10}$/', $qq)) {
    echo json_encode(['status' => 'error', 'message' => 'QQ号格式不正确']);
    exit;
}

switch ($action) {
    // 扫码登录
    case 'login':
        // 前端已经验证过QQ匹配，后端再次确认并执行登录
        $stmt = mysqli_prepare($conn, "SELECT id, username, qq, 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 && $user['qq'] === $qq) {
            $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');

            $response = ['status' => 'success', 'message' => '登录成功'];
        } else {
            $response['message'] = '验证失败，QQ号不匹配';
        }
        break;

    // 解除绑定
    case 'unbind':
        // 前端已验证，这里直接解绑
        $stmt = mysqli_prepare($conn, "SELECT qq 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 && $user['qq'] === $qq) {
            $update = mysqli_prepare($conn, "UPDATE users SET qq = '' WHERE id = ?");
            mysqli_stmt_bind_param($update, "i", $user_id);
            if (mysqli_stmt_execute($update)) {
                $response = ['status' => 'success', 'message' => '解绑成功'];
            } else {
                $response['message'] = '数据库错误';
            }
        } else {
            $response['message'] = '验证失败，QQ号不匹配';
        }
        break;

    // 更换绑定QQ (此时传来的 $qq 是新QQ)
    case 'change_qq':
        // 1. 检查新QQ是否已经被其他账号绑定
        $check = mysqli_prepare($conn, "SELECT id FROM users WHERE qq = ? AND id != ?");
        mysqli_stmt_bind_param($check, "si", $qq, $user_id);
        mysqli_stmt_execute($check);
        $check_res = mysqli_stmt_get_result($check);
        
        if (mysqli_num_rows($check_res) > 0) {
            $response['message'] = '操作失败：这个QQ号已经被其他账号绑定了';
            break;
        }

        // 2. 更新QQ号
        $update = mysqli_prepare($conn, "UPDATE users SET qq = ? WHERE id = ?");
        mysqli_stmt_bind_param($update, "si", $qq, $user_id);
        
        if (mysqli_stmt_execute($update)) {
            $response = ['status' => 'success', 'message' => '换绑成功'];
        } else {
            $response['message'] = '数据库更新失败';
        }
        break;

    default:
        $response['message'] = '未知操作';
        break;
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);
