<?php


namespace App\Http\Middleware;

use Closure;
use App\Core\Helper\LanguageService;
use Exception;

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

        $apiHeader = collect($request->headers)->toArray();
        if(!isset($apiHeader['language'])){
            return apiResponse(0, 'Language field is null.', null, 400);
        }
        $apiRequest = collect($request->params)->toArray();
        $apiRequest['locale'] = isset($apiRequest['locale']) ? $apiRequest['locale'] : reset($apiHeader['language']);
        LanguageService::setCurrentLanguage(reset($apiHeader['language']));
        $request->params = $apiRequest;
        app('translator')->setLocale(reset($apiHeader['language']));

        return $next($request);
    }
}
