<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Suiterus\Dms\Classes\UserAccess;

class SectionAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $user = User::where('id', Auth::user()->id)->first();

        $roles = $user->roles->pluck('id');

        $hasAccess = UserAccess::traverseFolderTreeAccess($request->section_id, $roles);

        if (!$hasAccess) {
            return abort(403);
        }
        
        return $next($request);
    }
}
