<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class LocaleMiddleware
{
    /**
     * Supported application locales.
     */
    public const SUPPORTED_LOCALES = [
        'en', 'ar', 'fr', 'es', 'de', 'it', 'pt', 'ru',
        'ja', 'ko', 'tr', 'id', 'hi', 'ta', 'bn', 'te', 'th', 'vi',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Locale is enabled and allowed to be change
        if (session()->has('locale') && in_array(session()->get('locale'), self::SUPPORTED_LOCALES)) {
            $locale = session()->get('locale');
            app()->setLocale($locale);
            Carbon::setLocale($locale);
        }

        return $next($request);
    }
}
