<?php
/**
 * Name: User Meta Display
 * Description: View, edit, and delete user metadata directly on profile pages with organized display by source to manage custom fields without database access
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Quick User Data Access",
 *     "description": "View and edit custom user metadata directly from the user profile page without needing additional plugins or database queries."
 *   },
 *   {
 *     "title": "Debug User Issues",
 *     "description": "Quickly inspect user meta fields to troubleshoot plugin conflicts or data issues without accessing the database directly."
 *   }
 * ]
 * Tags: user, meta, metadata, profile, admin, edit, delete
 * Added: 2025-10-16
 * WhereToFind: {
 *   "location": "Users → Edit User",
 *   "url": "user-edit.php",
 *   "instructions": "Scroll down to User Metadata section with search and edit",
 *   "newTab": false
 * }
 */

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

class SwitchboardUserMetaDisplay {

    public function __construct() {
        // AJAX handlers
        add_action('wp_ajax_switchboard_update_user_meta', [$this, 'ajax_update_user_meta']);
        add_action('wp_ajax_switchboard_delete_user_meta', [$this, 'ajax_delete_user_meta']);

        // Add meta display to user edit page
        add_action('show_user_profile', [$this, 'display_user_meta_on_profile']);
        add_action('edit_user_profile', [$this, 'display_user_meta_on_profile']);

        // Add custom styles to user edit page
        add_action('admin_head-user-edit.php', [$this, 'add_profile_styles']);
        add_action('admin_head-profile.php', [$this, 'add_profile_styles']);
    }

