<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $section
     * @param  string  $action
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $section, $action)
    {
        $user = Auth::user();

        if (!$user) {
            return response()->json(['message' => 'User not found.'], Response::HTTP_UNAUTHORIZED);
        }

        $role = $user->role;

        if (!$role) {
            return response()->json(['message' => 'Role not found or has been deleted.'], Response::HTTP_FORBIDDEN);
        }

        $permissions = $role->permissions;

        $permission = collect($permissions)->firstWhere('section', $section);
    
        if (!$permission || !isset($permission['access'][$action]) || !$permission['access'][$action]) {
            return response()->json(['message' => 'You do not have permission to perform this action.'], Response::HTTP_FORBIDDEN);
        }

        return $next($request);
    }
}
