<?php
if (!defined('ABSPATH')) {
    exit;
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Repeater;
use \Sifency\Traits\Sifency_Arg_Controls;
use \Sifency\Traits\Sifency_Animation_Controls;
use \Sifency\Traits\Sifency_Elementor_Parity_Controls;
use Sifency\Traits\Sifency_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Clients_Controls;
use Sifency\Traits\Sifency_Image_Style_Controls;

class Sifency_Addons_Widget_Clients extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Addons_Slider_Controls;
    use Sifency_Arg_Controls;
    use Sifency_Item_Style_Controls;
    use Sifency_Clients_Controls;
    use Sifency_Image_Style_Controls;

    public function get_name() {
        return 'sifency-addons-clients';
    }
    
    public function get_title() {
        return esc_html__('Sifency Clients', 'sifency-addons');
    }
    
    public function get_icon() {
        return 'eicon-gallery-grid';
    }
    
    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 [ 'swiper', 'sifency-swiper-style', 'sifency-frontend-style', 'sifency-clients-style', 'sifency-icon' ];
    } 
      
    protected function register_controls() {
        $carousel_condition = [
            'condition' => [
                'layout_style' => 'carousel'
            ]
        ];
        $this->add_sifency_clients_controls();
        $this->add_sifency_carousel_controls( $carousel_condition );
        $this->add_sifency_item_style_controls();
        $this->add_sifency_image_style_controls();
        Sifency_Elementor_Parity_Controls::register( $this );
        $this->add_sifency_animation_controls();
    }
    
    protected function render() {
        $settings = $this->get_settings_for_display();
        $animation_manager = new Sifency_Animation_Manager($settings);
        $is_carousel = ('carousel' === $settings['layout_style']);

        $this->add_render_attribute('wrapper', 'class', 'sifency-clients-wrapper');
        
        $animation_attrs = $animation_manager->get_wrapper_attributes();
        if (!empty($animation_attrs)) {
            preg_match('/class="([^"]+)"/', $animation_attrs, $class_matches);
            if (isset($class_matches[1])) {
                $this->add_render_attribute('wrapper', 'class', $class_matches[1]);
            }
        }

        if ($is_carousel) {
            $this->add_render_attribute('wrapper', 'class', [ 'sifency-carousel-wrapper', 'swiper-container' ]);
            
            $slide_count = ('posts' === $settings['source']) 
                ? (new \WP_Query(array_merge($this->get_sifency_query_args() ?? [], ['post_type' => $settings['query_post_type'] ?? 'client'])))->post_count 
                : count($settings['client_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('wrapper', 'class', 'sifency-clients--grid');
        }
        
        ?>
        <div <?php echo wp_kses_post ($this->get_render_attribute_string('wrapper')); ?>>
            <?php if ($is_carousel) : ?>
                <div class="swiper-wrapper">
            <?php endif; ?>

            <?php
            if ('posts' === $settings['source']) {
                $this->render_posts_content($settings, $animation_manager);
            } else {
                $this->render_custom_content($settings, $animation_manager);
            }
            ?>

            <?php if ($is_carousel) : ?>
                </div> <?php // End .swiper-wrapper ?>

                <?php if ( ! empty($settings['show_arrows']) && 'yes' === $settings['show_arrows'] ) : ?>
                    <div class="sifency-slider-nav-container">
                    <div class="swiper-button-prev sifency-slider-nav-arrow sifency-slider-nav-prev"><i class="icon-left"></i></div>
                    <div class="swiper-button-next sifency-slider-nav-arrow sifency-slider-nav-next"><i class="icon-right"></i></div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($settings['show_pagination'])) : ?>
                    <div class="swiper-pagination"></div>
                <?php endif; ?>
            <?php endif; ?>
        </div> <?php // End main wrapper
    }

    private function render_custom_content($settings, Sifency_Animation_Manager $animation_manager) {
        if ( empty($settings['client_list']) ) { return; }
        
        $is_carousel = ('carousel' === $settings['layout_style']);

        foreach ($settings['client_list'] as $index => $item) {
            $tag = 'span';
            $item_attrs = [];

            if ( ! empty($item['link']['url']) ) {
                $tag = 'a';
                $item_attrs['href'] = esc_url($item['link']['url']);
                if ( ! empty($item['link']['is_external']) ) {
                    $item_attrs['target'] = '_blank';
                }
                if ( ! empty($item['link']['nofollow']) ) {
                    $item_attrs['rel'] = 'nofollow';
                }
            }
            
            $base_item_classes = ['sifency-item-style', 'sifency-client-item'];
            if (($index + 1) % 2 !== 0) {
                $base_item_classes[] = 'odd-item';
            } else {
                $base_item_classes[] = 'even-item';
            }

            if ($is_carousel) {
                $slide_attrs = $animation_manager->get_item_attributes(['swiper-slide']);
                
                echo wp_kses_post ('<div ' . $slide_attrs . '>');

                $this->add_render_attribute('inner_item', ['class' => $base_item_classes] + $item_attrs, true);
                ?>
                <<?php echo esc_html($tag); ?> <?php echo wp_kses_post ($this->get_render_attribute_string('inner_item')); ?>>
                    <?php if ( ! empty($item['client_logo']['url']) ) : ?>
                        <div class="sifency-image-container">
                        <img src="<?php echo esc_url($item['client_logo']['url']); ?>" alt="<?php echo esc_attr($item['client_name']); ?>" />
                        <div class="sifency-image-overlay"></div>
                        </div>
                    <?php endif; ?>
                </<?php echo esc_html ($tag); ?>>
                <?php
                echo '</div>'; // End .swiper-slide
            } else {
                $final_item_attrs = $animation_manager->get_item_attributes($base_item_classes);
                
                $final_tag_attrs = $final_item_attrs;
                if ('a' === $tag) {
                    $link_attrs_string = '';
                    foreach ($item_attrs as $key => $value) {
                        $link_attrs_string .= esc_attr($key) . '="' . esc_attr($value) . '" ';
                    }
                    $final_tag_attrs = $link_attrs_string . $final_item_attrs;
                }

                ?>
                
                <<?php echo esc_html($tag); ?> <?php echo wp_kses_post ($final_tag_attrs); ?>>
                    <?php if ( ! empty($item['client_logo']['url']) ) : ?>
                        <div class="sifency-image-container">
                        <img src="<?php echo esc_url($item['client_logo']['url']); ?>" alt="<?php echo esc_attr($item['client_name']); ?>" />
                        <div class="sifency-image-overlay"></div>
                        </div>
                    <?php endif; ?>
                </<?php
                echo esc_html($tag); ?>>
                <?php
            }
        }
    }

    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'] ?? 'client';
        $query = new \WP_Query( $query_args );

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

        $is_carousel = ('carousel' === $settings['layout_style']);

        while( $query->have_posts() ) : $query->the_post();
            $client_link = get_post_meta(get_the_ID(), 'client_link', true);
            $tag = empty($client_link) ? 'span' : 'a';
            $item_attrs = [];
            
            if ('a' === $tag) {
                $item_attrs['href'] = esc_url($client_link);
                $item_attrs['rel'] = 'noopener';
            }

            // Define the base classes for the clickable/visible item
            $base_item_classes = ['sifency-item-style', 'sifency-client-item'];
            if (($query->current_post + 1) % 2 !== 0) {
                $base_item_classes[] = 'odd-item';
            } else {
                $base_item_classes[] = 'even-item';
            }

            if ($is_carousel) {
                $slide_attrs = $animation_manager->get_item_attributes(['swiper-slide']);
                
                echo wp_kses_post ('<div ' . $slide_attrs . '>');
                $this->add_render_attribute('inner_post_item', ['class' => $base_item_classes] + $item_attrs, true);
                ?>
                <<?php echo esc_html($tag); ?> <?php echo wp_kses_post ($this->get_render_attribute_string('inner_post_item')); ?>>
                    <?php if ( has_post_thumbnail() ) { the_post_thumbnail('large'); } ?>
                </<?php echo esc_html($tag); ?>>
                <?php
                echo '</div>'; // End .swiper-slide
            } else {
                $final_item_attrs = $animation_manager->get_item_attributes($base_item_classes);
                
                $final_tag_attrs = $final_item_attrs;
                if ('a' === $tag) {
                    $link_attrs_string = '';
                    foreach ($item_attrs as $key => $value) {
                        $link_attrs_string .= esc_attr($key) . '="' . esc_attr($value) . '" ';
                    }
                    $final_tag_attrs = $link_attrs_string . $final_item_attrs;
                }
                ?>
                <<?php echo esc_html($tag); ?> <?php echo wp_kses_post ($final_tag_attrs); ?>>
                    <?php if ( has_post_thumbnail() ) { the_post_thumbnail('large'); } ?>
                </<?php echo esc_html ($tag); ?>>
                <?php
            }
        endwhile;
        wp_reset_postdata();
    }
}