<?php

namespace App\Http\Middleware;

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

class LocaleFromUser
{
    public function handle(Request $request, Closure $next): mixed
    {
        if ($user = $request->user()) {
            $supported = config('app.supported_locales', [config('app.locale')]);
            $locale = in_array($user->locale, $supported, true)
                ? $user->locale
                : config('app.locale');
            App::setLocale($locale);
        }

        return $next($request);
    }
}
