<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureUserHasRole
{
    /**
     * Redirect users with no role or no permissions to the no-role page.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->routeIs('no-role')) {
            return $next($request);
        }

        $user = auth()->user();

        if ($user->roles()->count() === 0) {
            return redirect()->route('no-role');
        }

        if ($user->getAllPermissions()->isEmpty()) {
            return redirect()->route('no-role');
        }

        return $next($request);
    }
}
