<?php

use App\Models\UserRoleModel;
use App\Models\RolePermissionModel;
use App\Models\PermissionModel;

function has_permission($userId, $permissionName)
{
    $userRoleModel = new UserRoleModel();
    $rolePermissionModel = new RolePermissionModel();
    $permissionModel = new PermissionModel();

    $permission = $permissionModel->where('name', $permissionName)->first();
    if (!$permission) {
        return false;
    }

    $permissionId = $permission['id'];
    $roles = $userRoleModel->where('user_id', $userId)->findAll();
    foreach ($roles as $role) {
        $permissions = $rolePermissionModel->where('role_id', $role['role_id'])->where('permission_id', $permissionId)->findAll();
        if (!empty($permissions)) {
            return true;
        }
    }

    return false;
}
