<?php
ob_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/oauth_helper.php';
session_start();

// 从数据库获取配置
$app_id = getSiteConfig('oauth_qq_app_id');
$app_key = getSiteConfig('oauth_qq_app_key');
$callback = SITE_URL . 'api/qq_callback.php';

// 验证 state
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

if (empty($code)) {
    die('授权失败：未获取到授权码');
}

if ($state !== ($_SESSION['qq_state'] ?? '')) {
    die('授权失败：state 验证失败');
}
unset($_SESSION['qq_state']);

// 获取 access_token
$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={$app_id}&client_secret={$app_key}&code={$code}&redirect_uri=" . urlencode($callback);
$response = file_get_contents($token_url);

parse_str($response, $token_data);
$access_token = $token_data['access_token'] ?? '';

if (empty($access_token)) {
    die('获取 access_token 失败');
}

// 获取 openid
$openid_url = "https://graph.qq.com/oauth2.0/me?access_token={$access_token}";
$response = file_get_contents($openid_url);

if (preg_match('/callback\s*\(\s*(.+)\s*\)\s*;/', $response, $matches)) {
    $json = json_decode($matches[1], true);
    $openid = $json['openid'] ?? '';
} else {
    die('获取 openid 失败');
}

if (empty($openid)) {
    die('获取 openid 失败');
}

// 获取用户信息
$user_url = "https://graph.qq.com/user/get_user_info?access_token={$access_token}&oauth_consumer_key={$app_id}&openid={$openid}";
$response = file_get_contents($user_url);
$user_info = json_decode($response, true);

if ($user_info['ret'] != 0) {
    die('获取用户信息失败：' . ($user_info['msg'] ?? '未知错误'));
}

$nickname = $user_info['nickname'];
$avatar = $user_info['figureurl_qq_2'] ?: $user_info['figureurl_qq_1'];

// ========== 判断是绑定还是登录 ==========
if (isset($_SESSION['qq_bind']) && $_SESSION['qq_bind'] === true) {
    // 绑定模式
    $bind_user_id = $_SESSION['qq_bind_user_id'] ?? 0;
    unset($_SESSION['qq_bind'], $_SESSION['qq_bind_user_id']);
    
    if ($bind_user_id <= 0) {
        die('绑定失败：用户信息丢失');
    }
    
    // 检查是否已被其他账号绑定
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = 'qq' AND openid = '{$openid}'");
    if ($existing) {
        die('该 QQ 账号已被其他用户绑定');
    }
    
    // 检查当前用户是否已绑定 QQ
    $user_bound = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE user_id = {$bind_user_id} AND oauth_type = 'qq'");
    if ($user_bound) {
        // 更新绑定信息
        $db->query("UPDATE user_oauth_bindings SET openid = '{$openid}', nickname = '" . addslashes($nickname) . "', avatar = '" . addslashes($avatar) . "' WHERE user_id = {$bind_user_id} AND oauth_type = 'qq'");
    } else {
        // 插入绑定信息
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar, created_at) VALUES ({$bind_user_id}, 'qq', '{$openid}', '" . addslashes($nickname) . "', '" . addslashes($avatar) . "', NOW())");
    }
    
    header('Location: /admin.php?page=profile&bind_success=qq');
    exit;
} else {
    // 登录模式
    oauth_login('qq', $openid, $nickname, $avatar);
}