<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\CheckAccessController;
use App\Module;
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);

        $moduleIsActive = Module::where('path', $action)->first();

        if ($moduleIsActive->deleted_at){
            return redirect('/admin/');
        }

        if (in_array($request->user()->role, ['super_admin', 'admin']) || $request->user()->admin_token){
            $canAccess = true;
        }

        if(!$canAccess){
            return redirect('/admin/');
        }

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

        if ($request->user()->role == 'super_admin'){
            if (Route::currentRouteName() == 'users.edit'){
                if (!CheckAccessController::preventSuperAdminToEditOtherSuperAdmin($request->user->id)){
                    return redirect('/admin');
                }
            }
        }

        if ($request->user()->role == 'admin'){
            if (Route::currentRouteName() == 'users.edit'){
                if (!CheckAccessController::preventAdminTOAccessSuperAdmin($request->user->id)){
                    return redirect('/admin');
                }
            }
        }

        if ($request->user()->role == 'sub_admin'){
            if (Route::currentRouteName() == 'users.edit'){
                if (!CheckAccessController::preventSubAdminTOAccessOtherRoles($request->user->id)){
                    return redirect('/admin');
                }
            } elseif (Route::currentRouteName() == 'users.create'){
                return redirect('/admin');
            }
        }
        return $next($request);
    }
}
