<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class Admin
{
    /**
     * Gate the admin panel. Full admins pass everything; support/moderator
     * staff only pass routes in the sections they were granted.
     *
     * @param Request $request
     */
    public function handle(Request $request, Closure $next)
    {
        $user = auth()->user();

        if (!$user) {
            return redirect('/dashboard');
        }

        if ($user->is_admin) {
            return $next($request);
        }

        $section = User::sectionForRouteName(optional($request->route())->getName());

        if ($section && $user->canAccessSection($section)) {
            return $next($request);
        }

        return redirect('/dashboard');
    }
}
