<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class SetLocale
{
    public function handle($request, Closure $next)
    {

        // Get locale from session, cookie, or use default
        $locale = $request->cookie('locale') ?? config('app.locale');
        
        // Ensure the locale is supported
        if (in_array($locale, ['en', 'fr'])) {
            App::setLocale($locale);
        } else {
            // Fallback to French if locale is not supported
            $locale = 'fr';
            App::setLocale($locale);
        }
        
        // Set the application locale for the current request
        $response = $next($request);
        
        // Set the locale cookie for subsequent requests
        return $response->withCookie(cookie()->forever('locale', $locale));
    }
}
