<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $localizationSettings = LocalizationSetting::getSettings();
            if ($localizationSettings && $localizationSettings->locale) {
                App::setLocale($localizationSettings->locale);
            } else {
                App::setLocale(config('app.locale', 'en'));
            }
        } catch (\Exception $e) {
            // If settings don't exist yet, use default
            App::setLocale(config('app.locale', 'en'));
        }

        return $next($request);
    }
}
