<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;

class Khazanah
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $Roles = ["teller","admin","penilai","khazanah"];
        $routeMiddleware = $request->route()->middleware();
        $filteredMiddleware = array_intersect($routeMiddleware, $Roles);

        $filtered = array_map(function($res){
            switch($res){
                case 'teller' : return 'teller';
                case 'khazanah' : return 'pc';
            }
        },$filteredMiddleware);

        if(Auth::check() && (Auth::user()->roles == 'pc' || Auth::user()->roles == 'ppc' || in_array(Auth::user()->roles,$filtered))){
            return $next($request);
        }

        return redirect('/login');
    }
}
