<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Storage;

class ImageHelper
{
    /**
     * Get the public URL for an image path stored in public disk
     */
    public static function url(?string $path): ?string
    {
        if (!$path) {
            return null;
        }

        // If already a full URL, return as is
        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            return $path;
        }

        // Use Storage::url() which handles the public disk correctly
        try {
            return Storage::disk('public')->url($path);
        } catch (\Exception $e) {
            // Fallback to asset() if Storage fails
            return asset('storage/' . ltrim($path, '/'));
        }
    }

    /**
     * Get image URL with fallback placeholder
     */
    public static function urlOrPlaceholder(?string $path, string $placeholder = 'https://images.unsplash.com/photo-1542838132-92c53300491e?w=400'): string
    {
        return self::url($path) ?: $placeholder;
    }
}
