<?php
/**
 * Name: Simple Role Editor
 * Description: Edit user roles and capabilities with visual interface to add, remove, or modify permissions for administrators, editors, authors, and create custom roles
 * Category: User Management
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Customize Capabilities",
 *     "description": "Fine-tune what each user role can do by adding or removing specific capabilities without coding."
 *   },
 *   {
 *     "title": "Secure Workflows",
 *     "description": "Remove unnecessary permissions from roles to improve security and prevent accidental content changes."
 *   }
 * ]
 * Added: 2025-08-16
 * Tags: roles, capabilities, permissions, users, security
 * WhereToFind: {
 *   "location": "Switchboard → Role Editor",
 *   "url": "admin.php?page=switchboard-role-editor",
 *   "instructions": "Manage user roles and capabilities from the dedicated Role Editor page. Create custom roles, modify permissions, and see detailed capability descriptions.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardSimpleRoleEditor {

    /**
     * Capability descriptions organized by category
     * Each capability has: description, category, and danger level (0=safe, 1=moderate, 2=dangerous)
     */
    private static $capability_info = [
        // Posts & Pages
        'edit_posts' => [
            'desc' => 'Create and edit own posts (drafts)',
            'category' => 'posts',
            'danger' => 0
        ],
        'edit_others_posts' => [
            'desc' => 'Edit posts created by other users',
            'category' => 'posts',
            'danger' => 1
        ],
        'edit_published_posts' => [
            'desc' => 'Edit own posts after they are published',
            'category' => 'posts',
            'danger' => 0
        ],
        'publish_posts' => [
            'desc' => 'Publish posts (not just save as draft)',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_posts' => [
            'desc' => 'Delete own posts',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_others_posts' => [
            'desc' => 'Delete posts created by other users',
            'category' => 'posts',
            'danger' => 1
        ],
        'delete_published_posts' => [
            'desc' => 'Delete own published posts',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_private_posts' => [
            'desc' => 'Delete private posts',
            'category' => 'posts',
            'danger' => 1
        ],
        'edit_private_posts' => [
            'desc' => 'Edit private posts',
            'category' => 'posts',
            'danger' => 1
        ],
        'read_private_posts' => [
            'desc' => 'View private posts',
            'category' => 'posts',
            'danger' => 0
        ],
        'edit_pages' => [
            'desc' => 'Create and edit own pages',
            'category' => 'posts',
            'danger' => 0
        ],
        'edit_others_pages' => [
            'desc' => 'Edit pages created by other users',
            'category' => 'posts',
            'danger' => 1
        ],
        'edit_published_pages' => [
            'desc' => 'Edit own pages after they are published',
            'category' => 'posts',
            'danger' => 0
        ],
        'publish_pages' => [
            'desc' => 'Publish pages',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_pages' => [
            'desc' => 'Delete own pages',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_others_pages' => [
            'desc' => 'Delete pages created by other users',
            'category' => 'posts',
            'danger' => 1
        ],
        'delete_published_pages' => [
            'desc' => 'Delete own published pages',
            'category' => 'posts',
            'danger' => 0
        ],
        'delete_private_pages' => [
            'desc' => 'Delete private pages',
            'category' => 'posts',
            'danger' => 1
        ],
        'edit_private_pages' => [
            'desc' => 'Edit private pages',
            'category' => 'posts',
            'danger' => 1
        ],
        'read_private_pages' => [
            'desc' => 'View private pages',
            'category' => 'posts',
            'danger' => 0
        ],
        'read' => [
            'desc' => 'Read content on the site (basic access)',
            'category' => 'posts',
            'danger' => 0
        ],

        // Users & Roles
        'list_users' => [
            'desc' => 'View list of all users',
            'category' => 'users',
            'danger' => 0
        ],
        'create_users' => [
            'desc' => 'Create new user accounts',
            'category' => 'users',
            'danger' => 2
        ],
        'edit_users' => [
            'desc' => 'Edit user profiles and settings',
            'category' => 'users',
            'danger' => 2
        ],
        'delete_users' => [
            'desc' => 'Delete user accounts permanently',
            'category' => 'users',
            'danger' => 2
        ],
        'remove_users' => [
            'desc' => 'Remove users from the site (multisite)',
            'category' => 'users',
            'danger' => 2
        ],
        'promote_users' => [
            'desc' => 'Change user roles and promote users',
            'category' => 'users',
            'danger' => 2
        ],

        // Plugins & Themes
        'activate_plugins' => [
            'desc' => 'Activate and deactivate plugins',
            'category' => 'plugins',
            'danger' => 2
        ],
        'install_plugins' => [
            'desc' => 'Install new plugins from repository',
            'category' => 'plugins',
            'danger' => 2
        ],
        'update_plugins' => [
            'desc' => 'Update installed plugins',
            'category' => 'plugins',
            'danger' => 2
        ],
        'delete_plugins' => [
            'desc' => 'Delete plugins from the site',
            'category' => 'plugins',
            'danger' => 2
        ],
        'edit_plugins' => [
            'desc' => 'Edit plugin files directly (code editor)',
            'category' => 'plugins',
            'danger' => 2
        ],
        'switch_themes' => [
            'desc' => 'Switch to a different theme',
            'category' => 'plugins',
            'danger' => 1
        ],
        'install_themes' => [
            'desc' => 'Install new themes from repository',
            'category' => 'plugins',
            'danger' => 2
        ],
        'update_themes' => [
            'desc' => 'Update installed themes',
            'category' => 'plugins',
            'danger' => 1
        ],
        'delete_themes' => [
            'desc' => 'Delete themes from the site',
            'category' => 'plugins',
            'danger' => 2
        ],
        'edit_themes' => [
            'desc' => 'Edit theme files directly (code editor)',
            'category' => 'plugins',
            'danger' => 2
        ],
        'edit_theme_options' => [
            'desc' => 'Customize theme settings and widgets',
            'category' => 'plugins',
            'danger' => 1
        ],

        // Site Settings
        'manage_options' => [
            'desc' => 'Access and modify all site settings',
            'category' => 'settings',
            'danger' => 2
        ],
        'update_core' => [
            'desc' => 'Update WordPress core',
            'category' => 'settings',
            'danger' => 2
        ],
        'edit_dashboard' => [
            'desc' => 'Customize the admin dashboard',
            'category' => 'settings',
            'danger' => 0
        ],
        'import' => [
            'desc' => 'Import content from external sources',
            'category' => 'settings',
            'danger' => 1
        ],
        'export' => [
            'desc' => 'Export site content and data',
            'category' => 'settings',
            'danger' => 1
        ],
        'edit_files' => [
            'desc' => 'Edit files via the admin interface',
            'category' => 'settings',
            'danger' => 2
        ],
        'unfiltered_html' => [
            'desc' => 'Post HTML without filtering (scripts, iframes)',
            'category' => 'settings',
            'danger' => 2
        ],
        'unfiltered_upload' => [
            'desc' => 'Upload files without restriction',
            'category' => 'settings',
            'danger' => 2
        ],

        // Media
        'upload_files' => [
            'desc' => 'Upload media files to the library',
            'category' => 'media',
            'danger' => 0
        ],

        // Comments
        'moderate_comments' => [
            'desc' => 'Approve, edit, and delete comments',
            'category' => 'comments',
            'danger' => 0
        ],
        'edit_comment' => [
            'desc' => 'Edit individual comments',
            'category' => 'comments',
            'danger' => 0
        ],

        // Taxonomy
        'manage_categories' => [
            'desc' => 'Create, edit, and delete categories',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'manage_links' => [
            'desc' => 'Manage blogroll links (legacy)',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'assign_categories' => [
            'desc' => 'Assign categories to posts',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'assign_post_tags' => [
            'desc' => 'Assign tags to posts',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'edit_post_tags' => [
            'desc' => 'Create and edit post tags',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'delete_post_tags' => [
            'desc' => 'Delete post tags',
            'category' => 'taxonomy',
            'danger' => 0
        ],
        'manage_post_tags' => [
            'desc' => 'Manage all post tags',
            'category' => 'taxonomy',
            'danger' => 0
        ],

        // Multisite
        'manage_network' => [
            'desc' => 'Manage network settings (Super Admin)',
            'category' => 'multisite',
            'danger' => 2
        ],
        'manage_sites' => [
            'desc' => 'Manage sites in the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'manage_network_users' => [
            'desc' => 'Manage users across the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'manage_network_plugins' => [
            'desc' => 'Manage plugins across the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'manage_network_themes' => [
            'desc' => 'Manage themes across the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'manage_network_options' => [
            'desc' => 'Manage network-wide options',
            'category' => 'multisite',
            'danger' => 2
        ],
        'create_sites' => [
            'desc' => 'Create new sites in the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'delete_sites' => [
            'desc' => 'Delete sites from the network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'upgrade_network' => [
            'desc' => 'Upgrade the entire network',
            'category' => 'multisite',
            'danger' => 2
        ],
        'setup_network' => [
            'desc' => 'Initial network setup',
            'category' => 'multisite',
            'danger' => 2
        ],

        // WooCommerce (common)
        'manage_woocommerce' => [
            'desc' => 'Manage WooCommerce settings',
            'category' => 'woocommerce',
            'danger' => 1
        ],
        'view_woocommerce_reports' => [
            'desc' => 'View WooCommerce sales reports',
            'category' => 'woocommerce',
            'danger' => 0
        ],
        'edit_shop_orders' => [
            'desc' => 'Edit shop orders',
            'category' => 'woocommerce',
            'danger' => 1
        ],
        'edit_others_shop_orders' => [
            'desc' => 'Edit orders created by others',
            'category' => 'woocommerce',
            'danger' => 1
        ],
        'publish_shop_orders' => [
            'desc' => 'Publish shop orders',
            'category' => 'woocommerce',
            'danger' => 1
        ],
        'read_shop_orders' => [
            'desc' => 'View shop orders',
            'category' => 'woocommerce',
            'danger' => 0
        ],
        'delete_shop_orders' => [
            'desc' => 'Delete shop orders',
            'category' => 'woocommerce',
            'danger' => 2
        ],
        'edit_products' => [
            'desc' => 'Edit products',
            'category' => 'woocommerce',
            'danger' => 0
        ],
        'edit_others_products' => [
            'desc' => 'Edit products created by others',
            'category' => 'woocommerce',
            'danger' => 1
        ],
        'publish_products' => [
            'desc' => 'Publish products',
            'category' => 'woocommerce',
            'danger' => 0
        ],
        'delete_products' => [
            'desc' => 'Delete products',
            'category' => 'woocommerce',
            'danger' => 1
        ],

        // Privacy
        'manage_privacy_options' => [
            'desc' => 'Manage privacy settings and tools',
            'category' => 'settings',
            'danger' => 1
        ],
        'erase_others_personal_data' => [
            'desc' => 'Erase personal data for other users',
            'category' => 'users',
            'danger' => 2
        ],
        'export_others_personal_data' => [
            'desc' => 'Export personal data for other users',
            'category' => 'users',
            'danger' => 1
        ],

        // Blocks/Patterns
        'edit_block_patterns' => [
            'desc' => 'Edit reusable block patterns',
            'category' => 'posts',
            'danger' => 0
        ],
        'edit_template_parts' => [
            'desc' => 'Edit template parts',
            'category' => 'posts',
            'danger' => 1
        ],
        'edit_templates' => [
            'desc' => 'Edit site templates',
            'category' => 'posts',
            'danger' => 1
        ],
    ];

    /**
     * Category labels and order
     */
    private static $categories = [
        'posts' => 'Posts & Pages',
        'users' => 'Users & Roles',
        'plugins' => 'Plugins & Themes',
        'settings' => 'Site Settings',
        'media' => 'Media',
        'comments' => 'Comments',
        'taxonomy' => 'Categories & Tags',
        'multisite' => 'Multisite',
        'woocommerce' => 'WooCommerce',
        'other' => 'Other'
    ];

    /**
     * Get capability info with fallback for unknown capabilities
     */
    public static function get_capability_info($cap) {
        if (isset(self::$capability_info[$cap])) {
            return self::$capability_info[$cap];
        }

        // Generate info for unknown capabilities
        $category = 'other';
        $danger = 0;

        // Try to guess category from capability name
        if (strpos($cap, 'post') !== false || strpos($cap, 'page') !== false) {
            $category = 'posts';
        } elseif (strpos($cap, 'user') !== false || strpos($cap, 'role') !== false) {
            $category = 'users';
            $danger = 1;
        } elseif (strpos($cap, 'plugin') !== false || strpos($cap, 'theme') !== false) {
            $category = 'plugins';
            $danger = 1;
        } elseif (strpos($cap, 'option') !== false || strpos($cap, 'setting') !== false) {
            $category = 'settings';
            $danger = 1;
        } elseif (strpos($cap, 'media') !== false || strpos($cap, 'upload') !== false || strpos($cap, 'file') !== false) {
            $category = 'media';
        } elseif (strpos($cap, 'comment') !== false) {
            $category = 'comments';
        } elseif (strpos($cap, 'categor') !== false || strpos($cap, 'tag') !== false || strpos($cap, 'term') !== false) {
            $category = 'taxonomy';
        } elseif (strpos($cap, 'network') !== false || strpos($cap, 'site') !== false) {
            $category = 'multisite';
            $danger = 2;
        } elseif (strpos($cap, 'shop') !== false || strpos($cap, 'product') !== false || strpos($cap, 'order') !== false || strpos($cap, 'woo') !== false) {
            $category = 'woocommerce';
        }

        // Dangerous keywords
        if (strpos($cap, 'delete') !== false || strpos($cap, 'remove') !== false) {
            $danger = max($danger, 1);
        }
        if (strpos($cap, 'manage') !== false || strpos($cap, 'admin') !== false) {
            $danger = max($danger, 1);
        }
        if (strpos($cap, 'install') !== false || strpos($cap, 'unfiltered') !== false) {
            $danger = 2;
        }

        // Generate readable description from capability name
        $desc = ucfirst(str_replace('_', ' ', $cap));

        return [
            'desc' => $desc,
            'category' => $category,
            'danger' => $danger
        ];
    }

    /**
     * Get all categories
     */
    public static function get_categories() {
        return self::$categories;
    }

    public function __construct() {
        // The role editor now uses the main AJAX save handler in switchboard.php
        // No hooks needed here - all processing happens via ajax_save_module_settings

        // Register dedicated admin page
        add_action('admin_menu', [$this, 'register_admin_page']);

        // Enqueue assets for the dedicated page
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // AJAX handler for reset role
        add_action('wp_ajax_switchboard_reset_role', [$this, 'ajax_reset_role']);

        // AJAX handler for create role
        add_action('wp_ajax_switchboard_create_role', [$this, 'ajax_create_role']);

        // AJAX handler for delete role
        add_action('wp_ajax_switchboard_delete_role', [$this, 'ajax_delete_role']);

        // AJAX handler for saving capabilities (dedicated page)
        add_action('wp_ajax_switchboard_save_role_capabilities', [$this, 'ajax_save_role_capabilities']);

        // Register with data registry
        $this->register_with_data_registry();
    }

    /**
     * Register the dedicated admin page under Switchboard menu
     */
    public function register_admin_page() {
        add_submenu_page(
            'switchboard',
            __('Role Editor', 'wpswitchboard'),
            __('Role Editor', 'wpswitchboard'),
            'manage_options',
            'switchboard-role-editor',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Enqueue assets for the dedicated Role Editor page
     */
    public function enqueue_admin_assets($hook) {
        // Only load on our page (use strpos for hook matching like other modules)
        if (strpos($hook, 'switchboard-role-editor') === false) {
            return;
        }

        // Enqueue main Switchboard admin CSS (provides sb-module-* classes)
        wp_enqueue_style(
            'switchboard-admin',
            plugins_url('../../switchboard-admin.css', __FILE__),
            [],
            SWITCHBOARD_VERSION
        );

        // Enqueue jQuery
        wp_enqueue_script('jquery');
    }

    /**
     * Render the dedicated Role Editor admin page
     */
    public function render_admin_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'wpswitchboard'));
        }

        $admin_file = plugin_dir_path(__FILE__) . '../../assets/simple-role-editor/admin.php';
        if (file_exists($admin_file)) {
            include $admin_file;
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Role Editor', 'wpswitchboard') . '</h1>';
            echo '<p>' . esc_html__('Admin template not found.', 'wpswitchboard') . '</p></div>';
        }
    }

    /**
     * AJAX handler to save role capabilities from the dedicated page
     */
    public function ajax_save_role_capabilities() {
        check_ajax_referer('switchboard_role_editor', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $role_key = isset($_POST['role']) ? sanitize_key($_POST['role']) : '';
        if (empty($role_key)) {
            wp_send_json_error(['message' => __('Role not specified', 'wpswitchboard')]);
        }

        $role = get_role($role_key);
        if (!$role) {
            wp_send_json_error(['message' => __('Role not found', 'wpswitchboard')]);
        }

        // Get submitted capabilities
        $submitted_caps = isset($_POST['capabilities']) && is_array($_POST['capabilities'])
            ? array_map('sanitize_key', array_keys($_POST['capabilities']))
            : [];

        // Get all possible capabilities
        global $wp_roles;
        $all_caps = [];
        foreach ($wp_roles->roles as $r) {
            if (isset($r['capabilities'])) {
                $all_caps = array_merge($all_caps, array_keys($r['capabilities']));
            }
        }
        $all_caps = array_unique($all_caps);

        // Update capabilities
        foreach ($all_caps as $cap) {
            if (in_array($cap, $submitted_caps)) {
                $role->add_cap($cap);
            } else {
                $role->remove_cap($cap);
            }
        }

        wp_send_json_success(['message' => __('Capabilities saved successfully', 'wpswitchboard')]);
    }

    /**
     * Register this module with the data registry
     */
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }

    /**
     * Register data locations for this module
     *
     * @return array Data locations
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    /**
     * Note: Settings panel removed - this module uses a dedicated admin page at Switchboard → Role Editor
     * The render_settings() method was removed to redirect clicks on the settings icon to the dedicated page.
     * See render_admin_page() method and /assets/simple-role-editor/admin.php for the full interface.
     */

    /**
     * AJAX handler to reset a role to WordPress default capabilities
     */
    public function ajax_reset_role() {
        check_ajax_referer('switchboard_reset_role', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $role = isset($_POST['role']) ? sanitize_key($_POST['role']) : '';
        if (empty($role)) {
            wp_send_json_error(['message' => __('Role not specified', 'wpswitchboard')]);
        }

        // Define default capabilities for each role
        $default_caps = [
            'administrator' => [
                'switch_themes', 'edit_themes', 'activate_plugins', 'edit_plugins',
                'edit_users', 'edit_files', 'manage_options', 'moderate_comments',
                'manage_categories', 'manage_links', 'upload_files', 'import', 'unfiltered_html',
                'edit_posts', 'edit_others_posts', 'edit_published_posts', 'publish_posts',
                'edit_pages', 'read', 'delete_posts', 'delete_others_posts',
                'delete_published_posts', 'delete_pages', 'delete_others_pages',
                'delete_published_pages', 'delete_private_posts', 'edit_private_posts',
                'read_private_posts', 'delete_private_pages', 'edit_private_pages',
                'read_private_pages', 'delete_users', 'create_users', 'unfiltered_upload',
                'edit_dashboard', 'update_plugins', 'delete_plugins', 'install_plugins',
                'update_themes', 'install_themes', 'update_core', 'list_users',
                'remove_users', 'promote_users', 'edit_theme_options', 'delete_themes',
                'export'
            ],
            'editor' => [
                'moderate_comments', 'manage_categories', 'manage_links', 'upload_files',
                'unfiltered_html', 'edit_posts', 'edit_others_posts', 'edit_published_posts',
                'publish_posts', 'edit_pages', 'read', 'delete_posts', 'delete_others_posts',
                'delete_published_posts', 'delete_pages', 'delete_others_pages',
                'delete_published_pages', 'delete_private_posts', 'edit_private_posts',
                'read_private_posts', 'delete_private_pages', 'edit_private_pages',
                'read_private_pages'
            ],
            'author' => [
                'upload_files', 'edit_posts', 'edit_published_posts', 'publish_posts',
                'read', 'delete_posts', 'delete_published_posts'
            ],
            'contributor' => [
                'edit_posts', 'read', 'delete_posts'
            ],
            'subscriber' => [
                'read'
            ]
        ];

        if (!isset($default_caps[$role])) {
            wp_send_json_error(['message' => __('Unknown role or no default capabilities defined', 'wpswitchboard')]);
        }

        $role_obj = get_role($role);
        if (!$role_obj) {
            wp_send_json_error(['message' => __('Role not found', 'wpswitchboard')]);
        }

        // Remove all current capabilities
        foreach (array_keys($role_obj->capabilities) as $cap) {
            $role_obj->remove_cap($cap);
        }

        // Add default capabilities
        foreach ($default_caps[$role] as $cap) {
            $role_obj->add_cap($cap);
        }

        wp_send_json_success(['message' => __('Role reset successfully', 'wpswitchboard')]);
    }

    /**
     * AJAX handler to create a new custom role
     */
    public function ajax_create_role() {
        check_ajax_referer('switchboard_create_role', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $role_id = isset($_POST['role_id']) ? sanitize_key($_POST['role_id']) : '';
        $role_name = isset($_POST['role_name']) ? sanitize_text_field($_POST['role_name']) : '';
        $copy_from = isset($_POST['copy_from']) ? sanitize_key($_POST['copy_from']) : '';

        // Validation
        if (empty($role_id)) {
            wp_send_json_error(['message' => __('Role ID is required', 'wpswitchboard')]);
        }

        if (empty($role_name)) {
            wp_send_json_error(['message' => __('Display name is required', 'wpswitchboard')]);
        }

        // Check if role already exists
        if (get_role($role_id)) {
            wp_send_json_error(['message' => __('A role with this ID already exists', 'wpswitchboard')]);
        }

        // Validate role ID format (lowercase letters, numbers, underscores only)
        if (!preg_match('/^[a-z0-9_]+$/', $role_id)) {
            wp_send_json_error(['message' => __('Role ID must contain only lowercase letters, numbers, and underscores', 'wpswitchboard')]);
        }

        // Get capabilities to copy
        $capabilities = ['read' => true]; // Default capability
        if (!empty($copy_from)) {
            $source_role = get_role($copy_from);
            if ($source_role) {
                $capabilities = $source_role->capabilities;
            }
        }

        // Create the new role with NO PREFIX - exactly as entered by user
        $result = add_role($role_id, $role_name, $capabilities);

        if ($result === null) {
            wp_send_json_error(['message' => __('Failed to create role', 'wpswitchboard')]);
        }

        wp_send_json_success([
            'message' => __('Role created successfully', 'wpswitchboard'),
            'role_id' => $role_id
        ]);
    }

    /**
     * AJAX handler to delete a custom role
     */
    public function ajax_delete_role() {
        check_ajax_referer('switchboard_delete_role', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }

        $role = isset($_POST['role']) ? sanitize_key($_POST['role']) : '';
        if (empty($role)) {
            wp_send_json_error(['message' => __('Role not specified', 'wpswitchboard')]);
        }

        // Prevent deletion of default WordPress roles
        $default_roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
        if (in_array($role, $default_roles)) {
            wp_send_json_error(['message' => __('Cannot delete default WordPress roles', 'wpswitchboard')]);
        }

        // Check if role exists
        if (!get_role($role)) {
            wp_send_json_error(['message' => __('Role not found', 'wpswitchboard')]);
        }

        // Check if any users have this role
        $users = get_users(['role' => $role, 'number' => 1]);
        if (!empty($users)) {
            wp_send_json_error(['message' => __('Cannot delete role: users are still assigned to this role', 'wpswitchboard')]);
        }

        // Delete the role
        remove_role($role);

        wp_send_json_success(['message' => __('Role deleted successfully', 'wpswitchboard')]);
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardSimpleRoleEditor();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
