<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Closure;

class Role
{
    /**
        * Handle an incoming request.
        *
        * @param  \Illuminate\Http\Request  $request
        * @param  \Closure  $next
        *
        * @return mixed
        */
    public function __construct(Request $request)
    {
        $this->req = $request;
    }

    public function handle($request, Closure $next, $role)
    {
        if (!auth()->user()) {
            return redirect()->route('login');
        }

        if (auth()->user()->is_active != 1) {
            auth()->logout();
            return redirect()->route('login');
        }
        
        $roles = explode('|', $role);
        $accessPage = 0;
        foreach ($roles as $r) {
            if (auth()->user()->role == $r) {
                $accessPage = 1;
            }
        }

        if ($accessPage == 1) {
            return $next($request);
        }

        return redirect('home');
    }
}