    /**
     * AJAX handler to update user meta
     */
    public function ajax_update_user_meta() {
        check_ajax_referer('switchboard_user_meta', 'nonce');

        // SECURITY: Only administrators can edit user meta
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'wpswitchboard')]);
        }

        $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
        $meta_key = isset($_POST['meta_key']) ? sanitize_text_field(wp_unslash($_POST['meta_key'])) : '';
        $meta_value = isset($_POST['meta_value']) ? sanitize_text_field(wp_unslash($_POST['meta_value'])) : '';

        if (!$user_id || !$meta_key) {
            wp_send_json_error(['message' => __('Invalid parameters', 'wpswitchboard')]);
        }

        // SECURITY: Protect critical meta keys from modification
        $protected_keys = [
            'wp_capabilities',
            'wp_user_level',
            'wp_user-settings',
            'wp_user-settings-time',
            'wp_dashboard_quick_press_last_post_id',
            'session_tokens',
        ];

        // Check if meta key starts with wp_ (WordPress internal) or is in protected list
        if (strpos($meta_key, 'wp_') === 0 || in_array($meta_key, $protected_keys)) {
            wp_send_json_error(['message' => __('Cannot modify protected WordPress meta keys', 'wpswitchboard')]);
        }

        // Validate user exists
        if (!get_userdata($user_id)) {
            wp_send_json_error(['message' => __('User not found', 'wpswitchboard')]);
        }

        // Safely handle JSON data
        $decoded = json_decode($meta_value, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            $meta_value = $decoded;
        } else {
            // Sanitize as text
            $meta_value = sanitize_textarea_field($meta_value);
        }

        update_user_meta($user_id, $meta_key, $meta_value);

        wp_send_json_success(['message' => __('Meta updated successfully', 'wpswitchboard')]);
    }

    /**
     * AJAX handler to delete user meta
     */
    public function ajax_delete_user_meta() {
        check_ajax_referer('switchboard_user_meta', 'nonce');

        // SECURITY: Only administrators can delete user meta
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'wpswitchboard')]);
        }

        $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
        $meta_key = isset($_POST['meta_key']) ? sanitize_text_field(wp_unslash($_POST['meta_key'])) : '';

        if (!$user_id || !$meta_key) {
            wp_send_json_error(['message' => __('Invalid parameters', 'wpswitchboard')]);
        }

        // SECURITY: Prevent deletion of critical meta keys
        $protected_keys = [
            'wp_capabilities',
            'wp_user_level',
            'wp_user-settings',
            'wp_user-settings-time',
            'session_tokens',
            'nickname',
            'first_name',
            'last_name',
            'description'
        ];

        // Also protect all keys starting with wp_
        if (strpos($meta_key, 'wp_') === 0 || in_array($meta_key, $protected_keys)) {
            wp_send_json_error(['message' => __('Cannot delete protected WordPress meta keys', 'wpswitchboard')]);
        }

        delete_user_meta($user_id, $meta_key);

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

    /**
     * Display user meta on profile edit pages
     */
    public function display_user_meta_on_profile($user) {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Get all user meta (excluding sensitive WordPress internal keys)
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Need all user meta keys for admin display
        $meta_data = $wpdb->get_results($wpdb->prepare(
            "SELECT meta_key, meta_value FROM {$wpdb->usermeta}
             WHERE user_id = %d
             AND meta_key NOT IN ('wp_capabilities', 'wp_user_level', 'session_tokens')
             ORDER BY meta_key ASC",
            $user->ID
        ), ARRAY_A);

        $settings = get_option('switchboard_user-meta-display_settings', []);
        $show_hidden = isset($settings['show_hidden']) && $settings['show_hidden'] === '1';

        ?>
        <h2 class="sb-sp-flex sb-sp-items-center">
            <?php
            /* translators: %d: number of metadata fields */
            printf(esc_html__('User Metadata (%d fields)', 'wpswitchboard'), count($meta_data));
            ?>
            <span class="switchboard-badge">SWITCHBOARD</span>
        </h2>
        <table class="form-table switchboard-user-meta-table" role="presentation">
            <tbody>
                <tr>
                    <td colspan="2">
                        <div class="switchboard-meta-search-box">
                            <input type="text" id="meta-search" placeholder="<?php esc_attr_e('Search meta keys or values...', 'wpswitchboard'); ?>" class="sb-sp-input">
                            <button type="button" class="button" id="toggle-hidden-meta">
                                <?php echo $show_hidden ? esc_html__('Hide', 'wpswitchboard') : esc_html__('Show', 'wpswitchboard'); ?> <?php esc_html_e('Hidden Meta', 'wpswitchboard'); ?>
                            </button>
                            <button type="button" class="button button-primary" id="add-new-user-meta-btn">
                                <?php esc_html_e('+ Add New Meta Field', 'wpswitchboard'); ?>
                            </button>
                        </div>

                        <!-- Add New Meta Form (initially hidden) -->
                        <div id="add-user-meta-form" class="add-meta-form" style="display: none;">
                            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Add New User Meta Field', 'wpswitchboard'); ?></h4>
                            <div class="add-meta-fields">
                                <div class="add-meta-field">
                                    <label for="new-user-meta-key"><?php esc_html_e('Meta Key *', 'wpswitchboard'); ?></label>
                                    <input type="text" id="new-user-meta-key" placeholder="<?php esc_attr_e('my_custom_field', 'wpswitchboard'); ?>" class="sb-sp-input">
                                </div>
                                <div class="add-meta-field">
                                    <label for="new-user-meta-value"><?php esc_html_e('Meta Value', 'wpswitchboard'); ?></label>
                                    <textarea id="new-user-meta-value" placeholder="<?php esc_attr_e('Enter meta value...', 'wpswitchboard'); ?>" class="sb-sp-textarea" rows="3"></textarea>
                                    <p class="sb-sp-description"><?php esc_html_e('For arrays/objects, use JSON format', 'wpswitchboard'); ?></p>
                                </div>
                            </div>
                            <div class="add-meta-actions">
                                <button type="button" class="button button-primary" id="save-new-user-meta-btn"><?php esc_html_e('Save Meta Field', 'wpswitchboard'); ?></button>
                                <button type="button" class="button" id="cancel-new-user-meta-btn"><?php esc_html_e('Cancel', 'wpswitchboard'); ?></button>
                            </div>
                        </div>

                        <div class="switchboard-meta-container">
                            <?php
                            $hidden_count = 0;
                            $visible_count = 0;

                            foreach ($meta_data as $meta) {
                                $key = $meta['meta_key'];
                                $is_hidden = strpos($key, '_') === 0;

                                if ($is_hidden) {
                                    $hidden_count++;
                                    if (!$show_hidden) {
                                        continue;
                                    }
                                } else {
                                    $visible_count++;
                                }

                                $value = maybe_unserialize($meta['meta_value']);

                                // Format value
                                if (is_array($value) || is_object($value)) {
                                    $display_value = json_encode($value, JSON_PRETTY_PRINT);
                                    $value_class = 'meta-value-complex';
                                } else {
                                    $display_value = esc_html($value);
                                    $value_class = 'meta-value-simple';
                                }

                                $row_class = $is_hidden ? 'meta-row meta-hidden' : 'meta-row';
                                $is_protected = (strpos($key, 'wp_') === 0) || in_array($key, ['nickname', 'first_name', 'last_name', 'description']);
                                ?>
                                <div class="<?php echo esc_attr($row_class); ?>" data-key="<?php echo esc_attr($key); ?>" data-value="<?php echo esc_attr($value); ?>" data-user-id="<?php echo esc_attr($user->ID); ?>">
                                    <div class="meta-key">
                                        <?php if ($is_hidden): ?>
                                            <span class="meta-hidden-badge"><?php esc_html_e('Hidden', 'wpswitchboard'); ?></span>
                                        <?php endif; ?>
                                        <?php if ($is_protected): ?>
                                            <span class="meta-protected-badge"><?php esc_html_e('Protected', 'wpswitchboard'); ?></span>
                                        <?php endif; ?>
                                        <code><?php echo esc_html($key); ?></code>
                                    </div>
                                    <div class="meta-value <?php echo esc_attr($value_class); ?>">
                                        <pre class="meta-display"><?php echo esc_html($display_value); ?></pre>
                                        <div class="meta-edit-wrapper" style="display: none; position: relative; flex: 1;">
                                            <textarea class="meta-edit"><?php echo esc_textarea(is_array($value) || is_object($value) ? json_encode($value, JSON_PRETTY_PRINT) : $value); ?></textarea>
                                            <?php /* translators: %1$s: Esc key label, %2$s: Ctrl/Cmd+Enter key label */ ?>
                                            <span class="meta-edit-hint"><?php printf(esc_html__('Press %1$s to cancel, %2$s to save', 'wpswitchboard'), '<kbd>Esc</kbd>', '<kbd>Ctrl/Cmd+Enter</kbd>'); ?></span>
                                        </div>
                                        <div class="meta-actions">
                                            <button type="button" class="button button-small copy-meta-btn" data-value="<?php echo esc_attr(is_array($value) || is_object($value) ? json_encode($value) : $value); ?>" title="Copy value">
                                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                                                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                                                </svg>
                                            </button>
                                            <button type="button" class="button button-small edit-meta-btn" title="Edit">
                                                Edit
                                            </button>
                                            <?php if (!$is_protected): ?>
                                            <button type="button" class="button button-small delete-meta-btn" title="Delete">
                                                Delete
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                            ?>
                        </div>

                        <div class="meta-stats">
                            <span><?php esc_html_e('Visible:', 'wpswitchboard'); ?> <strong><?php echo esc_html($visible_count); ?></strong></span>
                            <span><?php esc_html_e('Hidden:', 'wpswitchboard'); ?> <strong><?php echo esc_html($hidden_count); ?></strong></span>
                            <span><?php esc_html_e('Total:', 'wpswitchboard'); ?> <strong><?php echo esc_html(count($meta_data)); ?></strong></span>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <script>
        jQuery(document).ready(function($) {
            const nonce = '<?php echo esc_attr(wp_create_nonce('switchboard_user_meta')); ?>';

            // Search functionality
            $('#meta-search').on('keyup', function() {
                var searchTerm = $(this).val().toLowerCase();

                $('.meta-row').each(function() {
                    var key = $(this).data('key').toLowerCase();
                    var value = $(this).data('value').toString().toLowerCase();

                    if (key.includes(searchTerm) || value.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });

            // Copy meta value
            $('.copy-meta-btn').on('click', function() {
                var value = $(this).data('value');
                var textarea = document.createElement('textarea');
                textarea.value = value;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                var btn = $(this);
                var originalIcon = btn.html();
                btn.html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg>');
                btn.css('color', '#16a34a');
                setTimeout(function() {
                    btn.html(originalIcon);
                    btn.css('color', '');
                }, 1500);
            });

            // Edit meta value
            $('.edit-meta-btn').on('click', function() {
                var $row = $(this).closest('.meta-row');
                var $display = $row.find('.meta-display');
                var $editWrapper = $row.find('.meta-edit-wrapper');
                var $edit = $row.find('.meta-edit');
                var $btn = $(this);

                if ($editWrapper.is(':visible')) {
                    // Save mode
                    saveMetaEdit($row);
                } else {
                    // Edit mode - store original value
                    $row.data('original-value', $edit.val());
                    $display.hide();
                    $editWrapper.show();
                    $edit.focus();
                    $btn.html('Save').attr('title', '<?php echo esc_js(__('Save', 'wpswitchboard')); ?>');
                }
            });

            // Handle ESC and Enter keys in edit mode
            $(document).on('keydown', '.meta-edit', function(e) {
                var $edit = $(this);
                var $row = $edit.closest('.meta-row');
                var $display = $row.find('.meta-display');
                var $editWrapper = $row.find('.meta-edit-wrapper');
                var $btn = $row.find('.edit-meta-btn');

                if (e.key === 'Escape') {
                    // Cancel edit - revert to original value
                    e.preventDefault();
                    var originalValue = $row.data('original-value');
                    $edit.val(originalValue);
                    $editWrapper.hide();
                    $display.show();
                    $btn.html('Edit').attr('title', '<?php echo esc_js(__('Edit', 'wpswitchboard')); ?>');
                } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
                    // Save with Ctrl/Cmd + Enter
                    e.preventDefault();
                    saveMetaEdit($row);
                }
            });

            // Save meta edit function
            function saveMetaEdit($row) {
                var $display = $row.find('.meta-display');
                var $editWrapper = $row.find('.meta-edit-wrapper');
                var $edit = $row.find('.meta-edit');
                var $btn = $row.find('.edit-meta-btn');
                var userId = $row.data('user-id');
                var metaKey = $row.data('key');
                var metaValue = $edit.val();

                $btn.prop('disabled', true).html('...');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_update_user_meta',
                        nonce: nonce,
                        user_id: userId,
                        meta_key: metaKey,
                        meta_value: metaValue
                    },
                    success: function(response) {
                        if (response.success) {
                            $display.text(metaValue).show();
                            $editWrapper.hide();
                            $btn.html('Edit').attr('title', '<?php echo esc_js(__('Edit', 'wpswitchboard')); ?>').prop('disabled', false);

                            // Show success message
                            showNotice('<?php echo esc_js(__('Meta updated successfully', 'wpswitchboard')); ?>', 'success');
                        } else {
                            alert('<?php echo esc_js(__('Error:', 'wpswitchboard')); ?> ' + response.data.message);
                            $btn.html('Save').attr('title', '<?php echo esc_js(__('Save', 'wpswitchboard')); ?>').prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('Error updating meta. Please try again.', 'wpswitchboard')); ?>');
                        $btn.html('Save').attr('title', '<?php echo esc_js(__('Save', 'wpswitchboard')); ?>').prop('disabled', false);
                    }
                });
            }

            // Delete meta value
            $('.delete-meta-btn').on('click', function() {
                var $row = $(this).closest('.meta-row');
                var userId = $row.data('user-id');
                var metaKey = $row.data('key');

                if (!confirm('<?php echo esc_js(__('Are you sure you want to delete the meta key', 'wpswitchboard')); ?> "' + metaKey + '"?')) {
                    return;
                }

                var $btn = $(this);
                $btn.prop('disabled', true).html('...');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_delete_user_meta',
                        nonce: nonce,
                        user_id: userId,
                        meta_key: metaKey
                    },
                    success: function(response) {
                        if (response.success) {
                            $row.fadeOut(300, function() {
                                $(this).remove();
                            });
                            showNotice('<?php echo esc_js(__('Meta deleted successfully', 'wpswitchboard')); ?>', 'success');
                        } else {
                            alert('<?php echo esc_js(__('Error:', 'wpswitchboard')); ?> ' + response.data.message);
                            $btn.html('Delete').prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('Error deleting meta. Please try again.', 'wpswitchboard')); ?>');
                        $btn.html('Delete').prop('disabled', false);
                    }
                });
            });

            // Toggle hidden meta
            $('#toggle-hidden-meta').on('click', function() {
                $('.meta-hidden').toggle();
                var isHidden = $('.meta-hidden').is(':visible');
                $(this).text(isHidden ? '<?php echo esc_js(__('Hide', 'wpswitchboard')); ?> <?php echo esc_js(__('Hidden Meta', 'wpswitchboard')); ?>' : '<?php echo esc_js(__('Show', 'wpswitchboard')); ?> <?php echo esc_js(__('Hidden Meta', 'wpswitchboard')); ?>');
            });

            // Show notice helper
            function showNotice(message, type) {
                var $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
                $('.wrap h1').after($notice);
                setTimeout(function() {
                    $notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                }, 3000);
            }

            // Add New User Meta Field handlers
            $('#add-new-user-meta-btn').on('click', function() {
                $('#add-user-meta-form').slideDown(200);
                $('#new-user-meta-key').focus();
            });

            $('#cancel-new-user-meta-btn').on('click', function() {
                $('#add-user-meta-form').slideUp(200);
                $('#new-user-meta-key').val('');
                $('#new-user-meta-value').val('');
            });

            $('#save-new-user-meta-btn').on('click', function() {
                var $btn = $(this);
                var metaKey = $('#new-user-meta-key').val().trim();
                var metaValue = $('#new-user-meta-value').val();
                var userId = <?php echo esc_attr($user->ID); ?>;

                if (!metaKey) {
                    alert('<?php echo esc_js(__('Please enter a meta key', 'wpswitchboard')); ?>');
                    return;
                }

                $btn.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'wpswitchboard')); ?>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_update_user_meta',
                        nonce: nonce,
                        user_id: userId,
                        meta_key: metaKey,
                        meta_value: metaValue
                    },
                    success: function(response) {
                        if (response.success) {
                            showNotice('<?php echo esc_js(__('Meta field added successfully! Refreshing...', 'wpswitchboard')); ?>', 'success');
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            alert('<?php echo esc_js(__('Error:', 'wpswitchboard')); ?> ' + response.data.message);
                            $btn.prop('disabled', false).text('<?php echo esc_js(__('Save Meta Field', 'wpswitchboard')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('Error adding meta field. Please try again.', 'wpswitchboard')); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Save Meta Field', 'wpswitchboard')); ?>');
                    }
                });
            });
        });
        </script>
        <?php
    }

    /**
     * Add custom styles to profile pages
     */
    public function add_profile_styles() {
        ?>
        <style>
        .switchboard-meta-search-box {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }

        .switchboard-meta-search-box input {
            flex: 1;
            max-width: 400px;
        }

        .add-meta-form {
            background: var(--primary-50);
            border: 2px solid #2271b1;
            border-radius: 4px;
            padding: 16px;
            margin-bottom: 16px;
        }

        .add-meta-form h4 {
            color: #1d2327;
            font-size: 14px;
            font-weight: 600;
        }

        .add-meta-fields {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;
        }

        .add-meta-field {
            flex: 1;
        }

        .add-meta-field label {
            display: block;
            font-weight: 500;
            margin-bottom: 6px;
            color: #1d2327;
            font-size: 13px;
        }

        .add-meta-field input,
        .add-meta-field textarea {
            width: 100%;
            box-sizing: border-box;
        }

        .add-meta-actions {
            display: flex;
            gap: 8px;
        }

        .switchboard-meta-container {
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
            max-height: 600px;
            overflow-y: auto;
        }

        .meta-row {
            display: flex;
            gap: 20px;
            padding: 12px 16px;
            border-bottom: 1px solid #e5e5e5;
            background: white;
            align-items: flex-start;
        }

        .meta-row:last-child {
            border-bottom: none;
        }

        .meta-row:hover {
            background: var(--primary-50);
        }

        .meta-key {
            flex: 0 0 250px;
            font-weight: 500;
            word-break: break-word;
        }

        .meta-key code {
            background: #f3f4f6;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 12px;
            display: inline-block;
        }

        .meta-hidden-badge {
            display: inline-block;
            background: #fbbf24;
            color: #78350f;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-right: 6px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .meta-value {
            flex: 1;
            position: relative;
            display: flex;
            gap: 10px;
            align-items: flex-start;
        }

        .meta-value pre {
            margin: 0;
            padding: 8px;
            background: #1f2937;
            color: #f9fafb;
            border-radius: 4px;
            font-size: 12px;
            max-width: 100%;
            overflow-x: auto;
            flex: 1;
            max-height: 200px;
            overflow-y: auto;
        }

        .meta-value-simple pre {
            background: transparent;
            color: #374151;
            padding: 0;
            font-family: inherit;
        }

        .meta-edit-wrapper {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .meta-value textarea.meta-edit {
            width: 100%;
            min-height: 80px;
            max-height: 300px;
            padding: 8px;
            font-family: monospace;
            font-size: 12px;
            border: 2px solid #2271b1;
            border-radius: 4px;
            resize: vertical;
            box-sizing: border-box;
        }

        .meta-edit-hint {
            font-size: 11px;
            color: #6b7280;
        }

        .meta-edit-hint kbd {
            display: inline-block;
            padding: 2px 6px;
            background: #f3f4f6;
            border: 1px solid #d1d5db;
            border-radius: 3px;
            font-family: monospace;
            font-size: 10px;
            font-weight: 600;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        .meta-actions {
            display: flex;
            gap: 4px;
            flex-shrink: 0;
        }

        .meta-actions .button {
            padding: 4px 8px;
            height: auto;
            line-height: 1.4;
            font-size: 14px;
            min-width: 32px;
            border-radius: 3px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .meta-actions .button svg {
            display: block;
        }

        .meta-actions .copy-meta-btn:hover {
            background: var(--primary-50);
            border-color: #2271b1;
            color: #2271b1;
        }

        .meta-actions .edit-meta-btn:hover {
            background: #fef3c7;
            border-color: #f59e0b;
        }

        .meta-actions .delete-meta-btn:hover {
            background: #fef2f2;
            border-color: #dc2626;
            color: #dc2626;
        }

        .meta-protected-badge {
            display: inline-block;
            background: var(--primary-100);
            color: var(--primary-900);
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-right: 6px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .meta-stats {
            display: flex;
            gap: 20px;
            padding: 12px 16px;
            background: #f3f4f6;
            border-radius: 0 0 4px 4px;
            font-size: 13px;
            color: #6b7280;
        }

        .meta-stats strong {
            color: #1f2937;
        }

        .meta-hidden {
            display: none;
        }
        </style>
        <?php
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        // This module displays/edits existing user meta, doesn't store its own data
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }

    /**
     * Render settings panel for User Meta Display
     * 
     * Displays comprehensive informational UI explaining the module's features with:
     * - Module description and purpose (view/edit/delete user metadata)
     * - Step-by-step "How to Use" instructions
     * - Features list with 6 key capabilities (view, edit, delete, search, toggle, copy)
     * - Modern card-based layout with color-coded sections
     * - Emoji indicators for visual guidance
     * 
     * This is a configuration-free module (no user settings to save). It automatically
     * adds a "User Metadata" section to WordPress user profile pages (both own profile
     * and when editing other users) that displays all user meta fields in an organized,
     * searchable interface.
     * 
     * The module provides:
     * - Complete user meta display in sortable table format
     * - Real-time search/filter functionality via JavaScript
     * - Inline editing via AJAX (modal dialog with textarea)
     * - Delete functionality with confirmation (AJAX)
     * - Toggle to show/hide underscore-prefixed (private) meta fields
     * - Copy-to-clipboard for meta keys and values
     * - Protection against deleting core WordPress meta fields
     * - Organized by source (WordPress core, plugins, custom)
     * 
     * AJAX handlers:
     * - ajax_update_user_meta: Updates meta values with nonce verification
     * - ajax_delete_user_meta: Deletes meta with protected field checks
     * 
     * The UI includes extensive inline CSS and JavaScript for rich interactivity
     * without requiring additional asset files. Styling matches WordPress admin
     * design patterns while providing modern UX enhancements.
     * 
     * @param array $settings Current module settings (unused - no settings to save)
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        ?>
        <input type="hidden" name="module" value="user-meta-display">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">User Meta Display</h4>
            <p class="sb-sp-description" style="margin: 0;">This module displays user metadata directly on the user profile pages. No settings panel needed! Just enable the module and it will automatically add a "User Metadata" section to all user profile pages.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">How to Use</h3>
            <ol class="sb-sp-list" style="margin: 0; padding-left: 20px;">
                <li class="sb-sp-list-item"><?php esc_html_e('Enable this module (just toggle it ON)', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php /* translators: %s: menu path "Users - All Users" */ printf(esc_html__('Go to %s', 'wpswitchboard'), '<strong>' . esc_html__('Users → All Users', 'wpswitchboard') . '</strong>'); ?></li>
                <li class="sb-sp-list-item"><?php /* translators: %s: "Edit" link label */ printf(esc_html__('Click %s on any user', 'wpswitchboard'), '<strong>' . esc_html__('Edit', 'wpswitchboard') . '</strong>'); ?></li>
                <li class="sb-sp-list-item"><?php /* translators: %s: "User Metadata" section name */ printf(esc_html__('Scroll down to see the %s section', 'wpswitchboard'), '<strong>"' . esc_html__('User Metadata', 'wpswitchboard') . '"</strong>'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('View, edit, or delete any meta fields!', 'wpswitchboard'); ?></li>
            </ol>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Features</h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong><?php esc_html_e('View all metadata', 'wpswitchboard'); ?></strong> - <?php esc_html_e('See every meta field for any user', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Edit meta values', 'wpswitchboard'); ?></strong> - <?php esc_html_e('Click the edit button to modify values', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Delete meta', 'wpswitchboard'); ?></strong> - <?php esc_html_e('Remove unnecessary meta fields (protected fields are safe)', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Search & Filter', 'wpswitchboard'); ?></strong> - <?php esc_html_e('Quickly find specific meta keys or values', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Toggle hidden fields', 'wpswitchboard'); ?></strong> - <?php esc_html_e('Show/hide underscore-prefixed meta', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Copy values', 'wpswitchboard'); ?></strong> - <?php esc_html_e('Easy copy-to-clipboard functionality', 'wpswitchboard'); ?></li>
            </ul>
        </div>
        <?php
    }
}

$switchboard_instance = new SwitchboardUserMetaDisplay();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
