<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        $supported = ['en','ar'];

        $sessionLocale = $request->session()->get('locale');
        $userLocale    = optional($request->user())->preferred_language;
        $fallback      = config('app.locale', 'en');

        $locale = $sessionLocale ?: ($userLocale ?: $fallback);
        if (!in_array($locale, $supported)) $locale = $fallback;

        App::setLocale($locale);

        $dir = $locale === 'ar' ? 'rtl' : 'ltr';
        View::share('appLocale', $locale);
        View::share('appDir', $dir);

        return $next($request);
    }
}
