<?php
namespace UM_Elementor\Base;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Css_Filter;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Widget_Base;
use Elementor\Repeater;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;

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

abstract class UM_Elementor_Base_Widget extends Widget_Base
{
    /**
     * Get widget categories
     */
    public function get_categories()
    {
        return ['um-addons-elementor'];
    }

    public function get_description()
    {
        return __('Display Ultimate Member members in Elementor with filters, search, pagination, and styling.', 'ultimate-member-widgets-for-elementor');
    }

    public function get_keywords()
    {
        return ['ultimate member', 'um', 'members', 'directory', 'users', 'list', 'grid'];
    }

    /**
     * Get widget icon
     */
    public function get_icon()
    {
        return 'eicon-person';
    }

    /**
     * Register common user query controls
     */
    protected function register_user_query_controls()
    {
        $this->start_controls_section(
            'section_user_query',
            [
                'label' => __('User Query', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        // Show members by role
        $this->add_control(
            'query_show_selected_roles',
            [
                'label' => __('Filter by User Role', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'default' => false,
                'label_on' => __('Yes', 'ultimate-member-widgets-for-elementor'),
                'label_off' => __('No', 'ultimate-member-widgets-for-elementor'),
                'return_value' => 'yes',
            ]
        );

        // User Roles - Select2
        $this->add_control(
            'query_user_roles',
            [
                'label' => __('Select Roles', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'default' => '',
                'multiple' => true,
                'label_block' => true,
                'options' => user_elementor_um_get_user_roles(),
                'condition' => [
                    'query_show_selected_roles' => 'yes',
                ],
            ]
        );

        // Number of Members to display
        $this->add_control(
            'user_numbers',
            [
                'label' => __('Number of Users', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'default' => 4,
                'min' => 1,
                'max' => 1000,
                'step' => 1,
                'description' => __('Used when pagination is off. When pagination is enabled, use “Users per page” instead.', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        // Show only approved users
        $this->add_control(
            'show_only_approved_users',
            [
                'label' => __('Show Only Approved Users', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'no',
                'label_on' => __('Yes', 'ultimate-member-widgets-for-elementor'),
                'label_off' => __('No', 'ultimate-member-widgets-for-elementor'),
                'return_value' => 'yes',
                'description' => __('Show only users with approved account status', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        // Order Members by
        $this->add_control(
            'query_user_order_by',
            [
                'label' => esc_html__('Order by', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'display_name',
                'options' => [
                    'ID' => esc_html__('ID', 'ultimate-member-widgets-for-elementor'),
                    'display_name' => esc_html__('Display Name', 'ultimate-member-widgets-for-elementor'),
                    'user_name' => esc_html__('User Name', 'ultimate-member-widgets-for-elementor'),
                    'user_email' => esc_html__('User Email', 'ultimate-member-widgets-for-elementor'),
                    'user_registered' => esc_html__('Registered', 'ultimate-member-widgets-for-elementor'),
                    'post_count' => esc_html__('Post Count', 'ultimate-member-widgets-for-elementor'),
                    'last_login' => esc_html__('Login', 'ultimate-member-widgets-for-elementor'),
                    'first_name' => esc_html__('First Name', 'ultimate-member-widgets-for-elementor'),
                    'last_name' => esc_html__('Last Name', 'ultimate-member-widgets-for-elementor'),
                    'custom_field' => esc_html__('Custom Field', 'ultimate-member-widgets-for-elementor'),
                ],
            ]
        );

        // Meta Key
        $this->add_control(
            'user_query_by_meta_key',
            [
                'label' => esc_html__('Meta Key', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'label_block' => true,
                'condition' => ['query_user_order_by' => 'custom_field']
            ]
        );

        // Members Order
        $this->add_control(
            'query_user_order',
            [
                'label' => esc_html__('Order', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'ASC',
                'options' => [
                    'ASC' => esc_html__('Ascending', 'ultimate-member-widgets-for-elementor'),
                    'DESC' => esc_html__('Descending', 'ultimate-member-widgets-for-elementor'),
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register user title controls
     */
    protected function register_user_title_controls()
    {
        $this->start_controls_section(
            'user_title_section',
            [
                'label' => esc_html__('User Title', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        // Show User Name
        $this->add_control(
            'um_elementor_show_member_name',
            [
                'label' => esc_html__('Show User Title', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    1 => [
                        'title' => esc_html__('Yes', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-check',
                    ],
                    0 => [
                        'title' => esc_html__('No', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-ban',
                    ]
                ],
                'default' => '1',
            ]
        );

        // User Name
        $this->add_control(
            'user_display_title',
            [
                'label' => esc_html__('Title Source', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'display_name',
                'options' => [
                    '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'),
                ],
                'condition' => ['um_elementor_show_member_name' => '1']
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register user image controls
     */
    protected function register_user_image_controls()
    {
        $this->start_controls_section(
            'user_image_section',
            [
                'label' => esc_html__('User Image', 'ultimate-member-widgets-for-elementor'),
            ]
        );

        // Show User Image
        $this->add_control(
            'um_elementor_show_user_image',
            [
                'label' => esc_html__('Show User Image', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    1 => [
                        'title' => esc_html__('Yes', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-check',
                    ],
                    0 => [
                        'title' => esc_html__('No', 'ultimate-member-widgets-for-elementor'),
                        'icon' => 'eicon-ban',
                    ]
                ],
                'default' => '1',
            ]
        );

        // Image Border Radius
        $this->add_control(
            'user_avatar_border_radius',
            [
                'label' => esc_html__('Border Radius', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'default' => [
                    'top' => '50',
                    'bottom' => '50',
                    'left' => '50',
                    'right' => '50',
                    'unit' => '%',
                ],
                'selectors' => [
                    '{{WRAPPER}} .um-elementor-member-image img, {{WRAPPER}} .thumbnail-avatar img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Css_Filter::get_type(),
            [
                'name' => 'um_user_avatar_css_filter',
                'selector' => '{{WRAPPER}} .um-elementor-member-image img',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register user meta fields controls
     */
    protected function register_user_meta_controls($section_label = 'User Fields', $control_name = 'um_user_meta_control')
    {
        $this->start_controls_section(
            'um_user_meta_section_' . $control_name,
            [
                'label' => $section_label,
            ]
        );

        $repeater = new Repeater();

        // Meta Keys
        $repeater->add_control(
            'um_user_meta_field_value',
            [
                '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',
            [
                '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',
            ]
        );

        $repeater->add_control(
            'field_visibility',
            [
                'label'   => __( 'Visible to', 'ultimate-member-widgets-for-elementor' ),
                'type'    => Controls_Manager::SELECT,
                'default' => \UM_Elementor_Field_Visibility::EVERYONE,
                'options' => [
                    \UM_Elementor_Field_Visibility::EVERYONE       => __( 'Everyone', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::LOGGED_IN      => __( 'Logged-in users only', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::SPECIFIC_ROLES => __( 'Specific roles', 'ultimate-member-widgets-for-elementor' ),
                ],
            ]
        );

        $repeater->add_control(
            'field_visibility_roles',
            [
                'label'       => __( 'Allowed roles', 'ultimate-member-widgets-for-elementor' ),
                'type'        => Controls_Manager::SELECT2,
                'multiple'    => true,
                'default'     => [],
                'options'     => self::get_all_roles_for_visibility(),
                'condition'   => [
                    'field_visibility' => \UM_Elementor_Field_Visibility::SPECIFIC_ROLES,
                ],
                'description' => __( 'Administrators always see all fields.', 'ultimate-member-widgets-for-elementor' ),
            ]
        );

        $repeater->add_control(
            'field_value_condition_enable',
            [
                'label'        => __( 'Conditional display', 'ultimate-member-widgets-for-elementor' ),
                'type'         => Controls_Manager::SWITCHER,
                'label_on'     => __( 'On', 'ultimate-member-widgets-for-elementor' ),
                'label_off'    => __( 'Off', 'ultimate-member-widgets-for-elementor' ),
                'return_value' => 'yes',
                'default'      => '',
                'separator'    => 'before',
                'description'  => __( 'Show this field only when a value on the displayed user matches a rule (e.g. Gold badge only if membership = gold).', 'ultimate-member-widgets-for-elementor' ),
            ]
        );

        $repeater->add_control(
            'field_value_condition_key',
            [
                'label'       => __( 'When field', 'ultimate-member-widgets-for-elementor' ),
                'type'        => Controls_Manager::SELECT,
                'label_block' => true,
                'default'     => '',
                'options'     => user_elementor_um_get_user_meta_keys_combine(),
                'condition'   => [ 'field_value_condition_enable' => 'yes' ],
            ]
        );

        $repeater->add_control(
            'field_value_condition_operator',
            [
                'label'     => __( 'Operator', 'ultimate-member-widgets-for-elementor' ),
                'type'      => Controls_Manager::SELECT,
                'default'   => \UM_Elementor_Field_Visibility::OP_IS,
                'options'   => [
                    \UM_Elementor_Field_Visibility::OP_IS           => __( 'is equal to', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_IS_NOT       => __( 'is not equal to', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_CONTAINS     => __( 'contains', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_NOT_CONTAINS => __( 'does not contain', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_IN_LIST      => __( 'is one of (comma list)', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_GREATER_THAN => __( 'is greater than', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_LESS_THAN    => __( 'is less than', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_NOT_EMPTY    => __( 'is not empty', 'ultimate-member-widgets-for-elementor' ),
                    \UM_Elementor_Field_Visibility::OP_EMPTY        => __( 'is empty', 'ultimate-member-widgets-for-elementor' ),
                ],
                'condition' => [ 'field_value_condition_enable' => 'yes' ],
            ]
        );

        $repeater->add_control(
            'field_value_condition_value',
            [
                'label'       => __( 'Value', 'ultimate-member-widgets-for-elementor' ),
                'type'        => Controls_Manager::TEXT,
                'default'     => '',
                'label_block' => true,
                'placeholder' => __( 'e.g. gold', 'ultimate-member-widgets-for-elementor' ),
                'condition'   => [
                    'field_value_condition_enable'    => 'yes',
                    'field_value_condition_operator!' => [
                        \UM_Elementor_Field_Visibility::OP_EMPTY,
                        \UM_Elementor_Field_Visibility::OP_NOT_EMPTY,
                    ],
                ],
            ]
        );

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

        $this->end_controls_section();
    }

    /**
     * All WP + UM roles as an options array for the visibility repeater control.
     *
     * @return array<string, string>
     */
    private static function get_all_roles_for_visibility(): array {
        $options = [];

        foreach ( wp_roles()->get_names() as $key => $name ) {
            if ( $key === 'administrator' ) {
                continue;
            }
            $options[ $key ] = translate_user_role( $name );
        }

        if ( function_exists( 'UM' ) ) {
            $um_role_slugs = (array) get_option( 'um_roles', [] );
            foreach ( $um_role_slugs as $slug ) {
                $role_key = 'um_' . $slug;
                if ( isset( $options[ $role_key ] ) ) {
                    continue;
                }
                $role_meta = get_option( 'um_role_' . $slug . '_meta', [] );
                $label     = ! empty( $role_meta['name'] ) ? $role_meta['name'] : $role_key;
                $options[ $role_key ] = esc_html( $label );
            }
        }

        return $options;
    }

    /**
     * Register layout controls
     */
    protected function register_layout_controls()
    {
        $this->start_controls_section(
            'um_elementor_section_member_grid_layout_' . $this->get_name(),
            [
                'label' => __('Layout', 'ultimate-member-widgets-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE
            ]
        );

        // Number of Columns
        $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'),
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register common style controls
     */
    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'
            ]
        );

        // Member Blocks Color
        $this->add_control(
            'um_member_block_color',
            [
                'label' => __('Background Color', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#fff9f0',
                'selectors' => [
                    '{{WRAPPER}} .um-widget-member-holder' => 'background-color: {{VALUE}}',
                ]
            ]
        );

        // 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}};',
                ],
            ]
        );

        // Padding Between Users
        $this->add_responsive_control(
            'um_member_block_padding',
            [
                'label' => esc_html__('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}} .um-widget-member-holder' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        // Border Radius of User Block
        $this->add_control(
            'um_member_block_border_radius',
            [
                'label' => esc_html__('Border Radius', 'ultimate-member-widgets-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .um-widget-member-holder' => 'border-radius: {{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',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'um_user_block_box_shadow',
                'label' => esc_html__('Box Shadow', 'ultimate-member-widgets-for-elementor'),
                'selector' => '{{WRAPPER}} .um-widget-member-holder',
                'condition' => [
                    'allow_box_shadow!' => '',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Abstract method for widget-specific controls
     */
    abstract protected function register_widget_controls();

    /**
     * Final register_controls method
     */
    protected function register_controls()
    {
        $this->register_user_query_controls();
        $this->register_widget_controls();
        $this->register_user_title_controls();
        $this->register_user_image_controls();
        $this->register_common_style_controls();
    }

    /**
     * Empty content template
     */
    protected function content_template() {}
} 
