<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Mtc\Core\Admin\Menu;
use Mtc\Core\Admin\User;

/**
 * Class AdminUserMiddleware
 *
 * This middleware adds admin user details
 *
 * @package App\Http\Middleware
 */
class AdminUserMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $twig = App::make('twig');
        $user = User::query()->find($_SESSION['adminId']);

        $twig->addGlobal('admin_id', $user->id);
        $twig->addGlobal('admin_user', $user);
        $twig->addGlobal('cms_tree', Menu::showCMSTree($user));
        $twigGlobals = $twig->getGlobals();
        if (empty($twigGlobals[Menu::GLOBAL_KEY])) {
            $twig->addGlobal(Menu::GLOBAL_KEY, Menu::getAdminMenu());
        }
        return $next($request);
    }

}
