<?php

namespace Workdo\MobileServiceManagement\Http\Middleware;

use App\Models\WorkSpace;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {

        if (!empty(session()->get('mobileservice_lang'))) {
            $currantLang = session()->get('mobileservice_lang');
        } else {
            $workspaceSlug = $request->route('workspaceSlug');
            if ($workspaceSlug) {
                $workspace = WorkSpace::where('slug', $workspaceSlug)->first();
                if ($workspace) {
                    $company_settings = getCompanyAllSetting($workspace->created_by, $workspace->id);
                    $currantLang      = $company_settings['defult_language'] ?? 'en';
                } else {
                    $currantLang = 'en';
                }
            } else {
                $currantLang = 'en';
            }
        }
        App::setLocale($currantLang);

        return $next($request);
    }
}
