<?php

namespace App\Http\Middleware;

use App\Models\Language;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class SetCurrentLanguageIdMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure(Request): (Response) $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Get the current locale from LaravelLocalization
        $currentLocale = request()->header('lang') ?? LaravelLocalization::getCurrentLocale();

        // Fetch the language ID from the database based on the current locale
        $languageId = Language::where('local', $currentLocale)->value('id');

        // Bind the language ID to the container
        //App::instance('currentLanguageId', $languageId); // app('currentLanguageId') //App::make('currentLanguageId')
        Config::set('app.currentLanguageId', $languageId); //Config::get('app.currentLanguageId') //app('currentLanguageId')

        View::share('lang', LaravelLocalization::getCurrentLocale());
        View::share('lang_dir', LaravelLocalization::getCurrentLocaleDirection());

        return $next($request);
    }
}
