<?php

namespace App\Http\Middleware;

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

class SetLocaleFromRequest
{
    public function handle(Request $request, Closure $next)
    {
        $supportedLocales = LocaleConfig::normalized();

        $locale = (string) ($request->route('locale') ?? $request->segment(1));
        $normalizedLocale = LocaleConfig::canonicalize($locale);

        if (! $locale || ! in_array($normalizedLocale, $supportedLocales, true)) {
            $preferred = Session::get('preferred_locale');

            if ($preferred && in_array($preferred, $supportedLocales, true)) {
                App::setLocale($preferred);
                Session::put('locale', $preferred);
                $request->attributes->set('preferred_locale', $preferred);
            }

            return $next($request);
        }

        App::setLocale($normalizedLocale);
        Session::put('preferred_locale', $normalizedLocale);
        Session::put('locale', $normalizedLocale);
        $request->attributes->set('preferred_locale', $normalizedLocale);

        return $next($request);
    }
}
