<?php
// User Avatar Widget
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Widget_Base;

class UM_User_Avatar_Widget extends Widget_Base {
    
    public function get_name() {
        return 'um-user-avatar';
    }
    
    public function get_title() {
        return esc_html__('UM: User Avatar', 'ultimate-member-widgets-for-elementor');
    }
    
    public function get_icon() {
        return 'eicon-user-circle-o';
    }
    
    public function get_categories() {
        return [ 'um-addons-elementor' ];
    }
    
    protected function _register_controls() {
        $this->start_controls_section(
            'content_section',
            array(
                'label' => esc_html__('Content', 'ultimate-member-widgets-for-elementor'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            )
        );
        
        $this->add_control(
            'show_selected_user',
            array(
                'label' => esc_html__('Select Specific User', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'ultimate-member-widgets-for-elementor'),
                'label_off' => esc_html__('No', 'ultimate-member-widgets-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            )
        );
        
        $this->add_control(
            'selected_user_id',
            array(
                'label' => esc_html__('Select User', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'options' => $this->get_um_users_for_select2(),
                'label_block' => true,
                'condition' => array(
                    'show_selected_user' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'avatar_size',
            array(
                'label' => esc_html__('Avatar Size', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px' ],
                'range' => array(
                    'px' => array(
                        'min' => 20,
                        'max' => 300,
                        'step' => 5,
                    ),
                ),
                'default' => array(
                    'unit' => 'px',
                    'size' => 80,
                ),
                'selectors' => array(
                    '{{WRAPPER}} .um-user-avatar img' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ),
            )
        );
        
        $this->add_control(
            'show_name',
            array(
                'label' => esc_html__('Show Name', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'ultimate-member-widgets-for-elementor'),
                'label_off' => esc_html__('No', 'ultimate-member-widgets-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            )
        );
        
        $this->add_control(
            'name_format',
            array(
                'label' => esc_html__('Name Format', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => array(
                    'first_name' => esc_html__('First Name', 'ultimate-member-widgets-for-elementor'),
                    'last_name' => esc_html__('Last Name', 'ultimate-member-widgets-for-elementor'),
                    'full_name' => esc_html__('Full Name (First Last)', 'ultimate-member-widgets-for-elementor'),
                    'full_name_reverse' => esc_html__('Full Name (Last, First)', 'ultimate-member-widgets-for-elementor'),
                    'display_name' => esc_html__('Display Name', 'ultimate-member-widgets-for-elementor'),
                    'username' => esc_html__('Username', 'ultimate-member-widgets-for-elementor'),
                    'nickname' => esc_html__('Nickname', 'ultimate-member-widgets-for-elementor'),
                ),
                'default' => 'full_name',
                'condition' => array(
                    'show_name' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'name_position',
            array(
                'label' => esc_html__('Name Position', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => array(
                    'below' => esc_html__('Below Avatar', 'ultimate-member-widgets-for-elementor'),
                    'above' => esc_html__('Above Avatar', 'ultimate-member-widgets-for-elementor'),
                    'right' => esc_html__('Right of Avatar', 'ultimate-member-widgets-for-elementor'),
                    'left' => esc_html__('Left of Avatar', 'ultimate-member-widgets-for-elementor'),
                ),
                'default' => 'below',
                'condition' => array(
                    'show_name' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'fallback_text',
            array(
                'label' => esc_html__('Fallback Text', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__('Guest User', 'ultimate-member-widgets-for-elementor'),
                'description' => esc_html__('Text to display when no user is logged in or name is not available', 'ultimate-member-widgets-for-elementor'),
                'condition' => array(
                    'show_name' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'link_to_profile',
            array(
                'label' => esc_html__('Link to User Profile', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'ultimate-member-widgets-for-elementor'),
                'label_off' => esc_html__('No', 'ultimate-member-widgets-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            )
        );
        
        $this->end_controls_section();
        
        // Avatar Style Section
        $this->start_controls_section(
            'avatar_style_section',
            array(
                'label' => esc_html__('Avatar Style', 'ultimate-member-widgets-for-elementor'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            )
        );
        
        $this->add_control(
            'avatar_shape',
            array(
                'label' => esc_html__('Avatar Shape', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => array(
                    'circle' => esc_html__('Circle', 'ultimate-member-widgets-for-elementor'),
                    'square' => esc_html__('Square', 'ultimate-member-widgets-for-elementor'),
                    'rounded' => esc_html__('Rounded Square', 'ultimate-member-widgets-for-elementor'),
                ),
                'default' => 'circle',
            )
        );
        
        $this->add_control(
            'avatar_border_radius',
            array(
                'label' => esc_html__('Border Radius', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'selectors' => array(
                    '{{WRAPPER}} .um-user-avatar img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
                'condition' => array(
                    'avatar_shape' => 'rounded',
                ),
            )
        );
        
        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            array(
                'name' => 'avatar_border',
                'label' => esc_html__('Border', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-user-avatar img',
            )
        );
        
        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            array(
                'name' => 'avatar_shadow',
                'label' => esc_html__('Box Shadow', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-user-avatar img',
            )
        );
        
        $this->add_control(
            'avatar_hover_effect',
            array(
                'label' => esc_html__('Hover Effect', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => array(
                    'none' => esc_html__('None', 'ultimate-member-widgets-for-elementor'),
                    'scale' => esc_html__('Scale', 'ultimate-member-widgets-for-elementor'),
                    'opacity' => esc_html__('Opacity', 'ultimate-member-widgets-for-elementor'),
                    'grayscale' => esc_html__('Grayscale', 'ultimate-member-widgets-for-elementor'),
                ),
                'default' => 'none',
            )
        );
        
        $this->end_controls_section();
        
        // Name Style Section
        $this->start_controls_section(
            'name_style_section',
            array(
                'label' => esc_html__('Name Style', 'ultimate-member-widgets-for-elementor'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
                'condition' => array(
                    'show_name' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'name_color',
            array(
                'label' => esc_html__('Name Color', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .um-user-name' => 'color: {{VALUE}};',
                ),
            )
        );
        
        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            array(
                'name' => 'name_typography',
                'label' => esc_html__('Typography', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-user-name',
            )
        );
        
        $this->add_control(
            'name_spacing',
            array(
                'label' => esc_html__('Name Spacing', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px' ],
                'range' => array(
                    'px' => array(
                        'min' => 0,
                        'max' => 50,
                        'step' => 1,
                    ),
                ),
                'default' => array(
                    'unit' => 'px',
                    'size' => 10,
                ),
                'selectors' => array(
                    '{{WRAPPER}} .um-avatar-layout-below .um-user-name' => 'margin-top: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .um-avatar-layout-above .um-user-name' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .um-avatar-layout-right .um-user-name' => 'margin-left: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .um-avatar-layout-left .um-user-name' => 'margin-right: {{SIZE}}{{UNIT}};',
                ),
            )
        );
        
        $this->add_control(
            'link_color',
            array(
                'label' => esc_html__('Link Color', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .um-user-name a' => 'color: {{VALUE}};',
                ),
                'condition' => array(
                    'link_to_profile' => 'yes',
                ),
            )
        );
        
        $this->add_control(
            'link_hover_color',
            array(
                'label' => esc_html__('Link Hover Color', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .um-user-name a:hover' => 'color: {{VALUE}};',
                ),
                'condition' => array(
                    'link_to_profile' => 'yes',
                ),
            )
        );
        
        $this->end_controls_section();
        
        // Layout Style Section
        $this->start_controls_section(
            'layout_style_section',
            array(
                'label' => esc_html__('Layout', 'ultimate-member-widgets-for-elementor'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            )
        );
        
        $this->add_control(
            'alignment',
            array(
                'label' => esc_html__('Alignment', 'ultimate-member-widgets-for-elementor'),
                'type' => \Elementor\Controls_Manager::CHOOSE,
                'options' => array(
                    'left' => array(
                        'title' => esc_html__('Left', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ),
                    'center' => array(
                        'title' => esc_html__('Center', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ),
                    'right' => array(
                        'title' => esc_html__('Right', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ),
                ),
                'default' => 'left',
                'toggle' => true,
                'selectors' => array(
                    '{{WRAPPER}} .um-user-avatar-wrapper' => 'text-align: {{VALUE}};',
                ),
            )
        );
        
        $this->end_controls_section();
    }
    
    /**
     * Get Ultimate Member users formatted for Select2 control.
     *
     * @return array An associative array of user IDs and their display names.
     */
    private function get_um_users_for_select2() {
        $users_data = [];

        if (class_exists('UM')) {
            $args = array(
                'number' => 100, // Limit to 100 users to prevent memory exhaustion
                'fields' => array( 'ID', 'display_name' ),
            );
            $users = get_users($args);

            foreach ($users as $user) {
                $users_data[$user->ID] = $user->display_name;
            }
        }

        return $users_data;
    }
    
    /**
     * Get user name based on selected format.
     *
     * @param int $user_id The user ID.
     * @param string $format The name format.
     * @param string $fallback The fallback text.
     * @return string The formatted user name.
     */
    private function get_user_name($user_id, $format, $fallback = 'User') {
        if (!$user_id) {
            return $fallback;
        }
        
        $user = get_user_by('ID', $user_id);
        if (!$user) {
            return $fallback;
        }
        
        // Fetch UM user data
        if (class_exists('UM')) {
            um_fetch_user($user_id);
        }
        
        switch ($format) {
            case 'first_name':
                $name = class_exists('UM') ? um_user('first_name') : $user->first_name;
                break;
                
            case 'last_name':
                $name = class_exists('UM') ? um_user('last_name') : $user->last_name;
                break;
                
            case 'full_name':
                $first_name = class_exists('UM') ? um_user('first_name') : $user->first_name;
                $last_name = class_exists('UM') ? um_user('last_name') : $user->last_name;
                $name = trim($first_name . ' ' . $last_name);
                break;
                
            case 'full_name_reverse':
                $first_name = class_exists('UM') ? um_user('first_name') : $user->first_name;
                $last_name = class_exists('UM') ? um_user('last_name') : $user->last_name;
                if ($first_name && $last_name) {
                    $name = $last_name . ', ' . $first_name;
                } else {
                    $name = trim($first_name . ' ' . $last_name);
                }
                break;
                
            case 'display_name':
                $name = $user->display_name;
                break;
                
            case 'username':
                $name = $user->user_login;
                break;
                
            case 'nickname':
                $name = get_user_meta($user_id, 'nickname', true);
                break;
                
            default:
                $name = $user->display_name;
                break;
        }
        
        return !empty($name) ? $name : $fallback;
    }
    
    /**
     * Get user avatar.
     *
     * @param int $user_id The user ID.
     * @param int $size The avatar size.
     * @return string The avatar HTML.
     */
    private function get_user_avatar($user_id, $size = 80) {
        if (!$user_id) {
            return get_avatar(0, $size);
        }
        
        if (class_exists('UM')) {
            um_fetch_user($user_id);
            return um_get_avatar($user_id, $size);
        }
        
        return get_avatar($user_id, $size);
    }
    
    /**
     * Get user profile URL.
     *
     * @param int $user_id The user ID.
     * @return string The profile URL.
     */
    private function get_user_profile_url($user_id) {
        if (class_exists('UM')) {
            return um_user_profile_url($user_id);
        }
        
        return get_author_posts_url($user_id);
    }
    
    /**
     * Get avatar shape class.
     *
     * @param string $shape The avatar shape.
     * @return string The CSS class.
     */
    private function get_avatar_shape_class($shape) {
        switch ($shape) {
            case 'circle':
                return 'um-avatar-circle';
            case 'square':
                return 'um-avatar-square';
            case 'rounded':
                return 'um-avatar-rounded';
            default:
                return 'um-avatar-circle';
        }
    }
    
    /**
     * Get layout class.
     *
     * @param string $position The name position.
     * @return string The CSS class.
     */
    private function get_layout_class($position) {
        return 'um-avatar-layout-' . $position;
    }
    
    protected function render() {
        $settings = $this->get_settings_for_display();

        $user_id = null;

        if ( 'yes' === $settings['show_selected_user'] && ! empty( $settings['selected_user_id'] ) ) {
            $user_id = (int) $settings['selected_user_id'];
        } else {
            $user_id = get_current_user_id();
        }
        
        $avatar_size = $settings['avatar_size']['size'] ?? 80;
        $avatar_shape_class = $this->get_avatar_shape_class($settings['avatar_shape']);
        $layout_class = $this->get_layout_class($settings['name_position']);
        $hover_effect_class = 'um-hover-' . $settings['avatar_hover_effect'];
        
        ?>
        <div class="um-elementor-element um-elementor-user-avatar">
            <div class="um-user-avatar-wrapper <?php echo esc_attr($layout_class); ?>">
                <?php
                // Show name above avatar
                if ('yes' === $settings['show_name'] && 'above' === $settings['name_position']) {
                    $this->render_user_name($user_id, $settings);
                }
                
                // Show avatar
                ?>
                <div class="um-user-avatar <?php echo esc_attr($avatar_shape_class . ' ' . $hover_effect_class); ?>">
                    <?php if ('yes' === $settings['link_to_profile'] && $user_id) : ?>
                        <a href="<?php echo esc_url($this->get_user_profile_url($user_id)); ?>">
                            <?php echo wp_kses_post($this->get_user_avatar($user_id, $avatar_size)); ?>
                        </a>
                    <?php else : ?>
                        <?php echo wp_kses_post($this->get_user_avatar($user_id, $avatar_size)); ?>
                    <?php endif; ?>
                </div>
                
                <?php
                // Show name below, left, or right of avatar
                if ('yes' === $settings['show_name'] && 'above' !== $settings['name_position']) {
                    $this->render_user_name($user_id, $settings);
                }
                ?>
            </div>
        </div>
        
        <style>
            .um-avatar-circle img {
                border-radius: 50% !important;
            }
            
            .um-avatar-square img {
                border-radius: 0 !important;
            }
            
            .um-avatar-layout-right,
            .um-avatar-layout-left {
                display: flex;
                align-items: center;
            }
            
            .um-avatar-layout-left {
                flex-direction: row-reverse;
            }
            
            .um-hover-scale:hover img {
                transform: scale(1.1);
                transition: transform 0.3s ease;
            }
            
            .um-hover-opacity:hover img {
                opacity: 0.7;
                transition: opacity 0.3s ease;
            }
            
            .um-hover-grayscale:hover img {
                filter: grayscale(100%);
                transition: filter 0.3s ease;
            }
            
            .um-user-avatar img {
                display: block;
                object-fit: cover;
            }
        </style>
        <?php
    }
    
    /**
     * Render user name.
     *
     * @param int $user_id The user ID.
     * @param array $settings The widget settings.
     */
    private function render_user_name($user_id, $settings) {
        if (!$user_id) {
            ?>
            <div class="um-user-name">
                <?php echo esc_html($settings['fallback_text']); ?>
            </div>
            <?php
            return;
        }
        
        $name = $this->get_user_name($user_id, $settings['name_format'], $settings['fallback_text']);
        $profile_url = $this->get_user_profile_url($user_id);
        
        ?>
        <div class="um-user-name">
            <?php if ('yes' === $settings['link_to_profile'] && $profile_url) : ?>
                <a href="<?php echo esc_url($profile_url); ?>">
                    <?php echo esc_html($name); ?>
                </a>
            <?php else : ?>
                <?php echo esc_html($name); ?>
            <?php endif; ?>
        </div>
        <?php
    }

	/**
	 * Get widget style dependencies.
	 */
	public function get_style_depends() {
		return ['um-elementor-styles'];
	}

}
