<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $locale = null;
        $allowedLocales = ['en', 'es', 'fr', 'ru'];

        // 1. From authenticated user preference
        if (Auth::check()) {
            $userLocale = Auth::user()->locale;
            if ($userLocale && in_array($userLocale, $allowedLocales)) {
                $locale = $userLocale;
            }
        }

        // 2. From session
        if (! $locale && Session::has('locale')) {
            $sessionLocale = Session::get('locale');
            if (in_array($sessionLocale, $allowedLocales)) {
                $locale = $sessionLocale;
            }
        }

        // 3. From browser Accept-Language
        if (! $locale) {
            $browserLang = substr($request->server('HTTP_ACCEPT_LANGUAGE', 'en'), 0, 2);
            if (in_array($browserLang, $allowedLocales)) {
                $locale = $browserLang;
            }
        }

        // 4. Default to app locale
        if (! $locale) {
            $locale = config('app.locale', 'en');
        }

        App::setLocale($locale);
        Session::put('locale', $locale);

        return $next($request);
    }
}
