<?php
/**
 * Name: Hide Admin Bar (By Role)
 * Description: Hide admin bar on the frontend for specific user roles like subscribers, contributors, or custom roles while keeping it visible for administrators and editors
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Clean Contributor View",
 *     "description": "Hide admin bar from Contributors and Authors who only write content, giving them cleaner frontend preview without backend distractions."
 *   },
 *   {
 *     "title": "Customer Account Pages",
 *     "description": "Remove admin bar from Customers and Subscribers viewing WooCommerce account pages to maintain professional frontend appearance."
 *   },
 *   {
 *     "title": "Editor-Only Toolbar",
 *     "description": "Show admin bar only to Editors and Administrators who need quick access, while other roles see clean site design."
 *   }
 * ]
 * WhereToFind: {
 *   "location": "Frontend (Top of Page)",
 *   "url": "/",
 *   "instructions": "Visit frontend while logged in to see admin bar hidden for selected roles",
 *   "newTab": true
 * }
 * Added: 2025-07-08
 * Tags: admin-bar, roles, hide, ui, toolbar, frontend
 */

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

class SwitchboardHideAdminBarRoles {

    public function __construct() {
        // Use show_admin_bar filter - only affects frontend
        add_filter('show_admin_bar', [$this, 'hide_admin_bar']);
        
        // 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_hide-admin-bar-roles_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel
     * 
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $selected_roles = isset($settings['roles']) ? explode(',', $settings['roles']) : ['subscriber'];
        $selected_roles = array_map('trim', $selected_roles);
        $all_roles = wp_roles()->get_names();
        ?>
        <input type="hidden" name="module" value="hide-admin-bar-roles">
        <input type="hidden" name="setting_roles" id="setting_roles" value="<?php echo esc_attr(implode(',', $selected_roles)); ?>">

        <?php
        // Check if the global "Disable Admin Bar (Frontend)" module is active
        $active_modules = get_option('switchboard_active_modules', []);
        if (in_array('disable-admin-bar-frontend', $active_modules, true)) : ?>
            <div class="sb-sp-alert sb-sp-alert-warning">
                <strong><?php esc_html_e('Conflict Detected:', 'wpswitchboard'); ?></strong>
                <?php esc_html_e('The "Disable Admin Bar (Frontend)" module is currently active, which hides the admin bar for ALL users. This role-based module will have no effect until you disable that module.', 'wpswitchboard'); ?>
            </div>
        <?php endif; ?>

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Select Roles to Hide Admin Bar', 'wpswitchboard'); ?></label>
            <div class="switchboard-tag-selector" data-input-id="setting_roles">
            <div class="switchboard-selected-tags" id="selected-roles">
                <?php foreach ($selected_roles as $role_slug):
                    if (isset($all_roles[$role_slug])): ?>
                        <span class="switchboard-tag" data-value="<?php echo esc_attr($role_slug); ?>">
                            <?php echo esc_html($all_roles[$role_slug]); ?> <span class="remove-tag">×</span>
                        </span>
                <?php endif; endforeach; ?>
            </div>
            <div class="switchboard-available-tags">
                <?php foreach ($all_roles as $role_slug => $role_name):
                    $is_selected = in_array($role_slug, $selected_roles) ? 'selected' : ''; ?>
                    <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($role_slug); ?>">
                        <?php echo esc_html($role_name); ?>
                    </span>
                <?php endforeach; ?>
            </div>
        </div>
        <p class="sb-sp-description"><?php esc_html_e('Select which user roles should have the admin bar hidden on the frontend.', 'wpswitchboard'); ?> <strong><?php esc_html_e('Note:', 'wpswitchboard'); ?></strong> <?php esc_html_e('The admin bar will always remain visible in the WordPress backend/admin area.', 'wpswitchboard'); ?></p>
        </div>
        <?php
    }

    public function hide_admin_bar($show) {
        $settings = get_option('switchboard_hide-admin-bar-roles_settings', []);
        $roles = isset($settings['roles']) && is_string($settings['roles'])
            ? explode(',', $settings['roles'])
            : ['subscriber'];

        // Trim whitespace from role names
        $roles = array_map('trim', $roles);

        $user = wp_get_current_user();

        // Validate user exists and has ID
        if (!$user || !isset($user->ID) || $user->ID === 0) {
            return $show;
        }

        // Validate roles property exists
        if (!isset($user->roles) || !is_array($user->roles)) {
            return $show;
        }

        $user_roles = (array) $user->roles;

        foreach ($user_roles as $role) {
            if (in_array($role, $roles, true)) {
                return false; // Hide admin bar
            }
        }

        return $show; // Keep current setting
    }
}

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