<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Locale
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request):Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $locale = explode('-', explode(',', (string) \Illuminate\Support\Facades\Request::server('HTTP_ACCEPT_LANGUAGE'))[0])[0];
            if (in_array($locale, config('app.locales'))) {
                session(['browser-locale' => $locale]);
            }
        } catch (Exception) {
        }
        app()->setLocale(session('locale', session('browser-locale', config('app.settings.language', config('app.locale', 'en')))));

        return $next($request);
    }
}
