<?php
/**
 * Name: Admin Color Schemes
 * Description: Create custom admin color schemes with primary and secondary colors applied throughout WordPress dashboard including menu, buttons, links, and interface elements
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "White-Label Client Dashboards",
 *     "description": "Match the WordPress admin colors to each client's brand identity when building custom websites for multiple clients."
 *   },
 *   {
 *     "title": "Team Role Identification",
 *     "description": "Assign different color schemes to different team departments (blue for developers, green for content, purple for design) to quickly identify who's working in admin."
 *   },
 *   {
 *     "title": "Reduce Eye Strain",
 *     "description": "Create a custom dark purple or warm amber color scheme for editors who work late hours and find default blue too harsh."
 *   }
 * ]
 * Added: 2025-08-20
 * Tags: colors, admin, theme, customization, branding
 * WhereToFind: {
 *   "location": "Throughout Admin Area",
 *   "url": "",
 *   "instructions": "Configure colors in module settings. Custom colors apply throughout the entire admin - admin bar, menu, buttons, and links.",
 *   "newTab": false
 * }
 */

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

class SwitchboardAdminColorSchemes {
    
    public function __construct() {
        add_action('admin_init', [$this, 'register_color_scheme']);
        
        // 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_admin-color-schemes_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 = []) {
        $primary = isset($settings['primary_color']) ? $settings['primary_color'] : 'var(--primary-500)';
        $secondary = isset($settings['secondary_color']) ? $settings['secondary_color'] : 'var(--primary-600)';
        ?>
        <input type="hidden" name="module" value="admin-color-schemes">

        <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;">Create a custom admin color scheme for your WordPress admin area. After saving your colors, go to <strong>Users → Your Profile</strong> and select <strong>"Switchboard Custom"</strong> from the Admin Color Scheme dropdown to activate it.</p>
        </div>

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

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_primary_color"><?php esc_html_e('Primary Color', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Used for: Admin bar, active menu items, primary buttons', 'wpswitchboard'); ?></p>
            </div>
            <div style="display: flex; align-items: center; gap: 12px;">
                <input class="sb-sp-input-color" type="color" name="setting_primary_color" id="setting_primary_color" value="<?php echo esc_attr($primary); ?>" data-default="var(--primary-500)" style="width: 60px; height: 40px; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer;">
                <input type="text" value="<?php echo esc_attr($primary); ?>" readonly style="width: 100px; padding: 8px; border: 1px solid #e5e7eb; border-radius: 6px; font-family: monospace; font-size: 13px; background: #f9fafb;">
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_secondary_color"><?php esc_html_e('Secondary Color', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Used for: Links, button hover, menu hover states, form focus', 'wpswitchboard'); ?></p>
            </div>
            <div style="display: flex; align-items: center; gap: 12px;">
                <input class="sb-sp-input-color" type="color" name="setting_secondary_color" id="setting_secondary_color" value="<?php echo esc_attr($secondary); ?>" data-default="#64748b" style="width: 60px; height: 40px; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer;">
                <input type="text" value="<?php echo esc_attr($secondary); ?>" readonly style="width: 100px; padding: 8px; border: 1px solid #e5e7eb; border-radius: 6px; font-family: monospace; font-size: 13px; background: #f9fafb;">
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">How to Activate</h4>
            <p class="sb-sp-description" style="margin: 0;">After saving your colors, go to <strong>Users → Your Profile</strong> and select <strong>"Switchboard Custom"</strong> from the Admin Color Scheme dropdown to apply your custom colors.</p>
        </div>

        <div class="sb-sp-group" style="margin-top: 24px;">
            <button type="button" id="reset-color-schemes" class="sb-module-button sb-module-button-secondary">
                <?php esc_html_e('Reset to Default Colors', 'wpswitchboard'); ?>
            </button>
        </div>

        <script>
        jQuery(document).ready(function($) {
            // Sync color picker with text input
            $('#setting_primary_color').on('change', function() {
                $(this).next('input[type="text"]').val($(this).val());
            });
            $('#setting_secondary_color').on('change', function() {
                $(this).next('input[type="text"]').val($(this).val());
            });

            // Reset to default colors
            $('#reset-color-schemes').on('click', function() {
                var defaultPrimary = '#2271b1';
                var defaultSecondary = '#135e96';

                $('#setting_primary_color').val(defaultPrimary);
                $('#setting_primary_color').next('input[type="text"]').val(defaultPrimary);

                $('#setting_secondary_color').val(defaultSecondary);
                $('#setting_secondary_color').next('input[type="text"]').val(defaultSecondary);

                // Show feedback
                $(this).text('<?php esc_html_e('Reset! Click Save to apply.', 'wpswitchboard'); ?>');
                setTimeout(function() {
                    $('#reset-color-schemes').text('<?php esc_html_e('Reset to Default Colors', 'wpswitchboard'); ?>');
                }, 2000);
            });
        });
        </script>
        <?php
    }
    
