<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use App\Models\Language;
use Illuminate\Support\Facades\Cache;

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        if (Session::has('locale')) {
            $locale = Session::get('locale');
        } else {
            // Get default from DB (Cached)
            $locale = Cache::rememberForever('default_locale', function () {
                return Language::where('is_default', true)->value('code') ?? 'en';
            });
        }

        App::setLocale($locale);

        return $next($request);
    }
}