<?php
/**
 * OAuth 登录辅助函数
 */

function oauth_login($type, $openid, $nickname, $avatar) {
    global $db;
    
    // 根据登录类型确定字段
    if ($type == 'qq') {
        $field = 'qq_id';
        $name_field = 'qq_name';
    } elseif ($type == 'gitee') {
        $field = 'gitee_id';
        $name_field = 'gitee_name';
    } elseif ($type == 'feishu') {
        $field = 'feishu_id';
        $name_field = 'feishu_name';
    } else {
        // 其他类型存在 union_id 字段
        $field = 'union_id';
        $name_field = 'union_name';
    }
    
    // 检查是否已绑定
    $user = $db->fetchOne("SELECT * FROM users WHERE {$field} = '{$openid}'");
    
    if ($user) {
        // 已绑定，直接登录
        if ($user['status'] == 0) {
            die('您的账号已被禁用，请联系管理员');
        }
        
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        
        // 更新最后登录时间
        // $db->query("UPDATE users SET last_login = NOW() WHERE id = {$user['id']}");
        
        header('Location: /admin.php');
        exit;
    }
    
    // 未绑定，创建新账号
    $username = generateUniqueUsername($nickname);
    $email = ''; // OAuth 可能没有邮箱
    $password = password_hash(uniqid(), PASSWORD_DEFAULT);
    
    // 如果是 QQ 或 Gitee，需要处理 avatar 字段
    $avatar_sql = '';
    if ($type == 'qq') {
        $avatar_sql = ", avatar = '" . addslashes($avatar) . "'";
    }
    
    $db->query("INSERT INTO users (username, email, password, {$field}, {$name_field}, role, status, created_at{$avatar_sql}) 
                VALUES ('{$username}', '', '{$password}', '{$openid}', '" . addslashes($nickname) . "', 'user', 1, NOW())");
    
    $user_id = $db->insertId();
    
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $username;
    $_SESSION['role'] = 'user';
    
    header('Location: /admin.php');
    exit;
}

function generateUniqueUsername($nickname) {
    global $db;
    
    // 清理昵称
    $base = preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '', $nickname);
    if (empty($base)) {
        $base = 'user';
    }
    
    $username = $base;
    $i = 1;
    
    while (true) {
        $check = $db->fetchOne("SELECT id FROM users WHERE username = '{$username}'");
        if (!$check) {
            return $username;
        }
        $username = $base . '_' . $i;
        $i++;
    }
}