<?php
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';

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

$code = $_GET['code'] ?? '';

if (empty($code)) {
    die('授权码不存在');
}

// ========== 第一步：获取 access_token ==========
$token_url = 'https://graph.qq.com/oauth2.0/token';
$token_params = [
    'grant_type' => 'authorization_code',
    'client_id' => QQ_APP_ID,
    'client_secret' => QQ_APP_KEY,
    'code' => $code,
    'redirect_uri' => QQ_REDIRECT_URI
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url . '?' . http_build_query($token_params));
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 ==========
$openid_url = 'https://graph.qq.com/oauth2.0/me?access_token=' . $access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $openid_url);
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 失败');
}

// ========== 第三步：获取用户信息 ==========
$userinfo_url = 'https://graph.qq.com/user/get_user_info';
$userinfo_params = [
    'access_token' => $access_token,
    'oauth_consumer_key' => QQ_APP_ID,
    'openid' => $openid
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $userinfo_url . '?' . http_build_query($userinfo_params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$userinfo_response = curl_exec($ch);
curl_close($ch);

$qq_user = json_decode($userinfo_response, true);
$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']);
    unset($_SESSION['qq_bind_user_id']);
    
    // 检查该 QQ 是否已被其他用户绑定
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = 'qq' AND openid = '$openid'");
    if ($existing) {
        die('该QQ账号已被其他用户绑定');
    }
    
    // 检查当前用户是否已绑定 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')");
    }
    
    // 更新 users 表
    $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;
}

// ========== 登录模式：查询用户是否已绑定 QQ ==========
$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;
}

// ========== 新用户：不写入数据库，只存 Session ==========
$username = $nickname;
$original_username = $username;
$counter = 1;

while ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) {
    $username = $original_username . $counter;
    $counter++;
}

$email = $openid . '@qq.oauth.user';
// 检查邮箱是否已被占用
$email_check = $db->fetchOne("SELECT id FROM users WHERE email = '$email'");
if ($email_check) {
    $email = $openid . '_' . time() . '@qq.oauth.user';
}

// 将用户信息存入 Session，不写入数据库
$_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;