<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        // ?lang=ar|en switches and persists the UI language.
        if (in_array($request->query('lang'), ['ar', 'en'], true)) {
            $request->session()->put('locale', $request->query('lang'));
        }

        $locale = $request->user()?->locale
            ?? $request->session()->get('locale')
            ?? config('app.locale');

        app()->setLocale($locale);

        return $next($request);
    }
}
