<?php
ob_start();
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/lhouath_config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

$config = getLhouathConfig();

session_start();

$state = $_GET['state'] ?? '';
if ($state !== ($_SESSION['lhouath_state'] ?? '')) die('State 验证失败');
unset($_SESSION['lhouath_state']);

$code = $_GET['code'] ?? '';
if (empty($code)) die('授权失败');

$ch = curl_init('https://open.lhwks.cn/token.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'grant_type'    => 'authorization_code',
    'code'          => $code,
    'client_id'     => $config['app_id'],
    'client_secret' => $config['app_secret'],
    'redirect_uri'  => $config['redirect_uri'],
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'] ?? '';
if (empty($accessToken)) die('Token 获取失败');

$ch = curl_init('https://open.lhwks.cn/userinfo.php?access_token=' . urlencode($accessToken));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$userInfo = json_decode(curl_exec($ch), true);
curl_close($ch);

if (empty($userInfo['openid'])) die('用户信息获取失败');

$openid = $userInfo['openid'];
$nickname = $userInfo['nickname'] ?? '麟泓用户';
$avatar = $userInfo['avatar'] ?? '';
if ($avatar && strpos($avatar, 'http') !== 0) $avatar = 'https://open.lhwks.cn' . $avatar;
$email = $userInfo['email'] ?? '';
$username_from_api = $userInfo['username'] ?? '';

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

// ========== 1. 通过 lhouath openid 查找 ==========
$existing = $db->fetchOne("SELECT * FROM users WHERE union_id = '$openid' AND union_type = 'lhouath'");

// ========== 2. 通过 OAuth 绑定表查找 ==========
if (!$existing) {
    $b = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = 'lhouath' AND openid = '$openid'");
    if ($b) $existing = $db->fetchOne("SELECT * FROM users WHERE id = {$b['user_id']}");
}

// ========== 3. 通过邮箱查找并自动绑定 ==========
if (!$existing && !empty($email)) {
    $existing = $db->fetchOne("SELECT * FROM users WHERE email = '$email'");
    if ($existing) {
        // 自动绑定
        $db->query("UPDATE users SET union_id = '$openid', union_type = 'lhouath', avatar_url = '$avatar' WHERE id = {$existing['id']}");
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ({$existing['id']}, 'lhouath', '$openid', '$nickname', '$avatar')
                    ON DUPLICATE KEY UPDATE nickname = '$nickname', avatar = '$avatar'");
    }
}

// ========== 4. 通过用户名查找并自动绑定 ==========
if (!$existing && !empty($username_from_api)) {
    $existing = $db->fetchOne("SELECT * FROM users WHERE username = '$username_from_api'");
    if ($existing) {
        $db->query("UPDATE users SET union_id = '$openid', union_type = 'lhouath', avatar_url = '$avatar' WHERE id = {$existing['id']}");
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                    VALUES ({$existing['id']}, 'lhouath', '$openid', '$nickname', '$avatar')
                    ON DUPLICATE KEY UPDATE nickname = '$nickname', avatar = '$avatar'");
    }
}

// ========== 已存在用户，直接登录 ==========
if ($existing) {
    clearLoginFail($ip);
    $_SESSION['user_id'] = $existing['id'];
    $_SESSION['username'] = $existing['username'];
    $_SESSION['role'] = $existing['role'];
    if ($avatar) $db->query("UPDATE users SET avatar_url = '$avatar' WHERE id = {$existing['id']}");
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

// ========== 创建新用户 ==========
$username = $nickname;
if ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) $username = 'lh_' . $openid;
$hashed = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
$db->query("INSERT INTO users (username, password, email, union_id, union_type, avatar_url, role, status, is_oauth_user, need_change_password) VALUES ('$username', '$hashed', '$email', '$openid', 'lhouath', '$avatar', 'user', 1, 1, 0)");
$uid = $db->insertId();
if ($uid) {
    $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) VALUES ($uid, 'lhouath', '$openid', '$nickname', '$avatar')");
    $_SESSION['user_id'] = $uid;
    $_SESSION['username'] = $username;
    $_SESSION['role'] = 'user';
    $_SESSION['should_change_password'] = true;
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}
die('登录失败');