<?php
ob_start();
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/qq_config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/mail_helper.php';

$config = getQQConfig();

// 验证 state
if (!isset($_GET['state']) || $_GET['state'] !== ($_SESSION['qq_state'] ?? '')) {
    die('State 验证失败，请重试');
}

$code = $_GET['code'] ?? '';
if (empty($code)) die('授权码不存在');

// 获取 access_token
$ch = curl_init('https://graph.qq.com/oauth2.0/token?' . http_build_query([
    'grant_type'    => 'authorization_code',
    'client_id'     => $config['app_id'],
    'client_secret' => $config['app_key'],
    'code'          => $code,
    'redirect_uri'  => $config['redirect_uri'],
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

parse_str($response, $token_arr);
$access_token = $token_arr['access_token'] ?? '';
if (empty($access_token)) die('获取 access_token 失败');

// 获取 OpenID
$ch = curl_init('https://graph.qq.com/oauth2.0/me?access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$openid_response = curl_exec($ch);
curl_close($ch);

preg_match('/\{[^}]+\}/', $openid_response, $matches);
$openid_data = json_decode($matches[0] ?? '', true);
$openid = $openid_data['openid'] ?? '';
if (empty($openid)) die('获取 OpenID 失败');

// 获取用户信息
$ch = curl_init('https://graph.qq.com/user/get_user_info?' . http_build_query([
    'access_token'       => $access_token,
    'oauth_consumer_key' => $config['app_id'],
    'openid'             => $openid
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$qq_user = json_decode(curl_exec($ch), true);
curl_close($ch);

$nickname = $qq_user['nickname'] ?? 'QQ用户';
$avatar = $qq_user['figureurl_qq_2'] ?? ($qq_user['figureurl_qq_1'] ?? '');
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

// 绑定模式
$is_bind = isset($_SESSION['qq_bind']) && $_SESSION['qq_bind'] === true;
$bind_user_id = $_SESSION['qq_bind_user_id'] ?? 0;

if ($is_bind && $bind_user_id > 0) {
    unset($_SESSION['qq_bind'], $_SESSION['qq_bind_user_id']);
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = 'qq' AND openid = '$openid'");
    if ($existing) die('该QQ账号已被其他用户绑定');
    $bound = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE user_id = $bind_user_id AND oauth_type = 'qq'");
    if ($bound) {
        $db->query("UPDATE user_oauth_bindings SET openid = '$openid', nickname = '$nickname', avatar = '$avatar' WHERE id = {$bound['id']}");
    } else {
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) VALUES ($bind_user_id, 'qq', '$openid', '$nickname', '$avatar')");
    }
    $db->query("UPDATE users SET union_id = '$openid', union_type = 'qq', avatar_url = '$avatar' WHERE id = $bind_user_id");
    $user_info = $db->fetchOne("SELECT * FROM users WHERE id = $bind_user_id");
    if ($user_info && !empty($user_info['email']) && ($user_info['email_notify'] ?? 1)) {
        sendOauthBindNotification($user_info, 'QQ');
    }
    header('Location: ' . SITE_URL . 'admin.php?page=profile');
    exit;
}

// 登录模式
$user = $db->fetchOne("SELECT * FROM users WHERE union_id = '$openid' AND union_type = 'qq'");
if (!$user) {
    $binding = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = 'qq' AND openid = '$openid'");
    if ($binding) $user = $db->fetchOne("SELECT * FROM users WHERE id = {$binding['user_id']}");
}

if ($user) {
    clearLoginFail($ip);
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $login_time = date('Y-m-d H:i:s');
    $device_info = getDetailedDeviceInfo($user_agent);
    $device = $device_info['full'];
    $city = getIPCity($ip);
    if (!empty($user['email']) && ($user['email_notify'] ?? 1)) {
        sendLoginAlert($user, $ip, $city, $device, $login_time);
    }
    $db->query("INSERT INTO user_login_log (user_id, ip, city, device, user_agent) VALUES ({$user['id']}, '$ip', '$city', '$device', '" . addslashes($user_agent) . "')");
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

// 新用户
$username = $nickname;
$original_username = $username;
$counter = 1;
while ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) {
    $username = $original_username . $counter++;
}
$email = $openid . '@qq.oauth.user';
if ($db->fetchOne("SELECT id FROM users WHERE email = '$email'")) {
    $email = $openid . '_' . time() . '@qq.oauth.user';
}
$_SESSION['temp_oauth_user'] = [
    'oauth_type' => 'qq', 'openid' => $openid, 'nickname' => $nickname,
    'username' => $username, 'email' => $email, 'avatar' => $avatar,
    'union_id' => $openid, 'union_type' => 'qq'
];
header('Location: ' . SITE_URL . 'modules/user/force_change_password.php');
exit;