<?php
// Profile Fields Widget
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Widget_Base;

class UM_Profile_Fields_Widget extends Widget_Base {
    
    // Constants for better maintainability
    private const WIDGET_NAME = 'um-profile-fields';
    private const WIDGET_CATEGORY = 'um-profile-forms-elementor';
    private const MAX_USERS_LIMIT = 100; // Performance optimization
    
    public function get_name(): string {
        return self::WIDGET_NAME;
    }
    
    public function get_title(): string {
        return esc_html__( 'Profile Fields', 'ultimate-member-widgets-for-elementor' );
    }

    public function get_description(): string {
        return esc_html__('Show selected Ultimate Member profile fields for the member being viewed.', 'ultimate-member-widgets-for-elementor');
    }

    public function get_keywords(): array {
        return [ 'ultimate member', 'um', 'profile', 'fields', 'member' ];
    }
    
    public function get_icon(): string {
        return 'eicon-form-horizontal';
    }
    
    public function get_categories(): array {
        return [ self::WIDGET_CATEGORY ];
    }
    
    protected function register_controls(): void {
        $this->register_content_controls();
        $this->register_style_controls();
    }
    
    /**
     * Register content controls
     */
    private function register_content_controls(): void {
        $this->start_controls_section(
            'content_section',
            [
                'label' => esc_html__('Content', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );
        
        $this->add_control(
            'fields_to_show',
            [
                'label' => esc_html__('Fields to Show', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => $this->get_um_fields(),
                'default' => ['first_name', 'last_name', 'user_email'],
            ]
        );
        
        $this->add_control(
            'show_selected_user',
            [
                'label' => esc_html__('Select Specific User', 'ultimate-member-widgets-for-elementor'),
                'type' => 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',
            [
                'label' => esc_html__('Select User', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'options' => $this->get_um_users_for_select2(),
                'label_block' => true,
                'condition' => [
                    'show_selected_user' => 'yes',
                ],
            ]
        );
        
        $this->end_controls_section();
    }
    
    /**
     * Register style controls
     */
    private function register_style_controls(): void {
        $this->start_controls_section(
            'style_section',
            [
                'label' => esc_html__('Style', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );
        
        $this->add_control(
            'field_label_color',
            [
                'label' => esc_html__('Label Color', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .um-field-label' => 'color: {{VALUE}};',
                ],
            ]
        );
        
        $this->add_control(
            'field_value_color',
            [
                'label' => esc_html__('Value Color', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .um-field-value' => 'color: {{VALUE}};',
                ],
            ]
        );
        
        $this->end_controls_section();
    }
    
    /**
     * Get Ultimate Member fields
     */
    private function get_um_fields(): array {
        // Early return if UM is not available
        if (!class_exists('UM')) {
            return [];
        }
        
        $fields = [];
        $um_fields = UM()->builtin()->all_user_fields();
        
        foreach ($um_fields as $key => $field) {
            $fields[$key] = $field['title'] ?? $key;
        }
        
        return $fields;
    }
    
    /**
     * Get the label for a given Ultimate Member field key
     */
    private function get_field_label(string $field_key): string {
        if (!class_exists('UM')) {
            return $field_key;
        }
        
        $field = UM()->builtin()->get_specific_field($field_key);
        return $field['title'] ?? $field_key;
    }
    
    /**
     * Get Ultimate Member users formatted for Select2 control
     * Optimized for performance with user limit
     */
    private function get_um_users_for_select2(): array {
        // Early return if UM is not available
        if (!class_exists('UM')) {
            return [];
        }
        
        $users_data = [];
        $args = [
            'number' => self::MAX_USERS_LIMIT,
            'fields' => ['ID', 'display_name'],
            'orderby' => 'display_name',
            'order' => 'ASC',
        ];
        
        $users = get_users($args);
        
        foreach ($users as $user) {
            $users_data[$user->ID] = $user->display_name;
        }
        
        return $users_data;
    }
    
    /**
     * Get the user ID to display
     */
    private function get_display_user_id(array $settings): ?int {
        if ('yes' === $settings['show_selected_user'] && !empty($settings['selected_user_id'])) {
            return (int) $settings['selected_user_id'];
        }
        
        return get_current_user_id() ?: null;
    }
    
    /**
     * Check if Ultimate Member is available and user exists
     */
    private function is_valid_setup(int $user_id): bool {
        return class_exists('UM') && $user_id > 0;
    }
    
    /**
     * Render a single field
     */
    private function render_field(string $field_key): void {
        $field_value = um_user($field_key);
        
        // Early return if field is empty
        if (empty($field_value)) {
            return;
        }
        
        $field_label = $this->get_field_label($field_key);
        ?>
        <div class="um-field-wrapper">
            <div class="um-field-label">
                <strong><?php echo esc_html($field_label); ?>:</strong>
            </div>
            <div class="um-field-value">
                <?php echo wp_kses_post($field_value); ?>
            </div>
        </div>
        <?php
    }
    
    protected function render(): void {
        if (!class_exists('UM')) {
            if ( current_user_can( 'edit_pages' ) ) {
                \UM_Elementor\Helpers\UM_Editor_Placeholder::render(
                    $this->get_title(),
                    __( 'Ultimate Member must be active to use this widget.', 'ultimate-member-widgets-for-elementor' )
                );
            }
            return;
        }
        
        require_once ABSPATH . 'wp-content/plugins/ultimate-member/includes/um-short-functions.php';
        
        $settings = $this->get_settings_for_display();

        if (empty($settings['fields_to_show'])) {
            if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
                \UM_Elementor\Helpers\UM_Editor_Placeholder::render(
                    $this->get_title(),
                    __( 'Select at least one profile field to display.', 'ultimate-member-widgets-for-elementor' )
                );
            }
            return;
        }

        $user_id = $this->get_display_user_id($settings);
        
        if (!$this->is_valid_setup($user_id)) {
            if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
                \UM_Elementor\Helpers\UM_Editor_Placeholder::render(
                    $this->get_title(),
                    __( 'No member to preview. Enable “Show Selected User” and pick a user, or view on a profile page.', 'ultimate-member-widgets-for-elementor' )
                );
            }
            return;
        }
        
        um_fetch_user($user_id);

        $chunks = [];
        foreach ($settings['fields_to_show'] as $field_key) {
            $field_key = sanitize_key( (string) $field_key );
            $field_value = um_user( $field_key );
            if ( empty( $field_value ) ) {
                continue;
            }
            ob_start();
            $this->render_field($field_key);
            $chunks[] = ob_get_clean();
        }

        if ( empty( $chunks ) ) {
            if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
                \UM_Elementor\Helpers\UM_Editor_Placeholder::render(
                    $this->get_title(),
                    __( 'Selected fields have no values for this member.', 'ultimate-member-widgets-for-elementor' )
                );
            }
            um_reset_user();
            return;
        }
        ?>
        <div class="um-elementor-element um-elementor-profile-fields um-elementor-reorderable">
            <?php echo implode( '', $chunks ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
        </div>
        <?php
        um_reset_user();
    }

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

}
