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

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

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

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

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

// 获取 access_token
$token_url = 'https://gitee.com/oauth/token';
$post_data = http_build_query([
    'grant_type' => 'authorization_code',
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $callback,
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: Mozilla/5.0']);
$response = curl_exec($ch);
curl_close($ch);

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

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

// 获取用户信息
$user_url = "https://gitee.com/api/v5/user?access_token={$access_token}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $user_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: Mozilla/5.0']);
$response = curl_exec($ch);
curl_close($ch);

$user_info = json_decode($response, true);

if (!isset($user_info['id'])) {
    die('获取用户信息失败');
}

$openid = $user_info['id'];
$nickname = $user_info['name'] ?? $user_info['login'];
$avatar = $user_info['avatar_url'] ?? '';

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