<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        $available = ['en', 'bn', 'ar'];

        // Priority: authenticated user's DB preference → session → app default
        if (Auth::check() && in_array(Auth::user()->locale, $available, true)) {
            $locale = Auth::user()->locale;
            // Keep session in sync so newly-switched locale is visible immediately
            session(['locale' => $locale]);
        } else {
            $locale = session('locale', config('app.locale'));
        }

        if (in_array($locale, $available, true)) {
            app()->setLocale($locale);
        }

        return $next($request);
    }
}
