<?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
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Priority: 1. Session, 2. User preference (if logged in), 3. Default config
        $locale = Session::get('locale');
        
        if (!$locale && auth()->check()) {
            // Check if user has a locale preference
            $userLocale = auth()->user()->locale;
            if ($userLocale && in_array($userLocale, ['en', 'fr', 'ar'])) {
                $locale = $userLocale;
                Session::put('locale', $locale);
            }
        }
        
        // Fallback to default if still no locale
        if (!$locale) {
            $locale = config('app.locale', 'en');
        }
        
        // Validate and set locale
        if (in_array($locale, ['en', 'fr', 'ar'])) {
            App::setLocale($locale);
            Session::put('locale', $locale);
        }

        return $next($request);
    }
}
