<?php
/**
 * 彩虹聚合登录统一回调处理
 */
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

session_start();

// 验证 state
if (!isset($_GET['state']) || $_GET['state'] != ($_SESSION['Oauth_state'] ?? '')) {
    die('State 验证失败，请重新登录');
}

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

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

// 彩虹聚合登录配置
$union_config = [
    'apiurl' => 'http://u.im01.cn/',
    'appid' => '1012',
    'appkey' => '764dfa5343f3ed81155672cb7f7409f3',
    'callback' => SITE_URL . 'api/union_callback.php'
];

// 调用 API 获取用户信息
$api_url = $union_config['apiurl'] . 'connect.php?' . http_build_query([
    'act' => 'callback',
    'appid' => $union_config['appid'],
    'appkey' => $union_config['appkey'],
    'code' => $code
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

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

$social_uid = $result['social_uid'] ?? '';
$nickname = $result['nickname'] ?? '';
$avatar = $result['faceimg'] ?? '';

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

// 获取登录方式对应的显示名称
$oauth_names = [
    'qq' => 'QQ', 'wx' => '微信', 'alipay' => '支付宝', 'sina' => '微博',
    'baidu' => '百度', 'douyin' => '抖音', 'huawei' => '华为', 'xiaomi' => '小米',
    'google' => '谷歌', 'microsoft' => '微软', 'facebook' => 'Facebook', 'twitter' => 'Twitter'
];
$oauth_name = $oauth_names[$type] ?? $type;

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

if ($is_bind && $bind_user_id > 0) {
    // 绑定操作：将第三方账号绑定到已有用户
    unset($_SESSION['oauth_bind']);
    unset($_SESSION['oauth_bind_user_id']);
    
    // 检查是否已绑定其他账号
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = '$type' AND openid = '$social_uid'");
    if ($existing) {
        die('该第三方账号已被其他用户绑定');
    }
    
    // 检查是否已绑定同类型
    $bound = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE user_id = $bind_user_id AND oauth_type = '$type'");
    if ($bound) {
        // 已绑定，更新信息
        $db->query("UPDATE user_oauth_bindings SET openid = '$social_uid', nickname = '$nickname', avatar = '$avatar' WHERE id = {$bound['id']}");
    } else {
        // 新增绑定
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ($bind_user_id, '$type', '$social_uid', '$nickname', '$avatar')");
    }
    
    // 更新 users 表
    $db->query("UPDATE users SET union_id = '$social_uid', union_type = '$type', avatar_url = '$avatar' WHERE id = $bind_user_id");
    
    // 发送绑定通知邮件
    require_once dirname(__DIR__) . '/includes/mail_helper.php';
    $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, $oauth_name);
    }
    
    header('Location: ' . SITE_URL . 'admin.php?page=profile');
    exit;
}
// ========== 绑定结束 ==========

// ========== 查询用户是否已绑定 ==========
$user = $db->fetchOne("SELECT * FROM users WHERE union_id = '$social_uid' AND union_type = '$type'");

// 同时查询绑定表
if (!$user) {
    $binding = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = '$type' AND openid = '$social_uid'");
    if ($binding) {
        $user = $db->fetchOne("SELECT * FROM users WHERE id = {$binding['user_id']}");
    }
}

if ($user) {
    // 已绑定，直接登录
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    if (function_exists('clearLoginFail')) {
        clearLoginFail($ip);
    }
    
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

// ========== 新用户：不写入数据库，只存 Session ==========
// 检查昵称是否被占用
$username = $nickname ?: 'user_' . substr($social_uid, -8);
$original_username = $username;
$counter = 1;
while ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) {
    $username = $original_username . $counter;
    $counter++;
}

$email = $social_uid . '@union.user';
// 检查邮箱是否已被占用
$email_check = $db->fetchOne("SELECT id FROM users WHERE email = '$email'");
if ($email_check) {
    $email = $social_uid . '_' . time() . '@union.user';
}

// 将用户信息存入 Session，不写入数据库
$_SESSION['temp_oauth_user'] = [
    'oauth_type' => 'union',
    'union_type' => $type,
    'union_id' => $social_uid,
    'openid' => $social_uid,
    'nickname' => $nickname,
    'username' => $username,
    'email' => $email,
    'avatar' => $avatar,
    'oauth_name' => $oauth_name
];

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