<?php
/**
 * 飞书 OAuth 回调处理
 */
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/feishu_config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

session_start();

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

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

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

// 使用正确的 OAuth 2.0 接口获取 user_access_token
$token_url = 'https://open.feishu.cn/open-apis/oauth/v2/access_token';
$post_data = http_build_query([
    'grant_type' => 'authorization_code',
    'code' => $code,
    'app_id' => FEISHU_APP_ID,
    'app_secret' => FEISHU_APP_SECRET,
    'redirect_uri' => FEISHU_REDIRECT_URI
]);

$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_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$token_data = json_decode($response, true);

if (empty($token_data['access_token'])) {
    echo '<pre>';
    print_r($token_data);
    echo '</pre>';
    die('获取 access_token 失败');
}

$access_token = $token_data['access_token'];
$refresh_token = $token_data['refresh_token'] ?? '';
$open_id = $token_data['open_id'] ?? '';
$user_id = $token_data['user_id'] ?? '';

// 获取用户详细信息
$user_url = 'https://open.feishu.cn/open-apis/authen/v1/user_info';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $user_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $access_token
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$user_data = json_decode($response, true);

if (empty($user_data['data'])) {
    // 如果没有用户信息，至少用 open_id
    $feishu_id = $open_id ?: $user_id;
    $feishu_name = '飞书用户';
    $feishu_avatar = '';
    $feishu_email = '';
} else {
    $feishu_id = $user_data['data']['user_id'] ?? $open_id;
    $feishu_name = $user_data['data']['name'] ?? '飞书用户';
    $feishu_avatar = $user_data['data']['avatar']['avatar_240'] ?? '';
    $feishu_email = $user_data['data']['email'] ?? '';
}

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

if ($is_bind && $bind_user_id > 0) {
    // 绑定操作
    unset($_SESSION['feishu_bind']);
    unset($_SESSION['feishu_bind_user_id']);
    
    $existing = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE oauth_type = 'feishu' AND openid = '$feishu_id'");
    if ($existing) {
        die('该飞书账号已被其他用户绑定');
    }
    
    $bound = $db->fetchOne("SELECT id FROM user_oauth_bindings WHERE user_id = $bind_user_id AND oauth_type = 'feishu'");
    if ($bound) {
        $db->query("UPDATE user_oauth_bindings SET openid = '$feishu_id', nickname = '$feishu_name', avatar = '$feishu_avatar' WHERE id = {$bound['id']}");
    } else {
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ($bind_user_id, 'feishu', '$feishu_id', '$feishu_name', '$feishu_avatar')");
    }
    
    header('Location: ' . SITE_URL . 'admin.php?page=profile');
    exit;
}

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

if (!$user) {
    $binding = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = 'feishu' AND openid = '$feishu_id'");
    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;
}

// 检查邮箱是否已被注册
if (!empty($feishu_email)) {
    $existing_user = $db->fetchOne("SELECT * FROM users WHERE email = '$feishu_email'");
    if ($existing_user) {
        $db->query("UPDATE users SET feishu_id = '$feishu_id', feishu_name = '$feishu_name', avatar_url = '$feishu_avatar' WHERE id = {$existing_user['id']}");
        $_SESSION['user_id'] = $existing_user['id'];
        $_SESSION['username'] = $existing_user['username'];
        $_SESSION['role'] = $existing_user['role'];
        header('Location: ' . SITE_URL . 'admin.php');
        exit;
    }
}

// 创建新用户
$username = $feishu_name ?: 'feishu_' . substr($feishu_id, -8);
$original_username = $username;
$counter = 1;

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

$email = !empty($feishu_email) ? $feishu_email : $feishu_id . '@feishu.user';
$hashed_password = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);

$db->query("INSERT INTO users (username, password, email, feishu_id, feishu_name, avatar_url, email_verified, role) 
            VALUES ('$username', '$hashed_password', '$email', '$feishu_id', '$feishu_name', '$feishu_avatar', 1, 'user')");

$user_id = $db->insertId();

$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['role'] = 'user';

header('Location: ' . SITE_URL . 'admin.php');
exit;