<?php

namespace Daylight\Core\Modules\Multilingualism\Http\Middleware;

use Closure;
use Daylight\Core\Modules\Multilingualism\Multilingualism;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetLocaleForLivewireRequests
{
    public function handle(Request $request, Closure $next): Response
    {
        $livewireLocale = $request->get('data')['livewireLocale'] ?? null;

        if ($livewireLocale && Multilingualism::getAvailableLocales()->has($livewireLocale)) {
            app()->setLocale($livewireLocale);
            session()->put('locale', $livewireLocale);
        }

        return $next($request);
    }
}
