<?php
define('IN_PHPBB', true);

$phpbb_root_path = '../../../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);

$user->session_begin();
$auth->acl($user->data);

// 获取用户名
$username = $request->variable('username', '', true);

header('Content-Type: application/json');

if (!$username) {
    echo json_encode(['success' => false, 'error' => 'No username provided']);
    exit;
}

// 查询用户信息（使用 username_clean 进行精确匹配）
$sql = 'SELECT user_id, username, user_avatar, user_avatar_type, user_avatar_width, user_avatar_height
        FROM ' . USERS_TABLE . " WHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'";
$res = $db->sql_query($sql);
$row = $db->sql_fetchrow($res);
$db->sql_freeresult($res);

// 如果精确匹配没找到，尝试模糊匹配（去掉空格）
if (!$row) {
    $sql = 'SELECT user_id, username, user_avatar, user_avatar_type, user_avatar_width, user_avatar_height
            FROM ' . USERS_TABLE . " WHERE username_clean LIKE '%" . $db->sql_escape(utf8_clean_string($username)) . "%' LIMIT 1";
    $res = $db->sql_query($sql);
    $row = $db->sql_fetchrow($res);
    $db->sql_freeresult($res);
}

if (!$row) {
    echo json_encode([
        'success' => false, 
        'error' => "User '$username' not found",
        'avatar_url' => './styles/artery_2026/theme/images/no_avatar.png',
        'user_id' => 0
    ]);
    exit;
}

// ==============================================
// 获取纯头像 URL
// ==============================================
$avatar_url = '';

if (!empty($row['user_avatar'])) {
    $avatar_type = $row['user_avatar_type'];
    $avatar = $row['user_avatar'];
    
    if ($avatar_type == 'avatar.driver.upload') {
        // 上传的头像
        $avatar_url = $phpbb_root_path . 'download/file.php?avatar=' . $avatar;
    } elseif ($avatar_type == 'avatar.driver.remote') {
        // 远程头像
        $avatar_url = $avatar;
    } elseif ($avatar_type == 'avatar.driver.gravatar') {
        // Gravatar
        $avatar_url = $avatar;
    } elseif ($avatar_type == 'avatar.driver.local') {
        // 本地头像
        $avatar_url = $phpbb_root_path . 'images/avatars/' . $avatar;
    }
}

// 如果没有头像，使用默认头像
if (empty($avatar_url)) {
    $style_path = $user->style['style_path'];
    $avatar_url = "./styles/artery_2026/theme/images/no_avatar.png";
}

// 清理路径
$avatar_url = str_replace('../../../', '', $avatar_url);
$avatar_url = str_replace('//', '/', $avatar_url);

// 确保路径正确
if (strpos($avatar_url, 'http') !== 0 && strpos($avatar_url, '/') !== 0) {
    $avatar_url = './' . ltrim($avatar_url, './');
}

echo json_encode([
    'success' => true,
    'avatar_url' => $avatar_url,
    'user_id' => (int)$row['user_id'],
    'username' => $row['username']
]);
exit;
?>