<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{

    const SUPPORTED_LANGS = ['in', 'en', 'es', 'de', 'fr', 'pt'];

    public function handle(Request $request, Closure $next): Response
    {

        $lang = $request->route('lang');

        if (in_array($lang, self::SUPPORTED_LANGS)) {

            $appLocale = ($lang === 'in') ? 'id' : $lang;

            App::setLocale($appLocale);

            URL::defaults(['lang' => $lang]);

            session(['locale' => $lang]);

        } else {

            App::setLocale(config('app.fallback_locale', 'id'));
        }

        return $next($request);
    }
}