<?php
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Css_Filter;
use Elementor\Repeater;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
use UM_Elementor\Base\UM_Elementor_Base_Widget;
use UM_Elementor\Helpers\UM_User_Meta_Renderer;
use UM_Elementor\Helpers\UM_Elementor_Utils;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class UM_ELEMENTOR_LIST_FLIP_MODULE extends UM_Elementor_Base_Widget
{
    private $meta_renderer;

    public function __construct($data = [], $args = null)
    {
        parent::__construct($data, $args);
        $this->meta_renderer = new UM_User_Meta_Renderer();
    }

    public function get_name()
    {
        return 'ele-um-user-list-flip';
    }

    public function get_title()
    {
        return __('UM: User Flip Cards', 'ultimate-member-widgets-for-elementor');
    }

    protected function register_widget_controls()
    {
        $this->register_flip_controls();
        $this->register_flip_specific_layout_controls();
        $this->register_flip_style_controls();
    }

    /**
     * Override base class common style controls to remove unwanted background color
     */
    protected function register_common_style_controls()
    {
        $this->start_controls_section(
            'um_elementor_section_member_style_' . $this->get_name(),
            [
                'label' => __('User Card', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        // Text Alignment
        $this->add_control(
            'title_alignment',
            [
                'label' => __('Text Alignment', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'text-left' => [
                        'title' => __('Left', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'text-center' => [
                        'title' => __('Center', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'text-right' => [
                        'title' => __('Right', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ]
                ],
                'default' => 'text-center'
            ]
        );

        // Margin Between Users
        $this->add_responsive_control(
            'um_member_block_margin',
            [
                'label' => esc_html__('Spacing Between Users', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'default' => [
                    'top' => '6',
                    'bottom' => '6',
                    'left' => '6',
                    'right' => '6',
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .um-item-user' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        // Allow Box Shadow
        $this->add_control(
            'allow_box_shadow',
            [
                'label' => _x('Box Shadow', 'Box Shadow Control', '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',
                'separator' => 'before',
                'render_type' => 'ui',
            ]
        );

        // Box Shadow of User Block
        $this->add_control(
            'um_user_block_box_shadow',
            [
                'label' => esc_html__('Box Shadow', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::BOX_SHADOW,
                'condition' => [
                    'allow_box_shadow!' => '',
                ],
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .um-item-user' => 'box-shadow: {{HORIZONTAL}}px {{VERTICAL}}px {{BLUR}}px {{SPREAD}}px {{COLOR}} {{box_shadow_position.VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register flip-specific controls
     */
    private function register_flip_controls()
    {
        // Front Section
        $this->start_controls_section(
            'um_flip_section_front',
            [
                'label' => esc_html__('Front', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        $this->register_meta_controls('um_user_meta_control_front', 'User Fields (Front)');

        $this->end_controls_section();

        // Back Section
        $this->start_controls_section(
            'um_flip_section_back',
            [
                'label' => esc_html__('Back', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        $this->register_meta_controls('um_user_meta_control', 'User Fields (Back)');

        $this->end_controls_section();
    }

    /**
     * Register meta controls for flip sections
     */
    private function register_meta_controls($control_name, $label)
    {
        $repeater = new Repeater();

        // Meta Keys
        $repeater->add_control(
            'um_user_meta_field_value' . ($control_name === 'um_user_meta_control_front' ? '_front' : ''),
            [
                'label' => esc_html__('Meta Key', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => esc_html__('description', 'ultimate-member-widgets-for-elementor'),
                'label_block' => true,
                'options' => user_elementor_um_get_user_meta_keys_combine(),
            ]
        );

        // Field Label
        $repeater->add_control(
            'um_user_meta_field_label' . ($control_name === 'um_user_meta_control_front' ? '_front' : ''),
            [
                'label' => __('Show Field Label', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    1 => [
                        'title' => __('Yes', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-check',
                    ],
                    0 => [
                        'title' => __('No', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-ban',
                    ]
                ],
                'default' => '1',
            ]
        );

        // User Meta
        $this->add_control(
            $control_name,
            [
                'label' => esc_html__($label, 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'seperator' => 'before',
                'fields' => $repeater->get_controls(),
                'title_field' => '{{{um_user_meta_field_value' . ($control_name === 'um_user_meta_control_front' ? '_front' : '') . '}}}',
                'default' => [
                    ['um_user_meta_field_value' . ($control_name === 'um_user_meta_control_front' ? '_front' : '') => 'birth_date'],
                    ['um_user_meta_field_value' . ($control_name === 'um_user_meta_control_front' ? '_front' : '') => 'description'],
                ],
            ]
        );
    }

    /**
     * Register flip-specific layout controls
     */
    private function register_flip_specific_layout_controls()
    {
        $this->start_controls_section(
            'um_elementor_section_flip_layout',
            [
                'label' => __('Flip Card Layout', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        // Number of Columns (override base class with more options)
        $this->add_control(
            'grid_column_no',
            [
                'label' => esc_html__('Columns', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => '3',
                'options' => [
                    '1' => esc_html__('1', 'ultimate-member-widgets-for-elementor'),
                    '2' => esc_html__('2', 'ultimate-member-widgets-for-elementor'),
                    '3' => esc_html__('3', 'ultimate-member-widgets-for-elementor'),
                    '4' => esc_html__('4', 'ultimate-member-widgets-for-elementor'),
                    '5' => esc_html__('5', 'ultimate-member-widgets-for-elementor'),
                    '6' => esc_html__('6', 'ultimate-member-widgets-for-elementor'),
                    '7' => esc_html__('7', 'ultimate-member-widgets-for-elementor'),
                    '8' => esc_html__('8', 'ultimate-member-widgets-for-elementor'),
                    '9' => esc_html__('9', 'ultimate-member-widgets-for-elementor'),
                    '10' => esc_html__('10', 'ultimate-member-widgets-for-elementor'),
                    '11' => esc_html__('11', 'ultimate-member-widgets-for-elementor'),
                    '12' => esc_html__('12', 'ultimate-member-widgets-for-elementor'),
                ],
            ]
        );

        $this->add_responsive_control(
            'flip_box_height',
            [
                'type' => Controls_Manager::SLIDER,
                'label' => esc_html__('Height', 'ultimate-member-widgets-for-elementor'),
                'size_units' => ['px', 'vh'],
                'range' => [
                    'px' => [
                        'min' => 20,
                        'max' => 1000,
                    ],
                    'vh' => [
                        'min' => 20,
                        'max' => 100,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 350,
                ],
                'selectors' => [
                    '{{WRAPPER}} .flip-card' => 'height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        // User Card Layout
        $this->add_control(
            'user_layout',
            [
                'label' => esc_html__('Layouts', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'flip-left',
                'options' => [
                    'flip-left' => esc_html__('Flip Left', 'ultimate-member-widgets-for-elementor'),
                    'flip-right' => esc_html__('Flip Right', 'ultimate-member-widgets-for-elementor'),
                    'flip-top' => esc_html__('Flip Top', 'ultimate-member-widgets-for-elementor'),
                    'flip-bottom' => esc_html__('Flip Bottom', 'ultimate-member-widgets-for-elementor'),
                ],
            ]
        );

        // Flip Card Padding (unique to flip cards)
        $this->add_responsive_control(
            'flip_card_padding',
            [
                'label' => esc_html__('Card Padding', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'default' => [
                    'top' => '12',
                    'bottom' => '12',
                    'left' => '12',
                    'right' => '12',
                    'unit' => 'px',
                ],
                'selectors' => [
                    '{{WRAPPER}} .flip-card-front, {{WRAPPER}} .flip-card-back' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        // Flip Card Border Radius (unique to flip cards)
        $this->add_control(
            'flip_card_border_radius',
            [
                'label' => esc_html__('Card Border Radius', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .flip-card-inner, {{WRAPPER}} .flip-card-front, {{WRAPPER}} .flip-card-back' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register flip style controls
     */
    private function register_flip_style_controls()
    {
        // Front Style Controls
        $this->start_controls_section(
            'um_elementor_section_member_style',
            [
                'label' => __('Front', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        $this->register_flip_side_style_controls('front');

        $this->end_controls_section();

        // Back Style Controls
        $this->start_controls_section(
            'um_elementor_section_member_style_back',
            [
                'label' => __('Back', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        $this->register_flip_side_style_controls('back');

        $this->end_controls_section();

        // Title Style Controls
        $this->start_controls_section(
            'um_ele_user_style_title_section',
            [
                'label' => __('Title', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        // Member Name Color
        $this->add_control(
            'um_member_block_title_color',
            [
                'label' => __('Title Color', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#303133',
                'selectors' => [
                    '{{WRAPPER}} .um-elementor-member-name, {{WRAPPER}} .um-elementor-member-name a' => 'color: {{VALUE}};',
                ]
            ]
        );

        // User Name Typography
        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'um_member_user_name_typography',
                'label' => esc_html__('Title Font', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-elementor-member-name a',
                'global' => ['default' => Global_Typography::TYPOGRAPHY_PRIMARY,],
                'fields_options' => [
                    'typography' => ['default' => 'yes'],
                    'font_weight' => ['default' => 700],
                    'font_family' => ['default' => 'Domine'],
                    'font_size' => [
                        'default' => [
                            'size' => '2',
                            'unit' => 'rem',
                        ],
                        'size_units' => ['rem'],
                    ],
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls for flip sides
     */
    private function register_flip_side_style_controls($side)
    {
        $suffix = $side === 'front' ? '_front' : '_back';
        $selector = $side === 'front' ? '.flip-card-front' : '.flip-card-back';

        // Text Alignment
        $this->add_control(
            'title_alignment' . $suffix,
            [
                'label' => __('Text Alignment', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'text-left' => [
                        'title' => __('Left', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'text-center' => [
                        'title' => __('Center', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'text-right' => [
                        'title' => __('Right', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ]
                ],
                'default' => 'text-center'
            ]
        );

        // Member Blocks Color
        $this->add_control(
            'um_member_block_color' . $suffix,
            [
                'label' => __('Member Blocks Color', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => $side === 'front' ? '#f5f4ed' : '#652f9c',
                'selectors' => [
                    '{{WRAPPER}} ' . $selector => 'background-color: {{VALUE}}',
                ]
            ]
        );

        // Member Meta Label Color
        $this->add_control(
            'um_member_meta_field_title_color' . $suffix,
            [
                'label' => __('Meta Label', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => $side === 'front' ? '#444444' : '#fff',
                'selectors' => [
                    '{{WRAPPER}} ' . $selector . ' .um-custom-label' => 'color: {{VALUE}};',
                ],
            ]
        );

        // Member Meta Value Color
        $this->add_control(
            'um_member_meta_field_value_color' . $suffix,
            [
                'label' => __('Meta Value', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => $side === 'front' ? '#5c534f' : '#fff',
                'selectors' => [
                    '{{WRAPPER}} ' . $selector . ' .um-custom-field' => 'color: {{VALUE}};',
                ],
            ]
        );

        // Meta Label Typography
        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'um_member_meta_field_title_typography' . $suffix,
                'label' => esc_html__('Typography', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} ' . $selector . ' .um-custom-label, {{WRAPPER}} ' . $selector . ' .um-custom-field',
                'global' => ['default' => Global_Typography::TYPOGRAPHY_TEXT,],
                'fields_options' => [
                    'typography' => ['default' => 'yes'],
                    'font_weight' => ['default' => 500],
                ],
            ]
        );
    }

    /**
     * Render user meta fields for back side
     */
    private function render_back_meta_fields($settings)
    {
        if (empty($settings['um_user_meta_control'])) {
            return;
        }

        foreach ($settings['um_user_meta_control'] as $item) {
            $this->render_single_meta_field($item);
        }
    }

    /**
     * Render user meta fields for front side
     */
    private function render_front_meta_fields($settings)
    {
        if (empty($settings['um_user_meta_control_front'])) {
            return;
        }

        foreach ($settings['um_user_meta_control_front'] as $item) {
            $this->render_single_meta_field($item, '_front');
        }
    }

    /**
     * Render a single meta field
     */
    private function render_single_meta_field($item, $suffix = '')
    {
        $field_key = $item['um_user_meta_field_value' . $suffix] ?? '';
        $show_label = $item['um_user_meta_field_label' . $suffix] ?? 1;

        if (empty($field_key)) {
            return;
        }

        $user_id = um_user('ID');
        um_fetch_user($user_id);
        $meta_value = um_user($field_key);

        if (empty($meta_value)) {
            return;
        }

        $this->output_meta_field($field_key, $meta_value, $show_label);
    }

    /**
     * Output meta field HTML
     */
    private function output_meta_field($field_key, $meta_value, $show_label)
    {
        echo '<span class="um-meta-field">';

        if ($show_label) {
            $label = UM()->Fields()->get_label($field_key);
            echo '<span class="um-custom-label">' . esc_attr($label) . ':</span>';
        }

        echo '<span class="um-custom-field">';
        $field_type = UM()->Fields()->get_field_type($field_key);
        $this->render_field_by_type($field_key, $meta_value, $field_type);
        echo '</span>';
        echo '</span>';
    }

    /**
     * Render field based on its type
     */
    private function render_field_by_type($field_key, $meta_value, $field_type)
    {
        $renderer = $this->get_meta_renderer();
        
        switch ($field_type) {
            case 'url':
                $renderer->render_url_field($meta_value);
                break;
            case 'tel':
                $renderer->render_tel_field($meta_value);
                break;
            case 'image':
                $renderer->render_image_field($field_key);
                break;
            case 'file':
                $renderer->render_file_field($field_key);
                break;
            case 'youtube_video':
                $renderer->render_youtube_field($meta_value);
                break;
            default:
                $renderer->render_default_field($meta_value);
                break;
        }
    }

    /**
     * Get meta renderer instance
     */
    private function get_meta_renderer() {
        return new \UM_Elementor\Helpers\UM_User_Meta_Renderer();
    }

    /**
     * Render the widget output
     */
    protected function render()
    {
        $settings = $this->get_settings();

        $member_name_type = $settings['user_display_title'] ?? 'display_name';
        $column = $settings['grid_column_no'] ?? '3';
        $align = $settings['title_alignment_front'] ?? 'text-left';
        $align_back = $settings['title_alignment_back'] ?? 'text-left';
        $layout = $settings['user_layout'] ?? 'flip-left';

        $settings['paged'] = 1;
        if (um_use_new_query_engine()) {
            $result = \UM_User_Query_Engine::get_users($settings);
            $users = $result['users'];
        } else {
            $args = \UM_Elementor\Helpers\UM_User_Query_Legacy::build($settings);
            $args['paged'] = 1;
            $members_query = new \WP_User_Query($args);
            $users = $members_query->get_results();
            $users = \UM_Elementor\Helpers\UM_User_Query_Legacy::filterDisplayableUsers($users);
        }

        if (empty($users)) {
            esc_html_e('Not Found', 'ultimate-member-widgets-for-elementor');
            return;
        }

        $this->render_flip_cards($users, $settings, $member_name_type, $column, $align, $align_back, $layout);
    }

    /**
     * Render flip cards
     */
    private function render_flip_cards($users, $settings, $member_name_type, $column, $align, $align_back, $layout)
    {
        ?>
        <div class="um-team-carousel-wrapper grid grid-cols-1 md:grid-cols-<?php echo esc_attr($column); ?>">
            <?php foreach ($users as $user_item) : 
                  $user_id = is_object($user_item) ? $user_item->ID : $user_item;
            ?>
                <div class="um-item-user">
                    <div class="flip-card <?php echo esc_attr($layout); ?>">
                        <div class="flip-card-inner">
                            <?php $this->render_flip_front($user_id, $settings, $member_name_type, $align); ?>
                            <?php $this->render_flip_back($user_id, $settings, $align_back); ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
        um_reset_user();
    }

    /**
     * Render flip card front
     */
    private function render_flip_front($user_id, $settings, $member_name_type, $align)
    {
        um_fetch_user($user_id);
        ?>
        <div class="flip-card-front">
            <div class="">
                <div class="um-elementor-member-content">
                    <div class="um-custom-field-container <?php echo esc_attr($align); ?>">

                        <?php if ($settings['um_elementor_show_user_image'] == 1) : ?>
                            <div class="um-elementor-member-image <?php echo esc_attr($align); ?>">
                                <a title="<?php echo esc_attr(um_user('display_name')); ?>" href="<?php echo esc_url(um_user_profile_url()); ?>">
                                    <?php echo um_get_avatar('', $user_id, 100); ?>
                                </a>
                            </div>
                        <?php endif; ?>

                        <?php if ($settings['um_elementor_show_member_name'] == 1) : ?>
                            <div class="um-elementor-member-name <?php echo esc_attr($align); ?>">
                                <p>
                                    <a title="<?php echo esc_attr(um_user('first_name')); ?>" href="<?php echo esc_url(um_user_profile_url()); ?>">
                                        <?php echo esc_html(um_user($member_name_type)); ?>
                                    </a>
                                </p>
                            </div>
                        <?php endif; ?>

                        <?php $this->render_front_meta_fields($settings); ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render flip card back
     */
    private function render_flip_back($user_id, $settings, $align_back)
    {
        um_fetch_user($user_id);
        ?>
        <div class="flip-card-back">
            <div class="">
                <div class="um-elementor-member-content">
                    <div class="um-custom-field-container <?php echo esc_attr($align_back); ?>">
                        <?php $this->render_back_meta_fields($settings); ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

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

}
