<?php
ob_start();
require_once dirname(__DIR__) . '/config.php';

session_start();

// 检查登录
if (!isLoggedIn()) {
    header('Location: ' . SITE_URL . 'modules/home/login.php');
    exit;
}

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

if (empty($app_id) || empty($app_key)) {
    die('QQ登录未配置，请联系管理员');
}

// 保存绑定标记
$_SESSION['qq_bind'] = true;
$_SESSION['qq_bind_user_id'] = $_SESSION['user_id'];

// 生成 state
$state = bin2hex(random_bytes(16));
$_SESSION['qq_state'] = $state;

// 构建授权 URL
$auth_url = 'https://graph.qq.com/oauth2.0/authorize?' . http_build_query([
    'response_type' => 'code',
    'client_id' => $app_id,
    'redirect_uri' => $callback,
    'state' => $state,
    'scope' => 'get_user_info'
]);

header('Location: ' . $auth_url);
exit;