<?php
/**
 * Name: Local User Avatar
 * Description: Use WordPress media library for user profile avatars instead of Gravatar service to host avatar images locally for privacy and avoid external dependencies
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Professional Profile Pictures",
 *     "description": "Let users upload custom avatars directly to your site instead of relying on Gravatar, giving you full control over profile images."
 *   },
 *   {
 *     "title": "Better Privacy",
 *     "description": "Keep user profile data on your own server instead of sending email addresses to third-party services like Gravatar."
 *   }
 * ]
 * Added: 2025-10-09
 * Tags: avatar, gravatar, profile, media, users
 * WhereToFind: {
 *   "location": "User Profile",
 *   "url": "profile.php",
 *   "instructions": "Avatar upload field appears in user profile editor",
 *   "newTab": false
 * }
 */

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

class SwitchboardLocalUserAvatar {
    
    public function __construct() {
        add_filter('get_avatar', [$this, 'get_local_avatar'], 10, 5);
        add_action('show_user_profile', [$this, 'add_avatar_field']);
        add_action('edit_user_profile', [$this, 'add_avatar_field']);
        add_action('personal_options_update', [$this, 'save_avatar']);
        add_action('edit_user_profile_update', [$this, 'save_avatar']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_media']);
    }
    
    public function enqueue_media($hook) {
        if ($hook === 'profile.php' || $hook === 'user-edit.php') {
            wp_enqueue_media();
        }
    }
    
    public function add_avatar_field($user) {
        $avatar_id = get_user_meta($user->ID, 'switchboard_avatar', true);
        $avatar_url = $avatar_id ? wp_get_attachment_url($avatar_id) : '';
        ?>
        <h3><?php esc_html_e('Profile Picture', 'wpswitchboard'); ?> <span class="switchboard-badge">SWITCHBOARD</span></h3>
        <table class="form-table">
            <tr>
                <th><?php esc_html_e('Local Avatar', 'wpswitchboard'); ?></th>
                <td>
                    <div id="switchboard-avatar-preview" style="margin-bottom: 10px;">
                        <?php if ($avatar_url): ?>
                            <img src="<?php echo esc_url($avatar_url); ?>" style="max-width: 150px; border-radius: 50%;">
                        <?php endif; ?>
                    </div>
                    <input type="hidden" id="switchboard_avatar" name="switchboard_avatar" value="<?php echo esc_attr($avatar_id); ?>">
                    <?php wp_nonce_field('switchboard_save_avatar_' . $user->ID, 'switchboard_avatar_nonce'); ?>
                    <button type="button" class="button" id="switchboard-upload-avatar"><?php esc_html_e('Upload Avatar', 'wpswitchboard'); ?></button>
                    <button type="button" class="button" id="switchboard-remove-avatar" <?php echo !$avatar_url ? 'style="display:none;"' : ''; ?>><?php esc_html_e('Remove', 'wpswitchboard'); ?></button>
                    <p class="description"><?php esc_html_e('Upload a custom avatar from your media library.', 'wpswitchboard'); ?></p>
                    
                    <script>
                    jQuery(document).ready(function($) {
                        var mediaUploader;
                        
                        $('#switchboard-upload-avatar').on('click', function(e) {
                            e.preventDefault();
                            
                            if (mediaUploader) {
                                mediaUploader.open();
                                return;
                            }
                            
                            mediaUploader = wp.media({
                                title: <?php echo json_encode(esc_html__('Choose Avatar', 'wpswitchboard')); ?>,
                                button: { text: <?php echo json_encode(esc_html__('Use as Avatar', 'wpswitchboard')); ?> },
                                multiple: false
                            });
                            
                            mediaUploader.on('select', function() {
                                var attachment = mediaUploader.state().get('selection').first().toJSON();
                                $('#switchboard_avatar').val(attachment.id);
                                $('#switchboard-avatar-preview').html('<img src="' + attachment.url + '" style="max-width: 150px; border-radius: 50%;">');
                                $('#switchboard-remove-avatar').show();
                            });
                            
                            mediaUploader.open();
                        });
                        
                        $('#switchboard-remove-avatar').on('click', function(e) {
                            e.preventDefault();
                            $('#switchboard_avatar').val('');
                            $('#switchboard-avatar-preview').html('');
                            $(this).hide();
                        });
                    });
                    </script>
                </td>
            </tr>
        </table>
        <?php
    }
    
    public function save_avatar($user_id) {
        if (!current_user_can('edit_user', $user_id)) {
            return;
        }

        // Verify nonce for CSRF protection
        if (!isset($_POST['switchboard_avatar_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['switchboard_avatar_nonce'])), 'switchboard_save_avatar_' . $user_id)) {
            return;
        }

        if (isset($_POST['switchboard_avatar'])) {
            $avatar_id = intval($_POST['switchboard_avatar']);
            if ($avatar_id) {
                // Verify attachment is an image
                if (!wp_attachment_is_image($avatar_id)) {
                    add_action('admin_notices', function() {
                        echo '<div class="notice notice-error"><p>' . esc_html__('Invalid image attachment. Please select an image file.', 'wpswitchboard') . '</p></div>';
                    });
                    return;
                }
                update_user_meta($user_id, 'switchboard_avatar', $avatar_id);
            } else {
                delete_user_meta($user_id, 'switchboard_avatar');
            }
        }
    }
    
    public function get_local_avatar($avatar, $id_or_email, $size, $default, $alt) {
        $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);
            }
        } else {
            $user = get_user_by('email', $id_or_email);
        }
        
        if (!$user) {
            return $avatar;
        }
        
        $avatar_id = get_user_meta($user->ID, 'switchboard_avatar', true);
        
        if (!$avatar_id) {
            return $avatar;
        }
        
        $avatar_url = wp_get_attachment_image_src($avatar_id, [$size, $size]);
        
        if ($avatar_url) {
            $avatar = '<img src="' . esc_url($avatar_url[0]) . '" alt="' . esc_attr($alt) . '" class="avatar avatar-' . $size . ' photo" height="' . $size . '" width="' . $size . '" />';
        }
        
        return $avatar;
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [
                'switchboard_avatar',
            ],
        ];
    }
}

$switchboard_instance = new SwitchboardLocalUserAvatar();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
