<?php
/*
  Plugin Name: User Avatar Generator
  Plugin URI: https://najeebmedia.com/user-avatar-generator
  Description: A powerful and customizable plugin to allow users to create unique avatars directly on your WordPress site. Perfect for privacy-conscious users and those seeking a unique avatar style.
  Version: 2.0
  Author: N-Media
  Author URI: https://najeebmedia.com
  Text Domain: user-avatar-generator
  Domain Path: /languages
  License: MIT
  License URI: https://opensource.org/licenses/MIT
*/


if (!defined('ABSPATH')) {
    exit;
}

class UserAvatarGeneratorWP_Class {
    
    public function __construct() {
        // Register shortcode
        add_shortcode('wp-avatar', [$this, 'render_avatar_shortcode']);
        
        add_action('rest_api_init', function () {
            register_rest_route('avatar/v1', '/upload', array(
                'methods' => 'POST',
                'callback' => [$this, 'handle_avatar_upload'], // Reference as a method
                'permission_callback' => function () {
                    return true;
                },
            ));
        });
        
        add_filter('get_avatar', [$this, 'custom_user_avatar'], 10, 5);
    }

    public function enqueue_scripts() {
        // Enqueue the React bundle generated by wp-scripts
        wp_enqueue_script(
            'user-avatar-generator-js',
            plugins_url('/assets/generator/dist/app.js', __FILE__), // Adjust path if needed
            ['wp-element'], // wp-element includes React in WordPress
            filemtime(plugin_dir_path(__FILE__) . 'assets/generator/dist/app.js'),
            true
        );
        
        // Enqueue CSS if applicable
        wp_enqueue_style(
            'user-avatar-generator-css',
            plugins_url('/assets/generator/dist/app.css', __FILE__), // Adjust if CSS is generated separately
            [],
            filemtime(plugin_dir_path(__FILE__) . 'assets/generator/dist/app.css')
        );
        
        $js_vars = apply_filters('wpavatar_js_vars', [
            'siteUrl'  => get_site_url(),
            'restUrl'  => esc_url_raw(rest_url('avatar/v1/upload')),
            'nonce'    => wp_create_nonce('wp_rest'),
            'strings'  => ['btn_save'  => __('Save', 'user-avatar-generator')],
        ]);
        
        // Pass data to the window global scope
        $script = 'window.avatarGeneratorData = ' . wp_json_encode($js_vars) . ';';
        
        wp_add_inline_script('user-avatar-generator-js', $script, 'before');
    }

    public function render_avatar_shortcode() {
        
        $this->enqueue_scripts();
        
        return '<div id="wp-avatar-root"></div>';
    }
    
    function handle_avatar_upload($request) {
        // Verify nonce for security
        $nonce = $request->get_header('x-wp-nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_forbidden', __('You do not have permission to perform this action.', 'user-avatar-generator'), array('status' => 403));
        }
        
        // Ensure the user is logged in
        $user_id = get_current_user_id();
        if (!$user_id) {
            return new WP_Error('rest_forbidden', __('You must be logged in to upload an avatar.', 'user-avatar-generator'), array('status' => 403));
        }
        
        // Get the avatar image data from the request
        $image_data = $request->get_param('image');
        if (!$image_data) {
            return new WP_Error('no_image', __('No image data found', 'user-avatar-generator'), array('status' => 400));
        }
        
        // Decode the base64 image data
        $image_data = explode(',', $image_data);
        $image_data = base64_decode($image_data[1]);
        
        // Generate a unique filename and upload the file
        $filename = 'avatar-' . time() . '.png';
        $upload = wp_upload_bits($filename, null, $image_data);
        
        if ($upload['error']) {
            return new WP_Error('upload_failed', __('Failed to upload image', 'user-avatar-generator'), array('status' => 500));
        }
        
        // Update the user's avatar URL in user meta
        $avatar_url = $upload['url'];
        update_user_meta($user_id, 'custom_avatar_url', $avatar_url);
        
        // Return the uploaded file URL as a response
        return rest_ensure_response(array('url' => $avatar_url));
    }
    
    function custom_user_avatar($avatar, $id_or_email, $size, $default, $alt) {
        // Get user ID from $id_or_email
        $user = false;
        if (is_numeric($id_or_email)) {
            $user = get_user_by('id', (int) $id_or_email);
        } elseif (is_string($id_or_email)) {
            $user = get_user_by('email', $id_or_email);
        } elseif (is_object($id_or_email) && !empty($id_or_email->user_id)) {
            $user = get_user_by('id', (int) $id_or_email->user_id);
        }
    
        // If a valid user is found, try to get the custom avatar URL
        if ($user) {
            $custom_avatar_url = get_user_meta($user->ID, 'custom_avatar_url', true);
            
            // If a custom avatar is set, return it instead of the default avatar
            if ($custom_avatar_url) {
                $avatar = '<img src="' . esc_url($custom_avatar_url) . '" alt="' . esc_attr($alt) . '" width="' . esc_attr($size) . '" height="' . esc_attr($size) . '" class="avatar avatar-' . esc_attr($size) . ' photo" />';
            }
        }
        
        return $avatar;
    }
}

new UserAvatarGeneratorWP_Class();