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

session_start();

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

// 从数据库获取配置
$client_id = getSiteConfig('oauth_gitee_client_id');
$client_secret = getSiteConfig('oauth_gitee_client_secret');
$callback = SITE_URL . 'api/gitee_callback.php';

if (empty($client_id) || empty($client_secret)) {
    die('Gitee登录未配置，请联系管理员');
}

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

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

// 跳转到 Gitee 授权
$auth_url = 'https://gitee.com/oauth/authorize?' . http_build_query([
    'client_id' => $client_id,
    'redirect_uri' => $callback,
    'response_type' => 'code',
    'state' => $state
]);

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