<?php



use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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


class Productscarouseltenthstkaveh extends Widget_Base
{

  public function get_name()
  {
    return 'productscarouseltenthstkaveh';
  }

  public function get_title()
  {
    return esc_html__('Products Carousel Style Ten', 'kavehTheme');
  }

  public function get_icon()
  {
    return 'eicon-archive-posts';
  }

  public function get_categories()
  {
    return ['kavehelements'];
  }

  protected function register_controls()
  {
    $this->start_controls_section(
      'content0productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Flash Sale Products Settings', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );
    $this->add_control(
      'pproductslahzecarouseltenthstkaveh',
      [
        'label' => esc_html__('Show Products', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'all',
          'options' => [
            'all' => esc_html__('All', 'kavehTheme'),
            'cat' => esc_html__('Category', 'kavehTheme'),

        ],
      ]
    );
    $this->add_control(
      'psortproductslahzecarouseltenthstkaveh',
      [
        'label' => esc_html__('Sort Products By', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'date',
          'options' => [
            'date' => esc_html__('Date', 'kavehTheme'),
            '_price' => esc_html__('Price', 'kavehTheme'),
            '_wc_average_rating' => esc_html__('Most Popular', 'kavehTheme'),
            'total_sales' => esc_html__('Sales Amount', 'kavehTheme'),

        ],
      ]
    );
    $this->add_control(
      'psortiproductslahzecarouseltenthstkaveh',
      [
        'label' => esc_html__('Sort Type', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'desc',
          'options' => [
            'asc' => esc_html__('Ascending', 'kavehTheme'),
            'desc' => esc_html__('Descending', 'kavehTheme'),
        ],
      ]
    );
    $options2 = array();
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false;
    $cat_args = array(
      'orderby' => $orderby,
      'order' => $order,
      'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms('product_cat', $cat_args);

    foreach ($product_categories as $key => $category) {
      $options2[$category->term_id] = $category->name;
    }
    $this->add_control(
      'catproductslahzecarouseltenthstkaveh',
      [
        'label' => esc_html__('Select Category', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => $options2,
        'condition' => [
          'pproductslahzecarouseltenthstkaveh' => 'cat',
        ],
      ]
    );
    $this->add_control(
      'backnvchjlahzecarouseltenthstkaveh',
      [
        'label' => esc_html__('Bottom Box Image', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::MEDIA,
        'selectors' => [
          '{{WRAPPER}} .discount-products-right::after' => 'background: url({{URL}}) 0 0 no-repeat',
        ],
      ]
    );
    $this->end_controls_section();

    $this->start_controls_section(
      'content2productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Left Side Products Settings', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );
    $this->add_control(
      'kaveh_exclude_out_of_stock',
      [
        'label' => esc_html__('Hide Out of Stock Products', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'yes' => esc_html__('Yes', 'kavehTheme'),
        'no' => esc_html__('No', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'yes',
      ]
    );
    $this->add_control(
      'pproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Show Products', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'all',
          'options' => [
            'all' => esc_html__('All', 'kavehTheme'),
            'cat' => esc_html__('Category', 'kavehTheme'),

        ],
      ]
    );
    $this->add_control(
      'psortproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Sort Products By', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'date',
          'options' => [
            'date' => esc_html__('Date', 'kavehTheme'),
            '_price' => esc_html__('Price', 'kavehTheme'),
            '_wc_average_rating' => esc_html__('Most Popular', 'kavehTheme'),
            'total_sales' => esc_html__('Sales Amount', 'kavehTheme'),

        ],
      ]
    );
    $this->add_control(
      'psortiproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Sort Type', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SELECT,
          'default' => 'desc',
          'options' => [
            'asc' => esc_html__('Ascending', 'kavehTheme'),
            'desc' => esc_html__('Descending', 'kavehTheme'),
        ],
      ]
    );
    $options2 = array();
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false;
    $cat_args = array(
      'orderby' => $orderby,
      'order' => $order,
      'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms('product_cat', $cat_args);

    foreach ($product_categories as $key => $category) {
      $options2[$category->term_id] = $category->name;
    }
    $this->add_control(
      'catproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Select Category', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => $options2,
        'condition' => [
          'pproductscarouseltenthstkaveh' => 'cat',
        ],
      ]
    );
    $this->end_controls_section();
    $this->start_controls_section(
      'content3productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Carousel Settings', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );

    // First Carousel Settings
    $this->add_control(
      'first_carousel_heading',
      [
        'label' => esc_html__('First Carousel Settings', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::HEADING,
        'separator' => 'before',
      ]
    );

    $this->add_control(
      'first_carousel_autoplay',
      [
        'label' => esc_html__('Autoplay', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'label_on' => esc_html__('Enable', 'kavehTheme'),
        'label_off' => esc_html__('Disable', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'yes',
      ]
    );

    $this->add_control(
      'first_carousel_autoplay_delay',
      [
        'label' => esc_html__('Autoplay Delay (milliseconds)', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1000,
        'max' => 10000,
        'step' => 500,
        'default' => 5000,
        'condition' => [
          'first_carousel_autoplay' => 'yes',
        ],
      ]
    );

    $this->add_control(
      'first_carousel_loop',
      [
        'label' => esc_html__('Loop', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'label_on' => esc_html__('Enable', 'kavehTheme'),
        'label_off' => esc_html__('Disable', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'yes',
      ]
    );

    $this->add_control(
      'first_carousel_effect',
      [
        'label' => esc_html__('Effect', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT,
        'default' => 'fade',
        'options' => [
          'fade' => esc_html__('Fade', 'kavehTheme'),
          'slide' => esc_html__('Slide', 'kavehTheme'),
        ],
      ]
    );

    // Second Carousel Settings
    $this->add_control(
      'second_carousel_heading',
      [
        'label' => esc_html__('Second Carousel Settings', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::HEADING,
        'separator' => 'before',
      ]
    );

    $this->add_control(
      'showarrowproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Show Arrows?', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SWITCHER,
          'label_on' => esc_html__('Yes', 'kavehTheme'),
          'label_off' => esc_html__('No', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'yes',
      ]
    );

    $this->add_control(
      'second_carousel_loop',
      [
        'label' => esc_html__('Loop', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'label_on' => esc_html__('Enable', 'kavehTheme'),
        'label_off' => esc_html__('Disable', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'yes',
      ]
    );

    $this->add_control(
      'second_carousel_autoplay',
      [
        'label' => esc_html__('Autoplay', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'label_on' => esc_html__('Enable', 'kavehTheme'),
        'label_off' => esc_html__('Disable', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'no',
      ]
    );

    $this->add_control(
      'second_carousel_autoplay_delay',
      [
        'label' => esc_html__('Autoplay Delay (milliseconds)', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1000,
        'max' => 10000,
        'step' => 500,
        'default' => 5000,
        'condition' => [
          'second_carousel_autoplay' => 'yes',
        ],
      ]
    );

    // Responsive Settings
    $this->add_control(
      'responsive_heading',
      [
        'label' => esc_html__('Responsive Settings', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::HEADING,
        'separator' => 'before',
      ]
    );

    $this->add_control(
      'productcolumnproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Number of Product Columns on Desktop', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1,
        'max' => 6,
        'step' => 1,
        'default' => 3,
      ]
    );

    $this->add_control(
      'productcolumn2productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Number of Product Columns on Tablet', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1,
        'max' => 4,
        'step' => 1,
        'default' => 2,
      ]
    );

    $this->add_control(
      'productcolumn3productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Number of Product Columns on Mobile', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1,
        'max' => 2,
        'step' => 1,
        'default' => 1,
      ]
    );

    $this->add_control(
      'productnumberproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Number of Products Displayed', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 1,
        'max' => 50,
        'step' => 1,
        'default' => 5,
      ]
    );

    $this->end_controls_section();

    $this->start_controls_section(
      'style3_productscarouseltenthstkaveh',
      [
        'label' => esc_html__('General Style', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_STYLE,
      ]
    );
    $this->add_control(
      'bgcolorproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Right Box Background Color', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          '{{WRAPPER}} .discount-products-right::before' => 'background-color: {{VALUE}}',
        ],
      ]
    );

    $this->add_control(
      'bgcoloriconproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Arrows Color', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'condition' => [
          'showarrowproductscarouseltenthstkaveh' => 'yes',
        ],
        'selectors' => [
          '{{WRAPPER}} .discount-products-left .swiper-button-next::after' => 'color: {{VALUE}}',
          '{{WRAPPER}} .discount-products-left .swiper-button-prev::after' => 'color: {{VALUE}}',

        ],
      ]
    );
    $this->add_control(
      'boxradiusproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Right Box Border Radius', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px'],
        'selectors' => [
          '{{WRAPPER}} .discount-products-right::before' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
      ]
    );
    $this->end_controls_section();
    $this->start_controls_section(
      'style4_productscarouseltenthstkaveh',
      [
        'label' => esc_html__('Image Style', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_STYLE,
      ]
    );
    $this->add_control(
      'width2bgproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Bottom Box Image Size', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SLIDER,
        'size_units' => ['px'],
        'range' => [
          'px' => [
            'min' => 0,
            'max' => 2000,
            'step' => 5,
          ],
        ],
        'selectors' => [
          '{{WRAPPER}} .discount-products-right::after' => 'width: {{SIZE}}{{UNIT}};',
          '{{WRAPPER}} .discount-products-right::after' => 'height: {{SIZE}}{{UNIT}};',

        ],
      ]
    );
    $this->add_control(
      'top2bgproductscarouseltenthstkaveh',
      [
        'label' => esc_html__('Image Top Spacing', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SLIDER,
        'size_units' => ['px'],
        'range' => [
          'px' => [
            'min' => 0,
            'max' => 2000,
            'step' => 5,
          ],
        ],
        'selectors' => [
          '{{WRAPPER}} .discount-products-right::after' => 'top: {{SIZE}}{{UNIT}};',

        ],
      ]
    );
    $this->end_controls_section();
  }


  protected function render() {
    $settings = $this->get_settings_for_display();
    $widget_id = $this->get_id();

    // Build first swiper settings array
    $first_swiper_settings = array(
      'slidesPerView' => 1,
      'spaceBetween' => 0,
      'loop' => $settings['first_carousel_loop'] === 'yes',
      'effect' => $settings['first_carousel_effect'],
    );

    if ($settings['first_carousel_autoplay'] === 'yes') {
      $first_swiper_settings['autoplay'] = array(
        'delay' => (int) $settings['first_carousel_autoplay_delay'],
        'disableOnInteraction' => false
      );
    }

    if ($settings['first_carousel_effect'] === 'fade') {
      $first_swiper_settings['fadeEffect'] = array(
        'crossFade' => true
      );
    }

    // Build second swiper settings array
    $second_swiper_settings = array(
      'loop' => $settings['second_carousel_loop'] === 'yes',
      'breakpoints' => array(
        320 => array(
          'slidesPerView' => (int) $settings['productcolumn3productscarouseltenthstkaveh'],
          'spaceBetween' => 4
        ),
        768 => array(
          'slidesPerView' => (int) $settings['productcolumn2productscarouseltenthstkaveh'],
          'spaceBetween' => 12
        ),
        992 => array(
          'slidesPerView' => (int) $settings['productcolumnproductscarouseltenthstkaveh'],
          'spaceBetween' => 12
        ),
        1200 => array(
          'slidesPerView' => (int) $settings['productcolumnproductscarouseltenthstkaveh'],
          'spaceBetween' => 20
        )
      )
    );

    if ($settings['showarrowproductscarouseltenthstkaveh'] === 'yes') {
      $second_swiper_settings['navigation'] = array(
        'nextEl' => '.swiper-button-next',
        'prevEl' => '.swiper-button-prev'
      );
    }

    if ($settings['second_carousel_autoplay'] === 'yes') {
      $second_swiper_settings['autoplay'] = array(
        'delay' => (int) $settings['second_carousel_autoplay_delay'],
        'disableOnInteraction' => false
      );
    }

    // Properly encode and escape JSON
    $first_swiper_json = wp_json_encode($first_swiper_settings, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $second_swiper_json = wp_json_encode($second_swiper_settings, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    ?>
    <section class="discount-products my-100">
      <div class="container d-flex flex-column flex-sm-row">
        <div class="discount-products-right w-100 position-relative">
          <!-- Start Carousel -->
          <div class="swiper swiper-discount-products overflow-hidden" data-swiper='<?php echo esc_attr($first_swiper_json); ?>'>
            <div class="swiper-wrapper">
              <?php 
              $args = array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'posts_per_page' => $settings['productnumberproductscarouseltenthstkaveh'],
                'order' => $settings['psortiproductslahzecarouseltenthstkaveh'],
                'orderby' => $settings['psortproductslahzecarouseltenthstkaveh'] === 'date' ? 'date' : 'meta_value_num',
                'meta_key' => $settings['psortproductslahzecarouseltenthstkaveh'] === 'date' ? '' : $settings['psortproductslahzecarouseltenthstkaveh'],
                'post__in' => array_merge(array(0), wc_get_product_ids_on_sale())
              );

              if ($settings['pproductslahzecarouseltenthstkaveh'] === 'cat' && !empty($settings['catproductslahzecarouseltenthstkaveh'])) {
                $args['tax_query'] = array(
                  array(
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => $settings['catproductslahzecarouseltenthstkaveh'],
                  )
                );
              }

              if ("yes" === $settings['kaveh_exclude_out_of_stock']) {
                $args['meta_query'] = array(
                  array(
                    'key' => '_stock_status',
                    'value' => 'outofstock',
                    'compare' => '!=',
                  ),
                );
              }

              $products_query = new \WP_Query($args);

              if ($products_query->have_posts()) {
                while ($products_query->have_posts()) {
                  $products_query->the_post();
                  global $product;
                  $product_id = $product->get_id();
                  $stock_status = $product->get_stock_status();
                  ?>
                  <div class="swiper-slide h-auto">
                    <div class="product-two product-two-new">
                      <div class="cs-height_10 cs-height_lg_10"></div>
                      <?php 
                      $date_to = get_post_meta($product_id, '_sale_price_dates_to', true);
                      if ("instock" == $stock_status && $date_to) {
                        $deal_end_date = date('Y-m-d 23:59:59', $date_to);
                        ?>
                        <ul class="timear position-absolute top-50 start-0" data-time="<?php echo esc_attr($deal_end_date); ?>">
                          <li>
                            <span class="hour d-flex align-items-center justify-content-center rounded-circle">00</span>
                            Hour
                          </li>
                          <li>
                            <span class="minute d-flex align-items-center justify-content-center rounded-circle">00</span>
                            Minute
                          </li>
                          <li>
                            <span class="second d-flex align-items-center justify-content-center rounded-circle">00</span>
                            Second
                          </li>
                        </ul>
                      <?php } ?>
                      <?php 
                      $styleproduct = $settings['stylecartproductscarouseltenthstkaveh']; 
                      get_template_part("template-part/product-cart-$styleproduct"); 
                      ?>
                    </div>
                  </div>
                  <?php
                }
                wp_reset_postdata();
              }
              ?>
            </div>
          </div>
          <!-- End Carousel -->
        </div>
        
        <div class="discount-products-left w-100 position-relative mt-4 mt-sm-0">
          <!-- Start Carousel -->
          <div class="swiper swiper-discount-products-two overflow-hidden" data-swiper='<?php echo esc_attr($second_swiper_json); ?>'>
            <div class="swiper-wrapper">
              <?php 
              $args = array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'posts_per_page' => $settings['productnumberproductscarouseltenthstkaveh'],
                'order' => $settings['psortiproductscarouseltenthstkaveh'],
                'orderby' => $settings['psortproductscarouseltenthstkaveh'] === 'date' ? 'date' : 'meta_value_num',
                'meta_key' => $settings['psortproductscarouseltenthstkaveh'] === 'date' ? '' : $settings['psortproductscarouseltenthstkaveh']
              );

              if ($settings['pproductscarouseltenthstkaveh'] === 'cat' && !empty($settings['catproductscarouseltenthstkaveh'])) {
                $args['tax_query'] = array(
                  array(
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => $settings['catproductscarouseltenthstkaveh'],
                  )
                );
              }

              if ("yes" === $settings['kaveh_exclude_out_of_stock']) {
                $args['meta_query'] = array(
                  array(
                    'key' => '_stock_status',
                    'value' => 'outofstock',
                    'compare' => '!=',
                  ),
                );
              }

              $products_query = new \WP_Query($args);

              if ($products_query->have_posts()) {
                while ($products_query->have_posts()) {
                  $products_query->the_post();
                  ?>
                  <div class="swiper-slide h-auto">
                    <?php 
                    $styleproduct = $settings['stylecartproductscarouseltenthstkaveh']; 
                    get_template_part("template-part/product-cart-$styleproduct"); 
                    ?>
                  </div>
                  <?php
                }
                wp_reset_postdata();
              }
              ?>
            </div>
            <?php if ("yes" === $settings['showarrowproductscarouseltenthstkaveh']) { ?>
              <div class="swiper-button-next"></div>
              <div class="swiper-button-prev"></div>
            <?php } ?>
          </div>
          <!-- End Carousel -->
        </div>
      </div>
    </section>
    
    <?php if (\Elementor\Plugin::$instance->editor->is_edit_mode()): ?>
      <script>
        (function($) {
          function initSwiper<?php echo $widget_id; ?>() {
            // Initialize first carousel
            $('.swiper-discount-products').each(function() {
              const $this = $(this);
              const options = JSON.parse($this.attr('data-swiper'));
              new Swiper(this, options);
            });
            
            // Initialize second carousel
            $('.swiper-discount-products-two').each(function() {
              const $this = $(this);
              const options = JSON.parse($this.attr('data-swiper'));
              new Swiper(this, options);
            });
          }
          
          // Initialize on document ready
          $(document).ready(function() {
            initSwiper<?php echo $widget_id; ?>();
          });
          
          // Initialize on Elementor frontend
          $(window).on('elementor/frontend/init', function() {
            elementorFrontend.hooks.addAction('frontend/element_ready/productscarouseltenthstkaveh.default', function() {
              initSwiper<?php echo $widget_id; ?>();
            });
          });
        })(jQuery);
      </script>
    <?php endif; ?>
    <?php
  }


}
