<?php

namespace Hilco\Middleware;

use Closure;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param null $permission
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $permissionString = null)
    {
        $permissions = explode('|', $permissionString);
        foreach ($permissions as $permission) {
            if ($request->user()->can($permission)) {
                return $next($request);
            }
        }

        return $request->ajax ? response('Unauthorized.', 401) : redirect('/login');
    }
}
