<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class CheckRole
{
    /**
     * Handle an incoming request.
     * Redirect user to home page if he has not the privilege to make the next action
     * @param  Request  $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $action=explode('.',Route::currentRouteName())[0];
        $canAccess=$request->user()->canAccess($action);
        // dd($action,$request->user()->getRole(), $canAccess);
        if(!$canAccess){
            return redirect('/admin/');
        }

        if (Auth::user()->role != 'admin'){
            if (settings('dashboard_disable') == 1){
                Auth::logout();
                return redirect('admin/login')->with('error', __('dashboard.failed'));
            }
        }
        return $next($request);
    }
}
