<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\HttpFoundation\Response;

class LanguageMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return Response
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(Request $request, Closure $next): Response
    {
        $language = $request->get('lang') ?? $request->session()->get('locale');
        Log::debug("Request Lang: " . $request->get('lang'));
        Log::debug("Session Lang: ". session()->get('locale')?? 'No session found');
        if (empty($language)) {
            $language = match($request->getPreferredLanguage()) {
                'es', 'es-ES', 'es_ES' => 'es_ES',
                default => 'en_EN'
            };
        }
        app()->setLocale($language);
        $request->session()->put('locale', $language);
        return $next($request);
    }
}
