<?php

if (!defined('ABSPATH')) {
    exit;
}

class ACC_Runtime_Permission_Engine {

    public static function can_access(string $entity, string $action): bool {

        global $wpdb;

        $user = wp_get_current_user();

        if (!$user || !$user->ID) {
            return false;
        }

        $roles = $user->roles;

        if (empty($roles)) {
            return false;
        }

        $table           = $wpdb->prefix . 'erp_ui_permissions';
        $sanitized_roles = array_map('sanitize_key', $roles);
        $placeholders    = implode(',', array_fill(0, count($sanitized_roles), '%s'));

        $args = array_merge(
            [sanitize_key($entity), sanitize_key($action)],
            $sanitized_roles
        );

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id FROM {$table} WHERE entity_key=%s AND action=%s AND role IN ({$placeholders}) LIMIT 1",
                $args
            )
        );

        return !empty($row);
    }

}
