<?php
/**
 * Name: Alphabet Avatars
 * Description: Replace default WordPress avatars with colorful letter-based avatars using user initials site-wide in comments, author boxes, and admin for better visual identification
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Colorful Default Avatars",
 *     "description": "Display attractive letter-based avatars for users without profile pictures, making your site look more polished and professional."
 *   },
 *   {
 *     "title": "Easy User Recognition",
 *     "description": "Help users quickly identify each other by their initials and unique background colors in comments and member lists."
 *   }
 * ]
 * Added: 2025-10-02
 * Tags: avatar, profile, user, initials, letters, gravatar
 * WhereToFind: {
 *   "location": "Comments & User Lists",
 *   "url": "/",
 *   "instructions": "View comments or user profiles - letter-based avatars appear",
 *   "newTab": true
 * }
 */

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

class SwitchboardAlphabetAvatars {
    
    public function __construct() {
        add_filter('get_avatar', [$this, 'get_alphabet_avatar'], 10, 6);
        add_filter('avatar_defaults', [$this, 'add_default_avatar']);
        add_action('admin_head', [$this, 'admin_avatar_styles']);
        add_action('wp_head', [$this, 'frontend_avatar_styles']);
        
        // 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_alphabet-avatars_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    public function admin_avatar_styles() {
        echo '<style>
            /* Remove white background from alphabet avatars in admin bar */
            #wpadminbar #wp-admin-bar-my-account.with-avatar > .ab-empty-item img,
            #wpadminbar #wp-admin-bar-my-account.with-avatar > a img {
                background: none !important;
                border: none !important;
            }
        </style>';
    }

    public function frontend_avatar_styles() {
        echo '<style>
            /* Remove white background from alphabet avatars in admin bar on frontend */
            #wpadminbar #wp-admin-bar-my-account.with-avatar > .ab-empty-item img,
            #wpadminbar #wp-admin-bar-my-account.with-avatar > a img {
                background: none !important;
                border: none !important;
            }
        </style>';
    }
    
    public function add_default_avatar($avatar_defaults) {
        $avatar_defaults['alphabet'] = __('Alphabet Avatar (Initials)', 'wpswitchboard');
        return $avatar_defaults;
    }
    
    public function get_alphabet_avatar($avatar, $id_or_email, $size, $default, $alt, $args) {
        $settings = get_option('switchboard_alphabet-avatars_settings', []);
        $letter_source = isset($settings['letter_source']) ? $settings['letter_source'] : 'first_last';
        $color_mode = isset($settings['color_mode']) ? $settings['color_mode'] : 'random';
        $custom_color = isset($settings['custom_color']) ? $settings['custom_color'] : '#3498db';
        $shape = isset($settings['shape']) ? $settings['shape'] : 'circle';
        $avatar_size = isset($settings['size']) ? $settings['size'] : 'regular';
        
        // Calculate font size and padding based on size setting
        if ($avatar_size === 'small') {
            $font_size_ratio = 0.45;
            $padding_ratio = 0.15;
        } else {
            $font_size_ratio = 0.5;
            $padding_ratio = 0.2;
        }
        
        // Get user data
        $user = false;
        if (is_numeric($id_or_email)) {
            $user = get_user_by('id', $id_or_email);
        } elseif (is_object($id_or_email)) {
            if (!empty($id_or_email->user_id)) {
                $user = get_user_by('id', $id_or_email->user_id);
            }
        } elseif (is_string($id_or_email)) {
            $user = get_user_by('email', $id_or_email);
        }
        
        if (!$user) {
            return $avatar; // Return default if no user found
        }
        
        // Get initials based on settings
        $initials = $this->get_initials($user, $letter_source);
        
        // Generate color based on mode
        if ($color_mode === 'custom') {
            $color = $custom_color;
        } else {
            $color = $this->generate_color($user->ID);
        }
        
        // Generate SVG avatar
        $svg = $this->generate_svg_avatar($initials, $color, $size, $shape, $font_size_ratio);
        
        // Return as data URI
        $avatar = sprintf(
            '<img alt="%s" src="data:image/svg+xml;base64,%s" class="avatar avatar-%d photo" height="%d" width="%d" loading="lazy" decoding="async" />',
            esc_attr($alt),
            base64_encode($svg),
            $size,
            $size,
            $size
        );
        
        return $avatar;
    }
    
    private function get_initials($user, $source) {
        switch ($source) {
            case 'username':
                // First 2 letters of username
                return strtoupper(substr($user->user_login, 0, 2));
                
            case 'display_name':
                // First 2 letters of display name
                return strtoupper(substr($user->display_name, 0, 2));
                
            case 'first_last':
                // First letter of first name + first letter of last name
                $first_name = get_user_meta($user->ID, 'first_name', true);
                $last_name = get_user_meta($user->ID, 'last_name', true);
                
                if (!empty($first_name) && !empty($last_name)) {
                    return strtoupper(substr($first_name, 0, 1) . substr($last_name, 0, 1));
                } elseif (!empty($first_name)) {
                    return strtoupper(substr($first_name, 0, 2));
                } else {
                    // Fallback to username
                    return strtoupper(substr($user->user_login, 0, 2));
                }
                
            case 'full_name':
                // First letter of each word in display name
                $words = explode(' ', $user->display_name);
                $initials = '';
                foreach ($words as $word) {
                    if (!empty($word)) {
                        $initials .= strtoupper(substr($word, 0, 1));
                        if (strlen($initials) >= 2) break;
                    }
                }
                return $initials ?: strtoupper(substr($user->user_login, 0, 2));
                
            default:
                return strtoupper(substr($user->user_login, 0, 2));
        }
    }
    
    private function generate_color($user_id) {
        // Generate consistent color based on user ID
        $colors = [
            '#1abc9c', '#2ecc71', '#3498db', '#9b59b6', '#34495e',
            '#16a085', '#27ae60', '#2980b9', '#8e44ad', '#2c3e50',
            '#f1c40f', '#e67e22', '#e74c3c', '#95a5a6', '#f39c12',
            '#d35400', '#c0392b', '#7f8c8d', '#00b894', '#0984e3',
            '#6c5ce7', '#fd79a8', '#fdcb6e', '#e17055', '#74b9ff'
        ];
        
        return $colors[$user_id % count($colors)];
    }
    
    private function generate_svg_avatar($initials, $color, $size, $shape, $font_size_ratio) {
        $font_size = $size * $font_size_ratio;
        
        // Determine shape
        $shape_element = '';
        if ($shape === 'circle') {
            $radius = $size / 2;
            $shape_element = sprintf('<circle cx="%d" cy="%d" r="%d" fill="%s"/>', $radius, $radius, $radius, $color);
        } elseif ($shape === 'rounded') {
            // Rounded square (20% border radius)
            $border_radius = $size * 0.2;
            $shape_element = sprintf('<rect width="%d" height="%d" rx="%d" ry="%d" fill="%s"/>', $size, $size, $border_radius, $border_radius, $color);
        } else {
            // Square
            $shape_element = sprintf('<rect width="%d" height="%d" fill="%s"/>', $size, $size, $color);
        }
        
        $svg = sprintf(
            '<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d">
                %s
                <text x="50%%" y="50%%" font-family="-apple-system, BlinkMacSystemFont, \'Segoe UI\', Arial, sans-serif" font-size="%d" font-weight="600" fill="#ffffff" text-anchor="middle" dominant-baseline="central">%s</text>
            </svg>',
            $size,
            $size,
            $size,
            $size,
            $shape_element,
            $font_size,
            esc_html($initials)
        );
        
        return $svg;
    }

    /**
     * Render settings panel for Alphabet Avatars
     * 
     * Displays comprehensive avatar customization options with:
     * - Live preview showing current user's avatar
     * - Letter source dropdown (first+last name, username, display name)
     * - Color mode dropdown (random per user or custom single color)
     * - Color picker (conditional display when custom mode selected)
     * - Shape dropdown (circle or rounded square)
     * - Size dropdown (small compact or regular)
     * - Informational note about Gravatar replacement
     * - JavaScript function to toggle color picker visibility
     * 
     * This module replaces WordPress default avatars (Gravatars) with colorful
     * letter-based SVG avatars using user initials. Uses get_avatar filter to
     * intercept avatar requests and generate custom SVG images on-the-fly.
     * 
     * Avatar generation process:
     * - Extracts initials based on letter_source setting
     * - Generates background color (random hash-based or custom)
     * - Creates inline SVG with circle/rounded rect shape
     * - Returns base64-encoded data URI for <img> src
     * 
     * Settings control:
     * - letter_source: How to extract letters (first_last/username/display_name)
     * - color_mode: random (unique per user) or custom (same for all)
     * - custom_color: Hex color when color_mode is custom
     * - shape: circle or rounded (rounded square)
     * - size: small (compact padding) or regular (recommended)
     * 
     * The preview uses get_avatar() to show live avatar for current logged-in user.
     * 
     * @param array $settings Current module settings
     * @return void Outputs HTML directly with inline JavaScript
     */
    public function render_settings($settings = []) {
        $letter_source = isset($settings['letter_source']) ? $settings['letter_source'] : 'first_last';
        $color_mode = isset($settings['color_mode']) ? $settings['color_mode'] : 'random';
        $custom_color = isset($settings['custom_color']) ? $settings['custom_color'] : '#3498db';
        $shape = isset($settings['shape']) ? $settings['shape'] : 'circle';
        $size = isset($settings['size']) ? $settings['size'] : 'regular';
        
        $current_user = wp_get_current_user();
        ?>
        <input type="hidden" name="module" value="alphabet-avatars">

        <div class="sb-sp-card" style="margin-bottom: 24px;">
            <div class="sb-sp-card-body">
                <h4 class="sb-sp-heading-sm" style="margin: 0 0 12px 0;"><?php esc_html_e('Preview', 'wpswitchboard'); ?></h4>
                <div style="display: flex; align-items: center; gap: 16px;">
                    <?php echo get_avatar($current_user->ID, 64); ?>
                    <div>
                        <p style="margin: 0 0 4px 0; font-weight: 600; font-size: 14px;"><?php echo esc_html($current_user->display_name); ?></p>
                        <p class="sb-sp-description" style="margin: 0; font-size: 12px;"><?php esc_html_e('Your avatar will update when you save settings', 'wpswitchboard'); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_letter_source" class="sb-sp-label"><?php esc_html_e('Letter Source', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose how to generate the letters for the avatar.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_letter_source" id="setting_letter_source" class="sb-sp-select">
                <option value="first_last" <?php selected($letter_source, 'first_last'); ?>><?php esc_html_e('First + Last Name Initials (Recommended)', 'wpswitchboard'); ?></option>
                <option value="username" <?php selected($letter_source, 'username'); ?>><?php esc_html_e('Username (first 2 letters)', 'wpswitchboard'); ?></option>
                <option value="display_name" <?php selected($letter_source, 'display_name'); ?>><?php esc_html_e('Display Name (first 2 letters)', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_color_mode" class="sb-sp-label"><?php esc_html_e('Background Color', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose between random colors or a single custom color.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_color_mode" id="setting_color_mode" class="sb-sp-select" onchange="toggleColorPicker(this.value)">
                <option value="random" <?php selected($color_mode, 'random'); ?>><?php esc_html_e('Random Colors (Each user gets unique color)', 'wpswitchboard'); ?></option>
                <option value="custom" <?php selected($color_mode, 'custom'); ?>><?php esc_html_e('Custom Color (Same for all users)', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">

            <div id="custom-color-picker" style="margin-top: 16px; <?php echo ($color_mode === 'custom' ? '' : 'display: none;'); ?>">
                <label for="setting_custom_color" class="sb-sp-label"><?php esc_html_e('Custom Background Color', 'wpswitchboard'); ?></label>
                <div style="display: flex; align-items: center; gap: 12px;">
                    <input type="color" name="setting_custom_color" id="setting_custom_color" value="<?php echo esc_attr($custom_color); ?>" data-default="#6366f1" style="width: 60px; height: 40px; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">
                    <input type="text" value="<?php echo esc_attr($custom_color); ?>" id="custom-color-text" style="width: 100px; padding: 8px; border: 1px solid #d1d5db; border-radius: 4px; font-family: monospace; font-size: 13px;" readonly>
                </div>
                <p class="sb-sp-description"><?php esc_html_e('Pick a color for all avatar backgrounds.', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_shape" class="sb-sp-label"><?php esc_html_e('Avatar Shape', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose the shape of the avatar.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_shape" id="setting_shape" class="sb-sp-select">
                <option value="circle" <?php selected($shape, 'circle'); ?>><?php esc_html_e('Circle', 'wpswitchboard'); ?></option>
                <option value="rounded" <?php selected($shape, 'rounded'); ?>><?php esc_html_e('Rounded Square', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_size" class="sb-sp-label"><?php esc_html_e('Avatar Size', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose the size and padding of the avatar.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_size" id="setting_size" class="sb-sp-select">
                <option value="small" <?php selected($size, 'small'); ?>><?php esc_html_e('Small (Compact)', 'wpswitchboard'); ?></option>
                <option value="regular" <?php selected($size, 'regular'); ?>><?php esc_html_e('Regular (Recommended)', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Note', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('This module replaces default WordPress avatars (Gravatars) with colorful letter-based avatars. Users without profile pictures will see their initials in a colorful avatar.', 'wpswitchboard'); ?></p>
        </div>
        
        <script>
        function toggleColorPicker(mode) {
            var picker = document.getElementById("custom-color-picker");
            if (mode === "custom") {
                picker.style.display = "block";
            } else {
                picker.style.display = "none";
            }
        }
        
        // Sync color picker and text input
        jQuery(document).ready(function($) {
            $('#setting_custom_color').on('change', function() {
                $('#custom-color-text').val($(this).val());
            });
            $('#custom-color-text').on('input', function() {
                var color = $(this).val();
                if (/^#[0-9A-F]{6}$/i.test(color)) {
                    $('#setting_custom_color').val(color);
                }
            });
        });
        </script>
        <?php
    }
}

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

