<?php
// app/Http/Middleware/SetLocale.php

namespace App\Http\Middleware;

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

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        $locale = 'en'; // default

        if (Auth::check()) {
            $user = Auth::user();
            $locale = $user->preferred_language ?? 'en';
        }

        // Validate supported locales
        $supportedLocales = ['en', 'fr', 'es', 'de', 'it', 'pt', 'zh'];
        if (!in_array($locale, $supportedLocales)) {
            $locale = 'en';
        }

        App::setLocale($locale);
        $request->merge(['current_locale' => $locale]);

        return $next($request);
    }
}
