<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;

class LocaleServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // مشاركة بيانات اللغة مع جميع الـ views
        View::composer('*', function ($view) {
            $locale = (auth()->user()?->locale ?? app()->getLocale());
            $locales = config('app.available_locales');

            $view->with([
                'currentLocale' => $locale,
                'currentLocaleData' => $locales[$locale] ?? null,
                'availableLocales' => $locales,
                'textDirection' => config('app.direction'),
            ]);
        });

        // إضافة helper function
        if (!function_exists('locale_url')) {
            function locale_url(string $url, ?string $locale = null): string
            {
                $locale = $locale ?: (auth()->user()?->locale ?? app()->getLocale());
                $parsed = parse_url($url);

                // إضافة locale إلى path
                $path = $parsed['path'] ?? '/';
                $path = '/' . $locale . ltrim($path, '/');

                return ($parsed['scheme'] ?? '') . '://' .
                    ($parsed['host'] ?? '') .
                    $path .
                    (!empty($parsed['query']) ? '?' . $parsed['query'] : '') .
                    (!empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '');
            }
        }
    }
}
