<?php

namespace App\Http\Middleware;

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

class CheckPermissions
{
    public function handle(Request $request, Closure $next, $permission, $accessLevel, $orgId = null)
    {
        $user = Auth::user();

        if($user->user_type == "admin" || $user->user_type == "manager"){
            return $next($request);
        }

        if ($user && $user->hasPermission($user->organisation_id, 'Owner', $accessLevel)) {
            
            if ($permission === 'HR') {
                return $next($request);
            }
            if ($permission === 'Owner') {
                return $next($request);
            }
        }

        if ($user && $user->hasPermission($user->organisation_id, 'HR', $accessLevel)) {

            if ($permission === 'Employee') {
                return $next($request);
            }
            if ($permission === 'HR') {
                return $next($request);
            }
        }

        if ($user && $user->hasPermission($user->organisation_id, $permission, $accessLevel)) {
            return $next($request);
        }

        return response()->json([
            "status" => "failed",
            "message"=> "Permission denied"
        ],403);
    }
}

