<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        $supported = ['en', 'bn'];
        $default = Schema::hasTable('settings') ? app(SettingService::class)->get('language.default', 'en') : 'en';
        $locale = session('locale', in_array($default, $supported, true) ? $default : 'en');
        app()->setLocale(in_array($locale, $supported, true) ? $locale : 'en');

        return $next($request);
    }
}
