<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        $supportedLocales = array_keys(config('app.supported_locales', [
            'bn' => 'বাংলা',
            'en' => 'English',
        ]));

        $locale = session('locale');

        if (! $locale || ! in_array($locale, $supportedLocales, true)) {
            $locale = config('app.locale', 'bn');
        }

        App::setLocale($locale);

        view()->share('currentLocale', $locale);
        view()->share('supportedLocales', config('app.supported_locales', [
            'bn' => 'বাংলা',
            'en' => 'English',
        ]));

        return $next($request);
    }
}