<?php
if (!defined('ABSPATH')) {
    exit;
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Typography;
use \Elementor\Group_Control_Image_Size;
use \Elementor\Repeater;
use \Elementor\Icons_Manager;
use \Sifency\Traits\Sifency_Arg_Controls;
use \Sifency\Traits\Sifency_Animation_Controls;
use \Sifency\Traits\Sifency_Elementor_Parity_Controls;
use Sifency\Traits\Sifency_Core_Text_Style;

use Sifency\Traits\Sifency_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Icon_Style_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Team_Controls;


class Sifency_Addons_Widget_Team extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Arg_Controls;
    use Sifency_Core_Text_Style;

    use Sifency_Item_Style_Controls;
    use Sifency_Addons_Slider_Controls;
    use Sifency_Icon_Style_Controls;
    use Sifency_Team_Controls;

    public function get_name() {
        return 'sifency-addons-team';
    }
    
    public function get_title() {
        return esc_html__('Sifency Team', 'sifency-addons');
    }
    
    public function get_icon() {
        return 'eicon-person';
    }
    
    public function get_categories() {
        return ['sifency-advance-widgets'];
    }

    public function get_script_depends() {
        return $this->get_carousel_script_depends();
    }

    public function get_style_depends() {
        return [ 'sifency-typo-style' , 'swiper', 'sifency-swiper-style', 'sifency-frontend-style', 'sifency-team-style', 'sifency-icon' ];
    }  
    protected function register_controls() {
        $carousel_condition = [
            'condition' => [
                'layout_style' => 'carousel'
            ]
        ];
        $this->add_sifency_team_controls();
        $this->add_sifency_carousel_controls($carousel_condition);
        $this->add_sifency_item_style_controls();
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'heading_style',
            'label'    => 'Member Name',
            'selector' => '.sifency-heading-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'content_style',
            'label'    => 'Member Designation',
            'selector' => '.sifency-content-style',
            'target_children' => false,
        ]);
        $this->add_sifency_icon_style_controls();
        Sifency_Elementor_Parity_Controls::register( $this );
        $this->add_sifency_animation_controls();
    }
    
/**
 * Render the widget output on the frontend.
 *
 * @since 1.0.4
 * @access protected
 */
protected function render() {
        $settings = $this->get_settings_for_display();
        $animation_manager = new Sifency_Animation_Manager($settings);
        $this->add_render_attribute( 'wrapper', 'class', 'sifency-team-wrapper' );
        $wrapper_attrs = $animation_manager->get_wrapper_attributes([]);
        if ( ! empty($wrapper_attrs) ) {
            preg_match('/class="([^"]+)"/', $wrapper_attrs, $class_matches);
            if (isset($class_matches[1])) { $this->add_render_attribute('wrapper', 'class', $class_matches[1]); }
        }
        $is_carousel = ('carousel' === $settings['layout_style']);
        if ($is_carousel) {
            $this->add_render_attribute('layout_container', 'class', 'swiper-container');
            
            $this->add_render_attribute('wrapper', 'class', 'sifency-carousel-wrapper');
            $slide_count = ('posts' === $settings['source'])
                ? (new \WP_Query(array_merge($this->get_sifency_query_args() ?? [], ['post_type' => $settings['query_post_type'] ?? 'team'])))->post_count
                : count($settings['team_list'] ?? []);
            $slider_options = $this->get_sifency_swiper_options($settings, $slide_count);
            $this->add_render_attribute('wrapper', 'data-swiper-options', wp_json_encode($slider_options));
        } else {
            $this->add_render_attribute('layout_container', 'class', 'sifency-team-grid');
        }

        ?>
        <div <?php echo wp_kses_post($this->get_render_attribute_string('wrapper')); ?>>
            <div <?php  ?><?php echo wp_kses_post($this->get_render_attribute_string('layout_container')); ?>>
                <?php if ($is_carousel) { echo '<div class="swiper-wrapper">'; } ?>

                <?php
                if ( 'posts' === $settings['source'] ) {
                    $this->render_posts_content($settings, $animation_manager);
                } else {
                    $this->render_custom_content($settings, $animation_manager);
                }
                ?>
                <?php if ($is_carousel) { echo '</div>'; } ?>
                
                <?php
                if ($is_carousel) {
                    if ( 'yes' === ($settings['show_arrows'] ?? 'no') ) { ?>
                        <div class="sifency-slider-nav-container">
                            <div class="sifency-slider-nav-arrow sifency-slider-nav-prev swiper-button-prev">
                                <i class="icon-left"></i>
                            </div>
                            <div class="sifency-slider-nav-arrow sifency-slider-nav-next swiper-button-next">
                               <i class="icon-right"></i>
                            </div>
                        </div>
                    <?php }
                    if ( ! empty($settings['show_pagination']) ) { 
                        echo '<div class="swiper-pagination"></div>';
                    }
                }
                ?>
            </div>
        </div>
        <?php
    }

