<?php
/**
 * Name: Simplified User Profiles
 * Description: Clean up user profile pages by removing unnecessary default WordPress fields like biographical info, color schemes, and other clutter for streamlined interface
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Cleaner Profile Pages",
 *     "description": "Hide unnecessary WordPress default fields from user profiles to reduce clutter and confusion."
 *   },
 *   {
 *     "title": "Focus on Essentials",
 *     "description": "Show only the profile fields your users actually need, making profiles easier to complete and update."
 *   }
 * ]
 * Added: 2025-08-04
 * Tags: profile, users, clean, simplify, admin
 * WhereToFind: {
 *   "location": "User Profile Page",
 *   "url": "profile.php",
 *   "instructions": "Unnecessary fields removed from profile editor",
 *   "newTab": false
 * }
 */

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

class SwitchboardSimplifiedProfiles {

    public function __construct() {
        add_filter('user_contactmethods', [$this, 'remove_contact_methods'], 10, 1);
        add_action('admin_init', [$this, 'remove_profile_sections']);
        add_action('admin_head', [$this, 'hide_profile_fields']);
        
        // Register with data registry
        $this->register_with_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__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_simplified-profiles_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    private function get_settings() {
        return get_option('switchboard_simplified-profiles_settings', []);
    }

    public function remove_contact_methods($methods) {
        $settings = $this->get_settings();
        $remove = isset($settings['remove_fields']) ? $settings['remove_fields'] : '';

        // Handle empty string case
        if (empty($remove)) {
            return $methods;
        }

        $fields_to_remove = array_map('trim', explode(',', $remove));

        // Remove Website and other contact methods
        foreach ($fields_to_remove as $field) {
            if (!empty($field) && $field === 'url') {
                unset($methods[$field]);
            }
        }

        return $methods;
    }

    public function remove_profile_sections() {
        // This method is no longer needed - color scheme is handled in hide_profile_fields()
    }

    public function hide_profile_fields() {
        $settings = $this->get_settings();
        $remove = isset($settings['remove_fields']) ? $settings['remove_fields'] : '';
        $remove_color = isset($settings['remove_color_scheme']) ? $settings['remove_color_scheme'] : 'yes';

        // Build CSS to hide selected fields
        $css = '<style>';

        // Handle color scheme removal
        if ($remove_color === 'yes') {
            $css .= '.user-admin-color-wrap { display: none !important; }';
        }

        // Handle field removal
        if (!empty($remove)) {
            $fields_to_remove = array_map('trim', explode(',', $remove));

            foreach ($fields_to_remove as $field) {
                switch ($field) {
                    case 'description':
                        $css .= '.user-description-wrap { display: none !important; }';
                        break;
                    case 'url':
                        $css .= '.user-url-wrap { display: none !important; }';
                        break;
                    case 'rich_editing':
                        $css .= '.user-rich-editing-wrap { display: none !important; }';
                        break;
                    case 'syntax_highlighting':
                        $css .= '.user-syntax-highlighting-wrap { display: none !important; }';
                        break;
                    case 'comment_shortcuts':
                        $css .= '.user-comment-shortcuts-wrap { display: none !important; }';
                        break;
                    case 'admin_bar_front':
                        $css .= '.user-admin-bar-front-wrap { display: none !important; }';
                        break;
                }
            }
        }

        $css .= '</style>';

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS is sanitized by wp_strip_all_tags
        echo wp_strip_all_tags($css);
    }

    /**
     * Render settings panel for Simplified User Profiles
     * 
     * Displays comprehensive profile field removal configuration with:
     * - Tag selector interface for choosing fields to remove
     * - Available fields: Biographical Info, Website, Visual Editor, Syntax Highlighting,
     *   Comment Shortcuts, Show Toolbar on Frontend
     * - Selected/available tags with click-to-toggle functionality
     * - Hidden input to store comma-separated field list
     * - Additional option to remove Color Scheme picker with toggle switch
     * - Inline jQuery for tag selection and removal handling
     * 
     * This module cleans up WordPress user profile pages by hiding unnecessary default
     * fields. It uses two approaches:
     * 
     * 1. remove_contact_methods filter: Removes contact method fields by unsetting from array
     * 2. CSS hiding via admin_head: Injects inline styles to hide form table rows
     * 
     * The tag selector UI provides a modern, user-friendly way to select multiple fields:
     * - Top section shows selected fields (removable with × button)
     * - Bottom section shows available fields (clickable to add)
     * - jQuery handles click events and updates hidden comma-separated input
     * - CSS classes .selected and .switchboard-tag mark active selections
     * 
     * Color scheme removal is a separate toggle because it requires different handling
     * (remove_action on admin_color_scheme_picker hook in remove_profile_sections).
     * 
     * Settings stored:
     * - remove_fields: Comma-separated field slugs (description,url,rich_editing,etc)
     * - remove_color_scheme: yes/no toggle for color scheme picker
     * 
     * The module uses CSS selectors matching WordPress form table structure:
     * .user-{field}-wrap { display: none !important; }
     * 
     * @param array $settings Current module settings with 'remove_fields' and 'remove_color_scheme' keys
     * @return void Outputs HTML directly with inline jQuery
     */
    public function render_settings($settings = []) {
        $remove_fields = isset($settings['remove_fields']) ? $settings['remove_fields'] : '';
        $remove_color_scheme = isset($settings['remove_color_scheme']) ? $settings['remove_color_scheme'] : 'yes';

        // Convert comma-separated string to array
        $selected_fields = !empty($remove_fields) ? array_map('trim', explode(',', $remove_fields)) : [];

        // All available user profile fields
        // Note: These are fields that can actually be removed/hidden
        $available_fields = [
            'description' => __('Biographical Info', 'wpswitchboard'),
            'url' => __('Website', 'wpswitchboard'),
            'rich_editing' => __('Visual Editor', 'wpswitchboard'),
            'syntax_highlighting' => __('Syntax Highlighting', 'wpswitchboard'),
            'comment_shortcuts' => __('Comment Shortcuts', 'wpswitchboard'),
            'admin_bar_front' => __('Show Toolbar on Frontend', 'wpswitchboard')
        ];
        ?>
        <input type="hidden" name="module" value="simplified-profiles">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading"><?php esc_html_e('Simplified User Profiles', 'wpswitchboard'); ?></h3>
            <p class="sb-sp-description"><?php esc_html_e('Remove unnecessary fields from WordPress user profile pages to reduce clutter. Selected fields will be hidden from all user profiles.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <label class="sb-sp-label"><?php esc_html_e('Remove Fields', 'wpswitchboard'); ?></label>
            <p class="sb-sp-description" style="margin-bottom: 12px;"><?php esc_html_e('Click to select fields to remove from user profiles:', 'wpswitchboard'); ?></p>

        <input type="hidden" name="setting_remove_fields" id="setting_remove_fields" value="<?php echo esc_attr($remove_fields); ?>">

        <div class="switchboard-tag-selector sb-sp-my-4">
            <div class="switchboard-selected-tags" id="selected-profile-fields">
                <?php foreach ($selected_fields as $field_slug): ?>
                    <?php if (isset($available_fields[$field_slug])): ?>
                        <span class="switchboard-tag" data-value="<?php echo esc_attr($field_slug); ?>">
                            <?php echo esc_html($available_fields[$field_slug]); ?> <span class="remove-tag">×</span>
                        </span>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <div class="switchboard-available-tags">
                <?php foreach ($available_fields as $field_slug => $field_name): ?>
                    <?php $is_selected = in_array($field_slug, $selected_fields) ? 'selected' : ''; ?>
                    <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($field_slug); ?>">
                        <?php echo esc_html($field_name); ?>
                    </span>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="sb-sp-divider" style="margin: 24px 0;"></div>

        <div class="sb-module-option-item sb-module-toggle-item">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Remove Color Scheme Picker', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_remove_color_scheme" value="yes" <?php checked($remove_color_scheme, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Hide the "Admin Color Scheme" section from Personal Options in user profiles', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            // Handle tag selection
            $(".switchboard-tag-option").on("click", function() {
                var value = $(this).data("value");
                var text = $(this).text();

                if ($(this).hasClass("selected")) {
                    // Remove from selected
                    $(this).removeClass("selected");
                    $("#selected-profile-fields .switchboard-tag[data-value=\"" + value + "\"]").remove();
                } else {
                    // Add to selected
                    $(this).addClass("selected");
                    $("#selected-profile-fields").append("<span class=\"switchboard-tag\" data-value=\"" + value + "\">" + text + " <span class=\"remove-tag\">×</span></span>");
                }

                updateHiddenField();
            });

            // Handle tag removal
            $(document).on("click", ".remove-tag", function() {
                var value = $(this).parent().data("value");
                $(this).parent().remove();
                $(".switchboard-tag-option[data-value=\"" + value + "\"]").removeClass("selected");
                updateHiddenField();
            });

            function updateHiddenField() {
                var values = [];
                $("#selected-profile-fields .switchboard-tag").each(function() {
                    values.push($(this).data("value"));
                });
                $("#setting_remove_fields").val(values.join(","));
            }
        });
        </script>
        <?php
    }
}

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