<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Set the application locale based on session or user preference
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check session first
        $locale = Session::get('locale');

        // Then check user preference
        if (!$locale && $request->user()) {
            $locale = $request->user()->locale;
        }

        // Default to config locale
        $locale = $locale ?? config('app.locale', 'en');

        // Set locale
        if (in_array($locale, ['en', 'ar'])) {
            App::setLocale($locale);
        }

        return $next($request);
    }
}
