<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Verifică dacă language change is requested via query parameter
        if ($request->has('lang')) {
            $lang = $request->get('lang');
            $language = Language::where('code', $lang)->where('is_active', true)->first();

            if ($language) {
                Session::put('locale', $lang);
                App::setLocale($lang);

                // Redirecționează to same URL fără lang parameter
                return redirect($request->url());
            }
        }

        // Check session saved locale
        if (Session::has('locale')) {
            $locale = Session::get('locale');
            $language = Language::where('code', $locale)->where('is_active', true)->first();

            if ($language) {
                App::setLocale($locale);
                return $next($request);
            }
        }

        // Check default language from settings (prioritate mai mare decât browser)
        $defaultLangCode = \App\Models\Setting::get('default_language', null);
        if ($defaultLangCode) {
            $defaultLanguage = Language::where('code', $defaultLangCode)->where('is_active', true)->first();
            if ($defaultLanguage) {
                App::setLocale($defaultLanguage->code);
                Session::put('locale', $defaultLanguage->code);
                return $next($request);
            }
        }

        // Fallback to default language from database
        $defaultLanguage = Language::where('is_default', true)->first();
        if ($defaultLanguage) {
            App::setLocale($defaultLanguage->code);
            Session::put('locale', $defaultLanguage->code);
            return $next($request);
        }

        // Hard fallback
        App::setLocale('ro');
        Session::put('locale', 'ro');

        return $next($request);
    }
}
