<?php
/**
 * Name: Custom Admin CSS
 * Description: Add custom CSS styles to WordPress admin dashboard to modify colors, layouts, fonts, spacing, or hide elements for branding and improved experience
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Accessibility Improvements",
 *     "description": "Increase font sizes, adjust contrast ratios, and modify spacing for team members with visual impairments."
 *   },
 *   {
 *     "title": "Brand-Matched Admin",
 *     "description": "Apply client's brand fonts, colors, and styling throughout the admin area for fully white-labeled WordPress experience."
 *   },
 *   {
 *     "title": "Fix Plugin UI Issues",
 *     "description": "Override poorly-styled third-party plugin admin interfaces that clash with your workflow or have usability problems."
 *   }
 * ]
 * Added: 2025-06-28
 * Tags: css, admin, styling, customization, design
 * WhereToFind: {
 *   "location": "Throughout Admin Area",
 *   "url": "",
 *   "instructions": "Add custom CSS in module settings. Your styles apply across all admin pages.",
 *   "newTab": false
 * }
 */

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

class SwitchboardCustomAdminCss {

    public function __construct() {
        add_action('admin_head', [$this, 'add_custom_css']);

        // 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_custom-admin-css_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 = []) {
        $css = isset($settings['css']) ? $settings['css'] : '';
        ?>
        <input type="hidden" name="module" value="custom-admin-css">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin: 0;">Add custom CSS to style the WordPress admin area. Your CSS will be loaded on all admin pages, allowing you to customize the appearance, layout, and styling of the admin interface.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Custom CSS</h3>

            <label class="sb-sp-label" for="setting_css"><?php esc_html_e('CSS Code', 'wpswitchboard'); ?></label>
            <textarea name="setting_css" id="setting_css" rows="15" class="sb-sp-textarea" style="width: 100%; font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.6;"><?php echo esc_textarea($css); ?></textarea>
            <p class="sb-sp-description"><?php esc_html_e('Add custom CSS for WordPress admin area. Use standard CSS syntax.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Tips</h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><?php esc_html_e('Your CSS is loaded on all admin pages via the admin_head hook', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Use browser developer tools to inspect admin elements and find the right selectors', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Changes persist through theme updates since CSS is stored in the database', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Test your CSS changes in a staging environment first', 'wpswitchboard'); ?></li>
            </ul>
        </div>
        <?php
    }

    public function add_custom_css() {
        $settings = get_option('switchboard_custom-admin-css_settings', []);
        $css = isset($settings['css']) ? $settings['css'] : '';

        if (!empty($css)) {
            // Sanitize CSS: remove script tags, closing style tags, and XSS vectors
            // Note: Only admins with manage_options can edit this CSS
            $css = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $css);
            $css = preg_replace('/<\/style>/is', '', $css); // Prevent breaking out of style context
            $css = wp_strip_all_tags($css, true);

            // Remove dangerous CSS properties and functions (keep @import for legitimate use)
            $css = preg_replace('/javascript\s*:/i', '', $css);
            $css = preg_replace('/expression\s*\(/i', '', $css);
            $css = preg_replace('/behavior\s*:/i', '', $css);

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

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