    public function register_color_scheme() {
        $settings = get_option('switchboard_admin-color-schemes_settings', []);

        // Validate settings is array
        if (!is_array($settings)) {
            $settings = [];
        }

        // Sanitize and validate hex colors
        $primary = isset($settings['primary_color']) ? sanitize_hex_color($settings['primary_color']) : '';
        $primary = $primary ? $primary : '#2271b1';

        $secondary = isset($settings['secondary_color']) ? sanitize_hex_color($settings['secondary_color']) : '';
        $secondary = $secondary ? $secondary : '#135e96';

        wp_admin_css_color(
            'switchboard_custom',
            __('Switchboard Custom', 'wpswitchboard'),
            false,
            [$primary, $secondary, '#f0f0f1', '#ffffff'],
            ['base' => '#1d2327', 'focus' => '#ffffff', 'current' => '#ffffff']
        );

        // Color scheme is registered and available in user profile
        // Users can manually select it from Profile > Admin Color Scheme
        
        // Add custom CSS for the color scheme
        add_action('admin_head', function() use ($primary, $secondary) {
            ?>
            <style>
            /* Admin Bar - Primary Color */
            #wpadminbar {
                background: <?php echo esc_attr($primary); ?>;
            }
            
            /* Buttons - Primary with Secondary on Hover */
            .wp-core-ui .button-primary {
                background: <?php echo esc_attr($primary); ?>;
                border-color: <?php echo esc_attr($secondary); ?>;
            }
            .wp-core-ui .button-primary:hover,
            .wp-core-ui .button-primary:focus {
                background: <?php echo esc_attr($secondary); ?>;
                border-color: <?php echo esc_attr($secondary); ?>;
            }
            
            /* Admin Menu - Primary Color */
            #adminmenu .wp-has-current-submenu .wp-submenu .wp-submenu-head,
            #adminmenu .wp-menu-arrow,
            #adminmenu .wp-menu-arrow div,
            #adminmenu li.current a.menu-top,
            #adminmenu li.wp-has-current-submenu a.wp-has-current-submenu {
                background: <?php echo esc_attr($primary); ?>;
            }
            
            /* Admin Menu Hover - Secondary Color */
            #adminmenu li.menu-top:hover,
            #adminmenu li.opensub > a.menu-top,
            #adminmenu li > a.menu-top:focus {
                background: <?php echo esc_attr($secondary); ?>;
            }
            
            /* Links - Secondary Color */
            a {
                color: <?php echo esc_attr($secondary); ?>;
            }
            a:hover,
            a:focus {
                color: <?php echo esc_attr($primary); ?>;
            }
            
            /* Form Focus - Secondary Color */
            input[type="text"]:focus,
            input[type="email"]:focus,
            input[type="url"]:focus,
            input[type="password"]:focus,
            input[type="search"]:focus,
            input[type="number"]:focus,
            textarea:focus,
            select:focus {
                border-color: <?php echo esc_attr($secondary); ?>;
                box-shadow: 0 0 0 1px <?php echo esc_attr($secondary); ?>;
            }
            
            /* Checkboxes - Secondary Color */
            input[type="checkbox"]:checked::before {
                color: <?php echo esc_attr($secondary); ?>;
            }
            </style>
            <?php
        });
    }
}

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