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

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

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

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

// 获取 access_token
$token_url = 'https://gitee.com/oauth/token';
$token_data = [
    'grant_type' => 'authorization_code',
    'code' => $code,
    'client_id' => GITEE_CLIENT_ID,
    'client_secret' => GITEE_CLIENT_SECRET,
    'redirect_uri' => GITEE_REDIRECT_URI
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$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);
$user_response = curl_exec($ch);
curl_close($ch);

$gitee_user = json_decode($user_response, true);

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

$gitee_id = $gitee_user['id'];
$gitee_name = $gitee_user['login'];
$gitee_email = $gitee_user['email'] ?? '';
$avatar_url = $gitee_user['avatar_url'] ?? '';

$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

// ========== 判断是绑定还是登录 ==========
$is_bind = isset($_SESSION['gitee_bind']) && $_SESSION['gitee_bind'] === true;
$bind_user_id = $_SESSION['gitee_bind_user_id'] ?? 0;

if ($is_bind && $bind_user_id > 0) {
    // 绑定操作：将第三方账号绑定到已有用户
    unset($_SESSION['gitee_bind']);
    unset($_SESSION['gitee_bind_user_id']);
    
    // 检查是否已绑定其他账号
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = 'gitee' AND openid = '$gitee_id'");
    if ($existing) {
        die('该Gitee账号已被其他用户绑定');
    }
    
    // 检查是否已绑定同类型
    $bound = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE user_id = $bind_user_id AND oauth_type = 'gitee'");
    if ($bound) {
        // 已绑定，更新信息
        $db->query("UPDATE user_oauth_bindings SET openid = '$gitee_id', nickname = '$gitee_name', avatar = '$avatar_url' WHERE id = {$bound['id']}");
    } else {
        // 新增绑定
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ($bind_user_id, 'gitee', '$gitee_id', '$gitee_name', '$avatar_url')");
    }
    
    // 更新 users 表的 gitee 相关字段
    $db->query("UPDATE users SET gitee_id = '$gitee_id', gitee_name = '$gitee_name', avatar_url = '$avatar_url' 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, 'Gitee');
    }
    
    header('Location: ' . SITE_URL . 'admin.php?page=profile');
    exit;
}
// ========== 绑定结束 ==========

// ========== 查询用户是否已绑定 Gitee ==========
$user = $db->fetchOne("SELECT * FROM users WHERE gitee_id = '$gitee_id'");

// 同时查询绑定表
if (!$user) {
    $binding = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = 'gitee' AND openid = '$gitee_id'");
    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;
}

// 检查邮箱是否已被注册（如果 Gitee 提供了邮箱）
if (!empty($gitee_email)) {
    $existing_user = $db->fetchOne("SELECT * FROM users WHERE email = '$gitee_email'");
    if ($existing_user) {
        // 邮箱已存在，绑定 Gitee 账号到现有用户
        clearLoginFail($ip);
        
        $db->query("UPDATE users SET gitee_id = '$gitee_id', gitee_name = '$gitee_name', avatar_url = '$avatar_url' WHERE id = {$existing_user['id']}");
        
        // 记录到绑定表
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ({$existing_user['id']}, 'gitee', '$gitee_id', '$gitee_name', '$avatar_url')");
        
        $_SESSION['user_id'] = $existing_user['id'];
        $_SESSION['username'] = $existing_user['username'];
        $_SESSION['role'] = $existing_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($existing_user['email']) && ($existing_user['email_notify'] ?? 1)) {
            sendLoginAlert($existing_user, $ip, $city, $device, $login_time);
        }
        
        $db->query("INSERT INTO user_login_log (user_id, ip, city, device, user_agent) 
                    VALUES ({$existing_user['id']}, '$ip', '$city', '$device', '" . addslashes($user_agent) . "')");
        
        header('Location: ' . SITE_URL . 'admin.php');
        exit;
    }
}

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

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

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

// 将用户信息存入 Session，不写入数据库
$_SESSION['temp_oauth_user'] = [
    'oauth_type' => 'gitee',
    'openid' => $gitee_id,
    'nickname' => $gitee_name,
    'username' => $username,
    'email' => $email,
    'avatar' => $avatar_url,
    'gitee_id' => $gitee_id,
    'gitee_name' => $gitee_name
];

// 跳转到设置密码页面
header('Location: ' . SITE_URL . 'modules/user/force_change_password.php');
exit;