<?php
// User Name Widget
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Widget_Base;

class UM_User_Name_Widget extends Widget_Base {
    
    public function get_name() {
        return 'um-user-name';
    }
    
    public function get_title() {
        return esc_html__('UM: User Name', 'ultimate-member-widgets-for-elementor');
    }
    
    public function get_icon() {
        return 'eicon-person';
    }
    
    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(
            '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',
            )
        );
        
        $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(
            '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'),
            )
        );
        
        $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();
        
        $this->start_controls_section(
            'style_section',
            array(
                'label' => esc_html__('Style', 'ultimate-member-widgets-for-elementor'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            )
        );
        
        $this->add_control(
            'text_color',
            array(
                'label' => esc_html__('Text 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' => 'typography',
                'label' => esc_html__('Typography', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-user-name',
            )
        );
        
        $this->add_control(
            'text_align',
            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-name-wrapper' => 'text-align: {{VALUE}};',
                ),
            )
        );
        
        $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();
    }
    
    /**
     * 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 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);
    }
    
    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();
        }
        
        if (!$user_id) {
            // If no user is logged in, show fallback text
            ?>
            <div class="um-elementor-element um-elementor-user-name">
                <div class="um-user-name-wrapper">
                    <div class="um-user-name">
                        <?php echo esc_html($settings['fallback_text']); ?>
                    </div>
                </div>
            </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-elementor-element um-elementor-user-name">
            <div class="um-user-name-wrapper">
                <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>
            </div>
        </div>
        <?php
    }

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

}
