<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    public const SUPPORTED = ['ps', 'fa', 'ar', 'en'];

    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->session()->get('locale', config('app.locale', 'ps'));

        if (! in_array($locale, self::SUPPORTED, true)) {
            $locale = 'ps';
        }

        App::setLocale($locale);
        View::share('currentLocale', $locale);
        View::share('availableLocales', [
            'ps' => 'پښتو',
            'fa' => 'دری',
            'ar' => 'العربية',
            'en' => 'English',
        ]);

        return $next($request);
    }
}
