<?php



use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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


class Productstabgridkaveh extends Widget_Base
{

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

  public function get_title()
  {
    return esc_html__('Grid Products Tabs', 'kavehTheme');
  }

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

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

  protected function register_controls()
  {

    $this->start_controls_section(
      'contentproductstabgridkaveh',
      [
        'label' => esc_html__('Element Content', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );
    $repeater = new \Elementor\Repeater();
    $repeater->add_control(
      'tabtitle1productstabgridkaveh',
      [
        'label' => esc_html__('Tab Title', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::TEXT,
      ]
    );
    $repeater->add_control(
      'pproductstabgridkaveh',
      [
        'label' => esc_html__('Display Products', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT,
        'default' => 'all',
        'options' => [
          'all' => esc_html__('All', 'kavehTheme'),
          'cat' => esc_html__('Category', 'kavehTheme'),

        ],
      ]
    );
    $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(
      'kaveh_only_sales',
      [
        'label' => esc_html__('Show Only Sale Products', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SWITCHER,
        'yes' => esc_html__('Yes', 'kavehTheme'),
        'no' => esc_html__('No', 'kavehTheme'),
        'return_value' => 'yes',
        'default' => 'no',
      ]
    );
    $repeater->add_control(
      'psortproductstabgridkaveh',
      [
        '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 Volume', 'kavehTheme'),

        ],
      ]
    );
    $repeater->add_control(
      'psortiproductstabgridkaveh',
      [
        'label' => esc_html__('Sort Order', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT,
        'default' => 'desc',
        'options' => [
          'asc' => esc_html__('Ascending', 'kavehTheme'),
          'desc' => esc_html__('Descending', 'kavehTheme'),
        ],
      ]
    );
    $taboptiongrid = 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) {
      $taboptiongrid[$category->term_id] = $category->name;
    }
    $repeater->add_control(
      'cat2productstabgridkaveh',
      [
        'label' => esc_html__('Select Category', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => $taboptiongrid,
        'condition' => [
          'pproductstabgridkaveh' => 'cat',
        ],
      ]
    );
    $repeater->add_control(
      'productnumberproductstabgridkaveh',
      [
        'label' => esc_html__('Number of Products', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 0,
        'max' => 100,
        'step' => 1,
        'default' => 8,
      ]
    );
    $this->add_control(
      'listproductstabgridkaveh',
      [
        'label' => esc_html__('Tabs', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::REPEATER,
        'fields' => $repeater->get_controls(),
        'default' => [
          [
            'tabtitle1productstabgridkaveh' => esc_html__('Category', 'kavehTheme'),
          ],
        ],
      ]
    );

    $this->add_control(
      'styleproductstabgridkaveh',
      [
        'label' => esc_html__('Product Box Layout', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT,
        'default' => 'one',
        'options' => [
          'one'  => esc_html__( 'Layout One', 'kavehTheme' ),
          'two'  => esc_html__( 'Layout Two', 'kavehTheme' ),
          'three'  => esc_html__( 'Layout Three', 'kavehTheme' ),
          'four'  => esc_html__( 'Layout Four', 'kavehTheme' ),
          'five'  => esc_html__( 'Layout Five', 'kavehTheme' ),
          'six'  => esc_html__( 'Layout Six', 'kavehTheme' ),
          'seven'  => esc_html__( 'Layout Seven', 'kavehTheme' ),
          'eight'  => esc_html__( 'Layout Eight', 'kavehTheme' ),
          'nine'  => esc_html__( 'Layout Nine', 'kavehTheme' ),
          'ten'  => esc_html__( 'Layout Ten', 'kavehTheme' ),
          'eleven'  => esc_html__( 'Layout Eleven', 'kavehTheme' ),
          'twelve'  => esc_html__( 'Layout Twelve', 'kavehTheme' ),
          'thirteen'  => esc_html__( 'Layout Thirteen', 'kavehTheme' ),
          'fourteen'  => esc_html__( 'Layout Fourteen', 'kavehTheme' ),
          'fifteen'  => esc_html__( 'Layout Fifteen', 'kavehTheme' ),
          'sixteen'  => esc_html__( 'Layout Sixteen', 'kavehTheme' ),
          'seventeen'  => esc_html__( 'Layout Seventeen', 'kavehTheme' ),
          'eighteen'  => esc_html__( 'Layout Eighteen', 'kavehTheme' ),
          'nineteen'  => esc_html__( 'Layout Nineteen', 'kavehTheme' ),
          'twenty'  => esc_html__( 'Layout Twenty', 'kavehTheme' ),
          'twenty-one'  => esc_html__( 'Layout Twenty-One', 'kavehTheme' ),
          'twenty-two'  => esc_html__( 'Layout Twenty-Two', 'kavehTheme' ),
          'twenty-three'  => esc_html__( 'Layout Twenty-Three', 'kavehTheme' ),
          'twenty-four'  => esc_html__( 'Layout Twenty-Four', 'kavehTheme' ),
          'twenty-five'  => esc_html__( 'Layout Twenty-Five', 'kavehTheme' ),
          'twenty-six'  => esc_html__( 'Layout Twenty-Six', 'kavehTheme' ),
          'twenty-seven'  => esc_html__( 'Layout Twenty-Seven', 'kavehTheme' ),
          'twenty-eight'  => esc_html__( 'Layout Twenty-Eight', 'kavehTheme' ),
        ],
      ]
    );

    $this->end_controls_section();
    $this->start_controls_section(
      'style1_productstabgridkaveh',
      [
        'label' => esc_html__('Tabs Style', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_STYLE,
      ]
    );
    $this->add_control(
      'buttontextcolorproductstabgridkaveh',
      [
        'label' => esc_html__('Text Color', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link' => 'color: {{VALUE}}',

        ],
      ]
    );
    $this->add_group_control(
      \Elementor\Group_Control_Typography::get_type(),
      [
        'name' => 'buttonst3_productstabgridkaveh',
        'label' => esc_html__('Text Typography', 'kavehTheme'),
        'selector' => '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link',
      ]
    );
    $this->add_control(
      'buttoncoloractivest3productstabgridkaveh',
      [
        'label' => esc_html__('Active Tab Background Color', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link.active' => 'background-color: {{VALUE}}',
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link:hover' => 'background-color: {{VALUE}}',

        ],
      ]
    );
    $this->add_control(
      'buttontextactivecolorproductstabgridkaveh',
      [
        'label' => esc_html__('Active Text Color', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link.active' => 'color: {{VALUE}}',
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link:hover' => 'color: {{VALUE}}',


        ],
      ]
    );
    $this->add_control(
      'buttonpaddingproductstabgridkaveh',
      [
        'label' => esc_html__('Padding', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px'],
        'selectors' => [
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
      ]
    );
    $this->add_control(
      'buttonradius1productstabgridkaveh',
      [
        'label' => esc_html__('Border Radius', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px'],
        'selectors' => [
          '{{WRAPPER}} .top-products-three-tabs .nav-item .nav-link' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
      ]
    );

    $this->end_controls_section();

  }


  protected function render()
  {
    $settings = $this->get_settings_for_display();
    $clsid = $this->get_id();
    ?>
    <section class="top-products-three">
      <div class="container position-relative">
        <!-- Start Tabs -->
        <ul class="nav nav-tabs top-products-three-tabs d-flex align-items-center">
          <?php
          $q = 1;
          if ($settings['listproductstabgridkaveh']) {
            foreach ($settings['listproductstabgridkaveh'] as $item) {
              ?>
              <li class="nav-item">
                <a href="#pro-<?php echo $clsid . $q; ?>" class="nav-link <?php if (1 === $q) { ?>active <?php } else {
                     } ?>" data-bs-toggle="tab"> <?php echo esc_html($item['tabtitle1productstabgridkaveh']); ?> </a>
              </li>
              <?php
              $q++;
            }
          }
          ?>
        </ul>
        <!-- End Tabs -->
        <div class="tab-content">
          <?php
          $s = 1;
          if ($settings['listproductstabgridkaveh']) {
            foreach ($settings['listproductstabgridkaveh'] as $item) {
              ?>
              <div id="pro-<?php echo $clsid . $s; ?>" class="tab-pane fade <?php if (1 == $s) { ?>active show<?php } else {
                   } ?>">
                <!-- Start Products -->
                <div class="row row-mobile">
                  <?php
                  if ('cat' === $item['pproductstabgridkaveh']) {
                    $query_args = array(
                      'post_type' => array('product'),
'post_status' => array('publish'),
                      'posts_per_page' => $item['productnumberproductstabgridkaveh'],
                      'orderby' => $item['psortproductstabgridkaveh'] === 'date' ? 'date' : 'meta_value_num',
                      'order' => $item['psortiproductstabgridkaveh'],
                      'tax_query' => array(
                          'relation' => 'AND',
                          array(
                            'taxonomy' => 'product_cat',
                            'field' => 'term_id',
                            'terms' => $item['cat2productstabgridkaveh'],
                          ),
                      ),
                      'meta_query' => array(),  // Initialize meta_query to avoid undefined index error
                  );
                  
                  // Handle specific orderby values
                  switch ($item['psortproductstabgridkaveh']) {
                      case '_price':
                          $query_args['meta_key'] = '_price';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  
                      case '_wc_average_rating':
                          $query_args['meta_key'] = '_wc_average_rating';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  
                      case 'total_sales':
                          $query_args['meta_key'] = 'total_sales';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  }
                  
                  if ("yes" === $settings['kaveh_exclude_out_of_stock']) {
                      $query_args['tax_query'][] = array(
                          'taxonomy' => 'product_visibility',
                          'field' => 'name',
                          'terms' => array('outofstock'),
                          'operator' => 'NOT IN'
                      );
                  }
                  
                  if ("yes" === $settings['kaveh_only_sales']) {
                      $query_args['meta_query'][] = WC()->query->get_meta_query();  // Ensure meta_query is an array
                      $query_args['post__in'] = array_merge(array(0), wc_get_product_ids_on_sale());
                  }

                // Get the cached query results
                $cached_query = KavehCustomQuery::get_cached_query($query_args);
                if ($cached_query->have_posts()):
                  while ($cached_query->have_posts()):
                    $cached_query->the_post();
                    ?>
                    <div class="col-6 col-md-4 col-lg-3 tbgrid">
                      <?php $styleproduct21 = $settings['styleproductstabgridkaveh']; ?>
                      <?php get_template_part("template-part/product-cart-$styleproduct21"); ?>
                    </div>
                        <?php
                  endwhile;
                  wp_reset_postdata();
                else:
                  echo 'No posts found.';
                endif;
                ?>

                    <?php
                  } else {
                    $query_args = array(
                      'post_type' => array('product'),
'post_status' => array('publish'),
                      'posts_per_page' => $item['productnumberproductstabgridkaveh'],
                      'orderby' => $item['psortproductstabgridkaveh'] === 'date' ? 'date' : 'meta_value_num',
                      'order' => $item['psortiproductstabgridkaveh'],
                      'tax_query' => array(
                          'relation' => 'AND',
                      ),
                      'meta_query' => array(),  // Initialize meta_query to avoid undefined index error
                  );
                  
                  // Handle specific orderby values
                  switch ($item['psortproductstabgridkaveh']) {
                      case '_price':
                          $query_args['meta_key'] = '_price';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  
                      case '_wc_average_rating':
                          $query_args['meta_key'] = '_wc_average_rating';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  
                      case 'total_sales':
                          $query_args['meta_key'] = 'total_sales';
                          $query_args['orderby'] = 'meta_value_num';
                          break;
                  }
                  
                  if ("yes" === $settings['kaveh_exclude_out_of_stock']) {
                      $query_args['tax_query'][] = array(
                          'taxonomy' => 'product_visibility',
                          'field' => 'name',
                          'terms' => array('outofstock'),
                          'operator' => 'NOT IN'
                      );
                  }
                  
                  if ("yes" === $settings['kaveh_only_sales']) {
                      $query_args['meta_query'][] = WC()->query->get_meta_query();  // Ensure meta_query is an array
                      $query_args['post__in'] = array_merge(array(0), wc_get_product_ids_on_sale());
                  }

                // Get the cached query results
                $cached_query = KavehCustomQuery::get_cached_query($query_args);
                if ($cached_query->have_posts()):
                  while ($cached_query->have_posts()):
                    $cached_query->the_post();
                    ?>
                    <div class="col-6 col-md-4 col-lg-3 tbgrid">
                      <?php $styleproduct21 = $settings['styleproductstabgridkaveh']; ?>
                      <?php get_template_part("template-part/product-cart-$styleproduct21"); ?>
                    </div>
                        <?php
                  endwhile;
                  wp_reset_postdata();
                else:
                  echo 'No posts found.';
                endif;
                  }
                  ?>
                </div>
                <!-- End Products -->
              </div>
              <?php
              $s++;
            }
          }
          ?>
        </div>
      </div>
    </section>
    <style>
      .top-products-three-tabs .nav-item .nav-link {
        white-space: nowrap;
      }
    </style>
    <?php
  }


}
