<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $permission
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $permission)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        // Allow super-admin to access everything
        if (Auth::user()->hasRole('super-admin')) {
            return $next($request);
        }

        // Allow tenant users to create and store subscriptions if they have manage subscriptions permission
        if ($permission === 'manage users' && in_array($request->route()->getName(), ['subscriptions.create', 'subscriptions.store']) && Auth::user()->can('manage subscriptions')) {
            return $next($request);
        }

        if (!Auth::user()->can($permission)) {
            abort(403, 'Unauthorized.');
        }

        return $next($request);
    }
}
