<?php
function normalizeAvatarUrl(?string $photoUrl, string $fallback = 'assets/images/100x100.jpg'): string
{
    $raw = trim((string)$photoUrl);
    if ($raw === '') {
        return $fallback;
    }

    if (preg_match('/^https?:\/\//i', $raw)) {
        return $raw;
    }

    if (strpos($raw, '/') === 0) {
        return $raw;
    }

    if (strpos($raw, 'assets/') === 0) {
        return $raw;
    }

    return $fallback;
}

function resolveUserAvatarUrl(PDO $pdo, int $userId, string $fallback = 'assets/images/100x100.jpg'): string
{
    if ($userId <= 0) {
        return $fallback;
    }

    $stmt = $pdo->prepare("SELECT photo_url FROM user_profiles WHERE user_id = :uid LIMIT 1");
    $stmt->execute([':uid' => $userId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $photoUrl = $row['photo_url'] ?? '';
    return normalizeAvatarUrl($photoUrl, $fallback);
}
