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

// 从数据库获取配置
$api_url = getSiteConfig('oauth_union_api_url');
$app_id = getSiteConfig('oauth_union_app_id');
$app_key = getSiteConfig('oauth_union_app_key');

// 获取回调参数
$code = $_GET['code'] ?? '';

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

// 获取 access_token 和用户信息
$request_url = $api_url . 'connect.php?act=callback&appid=' . $app_id . '&appkey=' . $app_key . '&code=' . $code;

$response = file_get_contents($request_url);
$user_info = json_decode($response, true);

if (!isset($user_info['code']) || $user_info['code'] != 0) {
    die('登录失败：' . ($user_info['msg'] ?? '未知错误'));
}

$data = $user_info['data'] ?? [];
$openid = $data['openid'] ?? '';
$nickname = $data['nickname'] ?? '用户';
$avatar = $data['avatar'] ?? '';
$type = $data['type'] ?? '';

if (empty($openid)) {
    die('获取用户信息失败');
}

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