private function render_custom_content($settings, Sifency_Animation_Manager $animation_manager) {
    if ( empty($settings['team_list']) ) { return; }
    
    foreach ($settings['team_list'] as $index => $item) {
        $oi = $index + 1;
        $parity_class = ($oi % 2 !== 0) ? 'odd-item' : 'even-item';
        
        $this->render_team_member($item, $parity_class, $settings, $animation_manager);
    }
}

private function render_posts_content($settings, Sifency_Animation_Manager $animation_manager) {
    $query_args = method_exists($this, 'get_sifency_query_args') ? $this->get_sifency_query_args() : [];
    $query_args['post_type'] = $settings['query_post_type'] ?? 'team';
    $query = new \WP_Query( $query_args );

    if ( ! $query->have_posts() ) { return; }

    while( $query->have_posts() ) : $query->the_post();
        $oi = $query->current_post + 1;
        $parity_class = ($oi % 2 !== 0) ? 'odd-item' : 'even-item';
        
        $meta = get_post_meta(get_the_ID(), 'team_options_metabox', true) ?: [];
        $member_data = [
            'name' => get_the_title(), 'image' => [ 'id' => get_post_thumbnail_id() ],
            'position' => $meta['member_position'] ?? '', 'link' => [ 'url' => get_permalink() ],
            'social_icons' => $meta['member_social_icons'] ?? [],
        ];

        $this->render_team_member($member_data, $parity_class, $settings, $animation_manager);
    endwhile;
    wp_reset_postdata();
}

private function render_team_member($member, $parity_class, $settings, Sifency_Animation_Manager $animation_manager) {
    $is_carousel = ('carousel' === $settings['layout_style']);

    $item_container_tag = $is_carousel ? 'div' : 'div';
    $item_container_classes = $is_carousel ? ['swiper-slide'] : ['sifency-item-style', 'sifency-team-item', $parity_class];
    $item_container_attrs = $animation_manager->get_item_attributes($item_container_classes);

    $link_key = 'member_link_' . ( $member['image']['id'] ?? wp_rand( 1000, 9999 ) );
    $this->remove_render_attribute($link_key);
    ?>
    <<?php  ?><?php echo esc_html($item_container_tag); ?> <?php echo wp_kses_post($item_container_attrs); ?>>
        <?php if ($is_carousel) : ?>
            <div class="sifency-item-style sifency-team-item <?php echo esc_attr($parity_class); ?>">
        <?php endif; ?>

            <div class="sifency-team-item__image">
                <?php
                if ( ! empty($member['link']['url']) ) {
                    $this->add_link_attributes($link_key, $member['link']);
                    echo '<a ' . wp_kses_post ( $this->get_render_attribute_string($link_key) ) . '>';
                }
                
                echo wp_kses_post (\Elementor\Group_Control_Image_Size::get_attachment_image_html( $member, 'thumbnail', 'image' ));
                if ( ! empty($member['link']['url']) ) { echo '</a>'; }
                ?>
            </div>
            <div class="sifency-team-item__content">
                <h3 class="sifency-team-item__name sifency-heading-style">
                    <?php if ( ! empty($member['link']['url']) ) : ?>
                        <a <?php  ?><?php echo wp_kses_post ( $this->get_render_attribute_string($link_key)); ?>>
                            <?php echo esc_html($member['name']); ?>
                        </a>
                    <?php else: ?>
                        <?php echo esc_html($member['name']); ?>
                    <?php endif; ?>
                </h3>
                <?php if ( ! empty($member['position']) ) : ?>
                    <div class="sifency-team-item__position sifency-content-style"><?php echo esc_html($member['position']); ?></div>
                <?php endif; ?>
                
                <?php if ( ! empty($member['social_icons']) ) : ?>
                    <div class="sifency-team-item__social">
                        <?php foreach ($member['social_icons'] as $icon_item) :

                            $icon_data = $icon_item['social_icon'] ?? null;
                            $social_link_key = 'social_link_' . ($icon_item['_id'] ?? wp_rand());

                            // Add link if available
                            $this->remove_render_attribute($social_link_key);
                            if (!empty($icon_item['link']['url'])) {
                                $this->add_link_attributes($social_link_key, $icon_item['link']);
                            } else {
                                $this->add_render_attribute($social_link_key, 'href', '#');
                            }
                            
                            echo '<a ' . wp_kses_post ( $this->get_render_attribute_string($social_link_key)) . ' class="sifency-icon-style">';

                            if ( is_array($icon_data) && ! empty($icon_data['value']) ) {
                                \Elementor\Icons_Manager::render_icon(
                                    $icon_data,
                                    [ 'aria-hidden' => 'true' ]
                                );
                            } elseif ( ! empty($icon_data) && is_string($icon_data) ) {
                                echo '<i class="' . esc_attr($icon_data) . '" aria-hidden="true"></i>';
                            }

                            echo '</a>';

                        endforeach; ?>
                    </div>
                <?php endif; ?>

            </div>

        <?php if ($is_carousel) : ?>
            </div>
        <?php endif; ?>
    </<?php echo esc_html($item_container_tag); ?><?php  ?>>
    <?php
}
}