<?php

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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


class Productsrandomofferstkaveh extends Widget_Base
{

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

  public function get_title()
  {
    return esc_html__('Instant Offer', 'kavehTheme');
  }

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

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

  protected function register_controls()
  {
    $this->start_controls_section(
      'content00productsrandomofferstkaveh',
      [
        'label' => esc_html__('Instant Discount Products Settings', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );
    $this->add_control(
      'pproductslahzeproductsrandomofferstkaveh',
      [
        '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(
      'psortproductslahzeproductsrandomofferstkaveh',
      [
        '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'),

        ],
      ]
    );
    $this->add_control(
      'psortiproductslahzeproductsrandomofferstkaveh',
      [
        '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(
      'catproductslahzeproductsrandomofferstkaveh',
      [
        'label' => esc_html__('Select Category', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => $options2,
        'condition' => [
          'pproductslahzeproductsrandomofferstkaveh' => 'cat',
        ],
      ]
    );
    $this->add_control(
      'productnumberproductsproductsrandomofferstkaveh',
      [
        'label' => esc_html__('Number of Products Displayed', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 0,
        'max' => 50,
        'step' => 1,
        'default' => 5,
      ]
    );
    $this->end_controls_section();
    $this->start_controls_section(
      'content3productsrandomofferstkaveh',
      [
        'label' => esc_html__('Carousel Settings', 'kavehTheme'),
        'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
      ]
    );
    $this->add_control(
      'productcolumnproductsrandomofferstkaveh',
      [
        'label' => esc_html__('Number of Category Columns on Desktop', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 0,
        'max' => 8,
        'step' => 1,
        'default' => 4,

      ]
    );
    $this->add_control(
      'productcolumn2productsrandomofferstkaveh',
      [
        'label' => esc_html__('Number of Category Columns on Tablet', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 0,
        'max' => 5,
        'step' => 1,
        'default' => 3,

      ]
    );
    $this->add_control(
      'productcolumn3productsrandomofferstkaveh',
      [
        'label' => esc_html__('Number of Category Columns on Mobile', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::NUMBER,
        'min' => 0,
        'max' => 5,
        'step' => .5,
        'default' => 1.5,

      ]
    );
    $this->end_controls_section();


  }


  protected function render()
  {
    $settings = $this->get_settings_for_display();
    $clsid = $this->get_id();
    $woo_currency = get_woocommerce_currency_symbol();

    ?>
    <div class="rand-offer">
      <!-- Start Carousel -->
      <div class="swiper swiper-discount-product-special position-relative">
        <div class="swiper-wrapper">
          <?php if ('cat' === $settings['pproductslahzeproductsrandomofferstkaveh']) { ?>
            <?php
            // Define your custom query arguments
            $query_args = array(
              'post_type' => 'product',
              'posts_per_page' => $settings['productnumberproductsproductsrandomofferstkaveh'],
              'orderby' => $settings['psortproductslahzeproductsrandomofferstkaveh'] === 'date' ? 'date' : 'meta_value_num', // Default to date or meta value
              'order' => $settings['psortiproductslahzeproductsrandomofferstkaveh'],
              'tax_query' => array(
                'relation' => 'AND',
                array(
                  'taxonomy' => 'product_cat',
                  'field' => 'term_id',
                  'terms' => $settings['catproductslahzeproductsrandomofferstkaveh'],
                ),
              ),
            );
            // Handle specific orderby values
            switch ($settings['psortproductslahzeproductsrandomofferstkaveh']) {
              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;
            }

            // 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();
                $post_id = get_the_ID();
                $product = wc_get_product($post_id);
                ?>
                <!-- Start Slide -->
                <div class="swiper-slide">
                  <div class="product-eight product-eight-offer">
                    <div class="image">
                      <a href="<?php the_permalink(); ?>">
                        <img src="<?php if (get_the_post_thumbnail_url()): ?>
                        <?php the_post_thumbnail_url('full'); ?>
                        <?php else: ?>
                        <?php echo wc_placeholder_img_src(); ?>
                        <?php endif; ?>" alt="<?php the_title(); ?>" width="266" height="266">
                      </a>
                      <?php if (!$product->get_stock_status() === 'outofstock'):
                        if ($product->is_on_sale()): ?>
                          <div class="offer">
                            <?php if ($product->is_type('variable')): ?>
                              <?php echo (int) ((((float) $product->get_variation_regular_price('min') - (float) $product->get_variation_sale_price('min')) / (float) $product->get_variation_regular_price('min')) * 100); ?>                <?php echo ' ' . '%'; ?>
                            <?php elseif ($product->is_type('simple')): ?>
                              <?php echo (int) ((((float) $product->get_regular_price() - (float) $product->get_sale_price()) / (float) $product->get_regular_price()) * 100); ?>                <?php echo ' ' . '%'; ?>
                            <?php endif; ?>
                          </div>
                        <?php endif; ?>
                      <?php endif; ?>
                    </div>
                    <div class="content">
                      <ul class="tags d-flex align-items-center flex-wrap">
                      </ul>
                      <h2 class="product-name">
                        <a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a>
                      </h2>
                      <div class="d-flex align-items-center justify-content-between">
                        <?php if (!$product->is_type('variable')): ?>
                          <?php if (!empty($product->get_sale_price())) { ?>
                            <div class="price">
                              <del> <?php if (!empty($product->get_regular_price())): ?>
                                  <?php echo number_format($product->get_regular_price(), 0, '.', ','); ?>
                                <?php endif; ?></del>
                              <span> <?php if (!empty($product->get_sale_price())): ?>
                                  <?php echo number_format($product->get_sale_price(), 0, '.', ','); ?>
                                <?php endif; ?> </span>
                              <?php echo $woo_currency; ?>
                            </div>
                          <?php } else { ?>
                            <div class="price">
                              <span> <?php if (!empty($product->get_regular_price())): ?>
                                  <?php echo number_format($product->get_regular_price(), 0, '.', ','); ?>
                                <?php endif; ?></span>
                              <?php echo $woo_currency; ?>
                            </div>
                          <?php } ?>
                        <?php else: ?>
                          <div class="price">
                            <?php echo $product->get_price_html(); ?>
                          </div>
                        <?php endif; ?>
                        <?php if (!$product->is_type('variable')) { ?>
                          <a type="submit" name="add-to-cart" value="<?php echo $post_id; ?>"
                            class="btn btn-success-2 shadow-none single_add_to_cart_button"><span> + Buy </span></a>
                        <?php } else { ?>
                        <?php } ?>
                      </div>
                      <a href="<?php the_permalink(); ?>" class="btn btn-secondary rounded-pill"> <?php esc_html_e( 'View Product', 'kavehTheme'); ?> </a>
                    </div>
                  </div>
                </div>
                <!-- End Slide -->
                <?php
              endwhile;
              wp_reset_postdata();
            else:
              echo 'No posts found.';
            endif;
            ?>
          <?php } elseif ('all' === $settings['pproductslahzeproductsrandomofferstkaveh']) {
            ?>
            <?php
            // Define your custom query arguments
            $query_args = array(
              'post_type' => 'product',
              'posts_per_page' => $settings['productnumberproductsproductsrandomofferstkaveh'],
              'orderby' => $settings['psortproductslahzeproductsrandomofferstkaveh'] === 'date' ? 'date' : 'meta_value_num', // Default to date or meta value
              'order' => $settings['psortiproductslahzeproductsrandomofferstkaveh'],
              'tax_query' => array(
                'relation' => 'AND',
              ),
            );
            // Handle specific orderby values
            switch ($settings['psortproductslahzeproductsrandomofferstkaveh']) {
              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;
            }

            // 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();
                $post_id = get_the_ID();
                $product = wc_get_product($post_id);
                ?>
                <!-- Start Slide -->
                <div class="swiper-slide">
                  <div class="product-eight product-eight-offer">
                    <div class="image">
                      <a href="<?php the_permalink(); ?>">
                        <img src="<?php if (get_the_post_thumbnail_url()): ?>
                        <?php the_post_thumbnail_url('full'); ?>
                        <?php else: ?>
                        <?php echo wc_placeholder_img_src(); ?>
                        <?php endif; ?>" alt="<?php the_title(); ?>" width="266" height="266">
                      </a>
                      <?php if (!$product->get_stock_status() === 'outofstock'):
                        if ($product->is_on_sale()): ?>
                          <div class="offer">
                            <?php if ($product->is_type('variable')): ?>
                              <?php echo (int) ((((float) $product->get_variation_regular_price('min') - (float) $product->get_variation_sale_price('min')) / (float) $product->get_variation_regular_price('min')) * 100); ?>                <?php echo ' ' . '%'; ?>
                            <?php elseif ($product->is_type('simple')): ?>
                              <?php echo (int) ((((float) $product->get_regular_price() - (float) $product->get_sale_price()) / (float) $product->get_regular_price()) * 100); ?>                <?php echo ' ' . '%'; ?>
                            <?php endif; ?>
                          </div>
                        <?php endif; ?>
                      <?php endif; ?>
                    </div>
                    <div class="content">
                      <ul class="tags d-flex align-items-center flex-wrap">
                      </ul>
                      <h2 class="product-name">
                        <a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a>
                      </h2>
                      <div class="d-flex align-items-center justify-content-between">
                        <?php if (!$product->is_type('variable')): ?>
                          <?php if (!empty($product->get_sale_price())) { ?>
                            <div class="price">
                              <del> <?php if (!empty($product->get_regular_price())): ?>
                                  <?php echo number_format($product->get_regular_price(), 0, '.', ','); ?>
                                <?php endif; ?></del>
                              <span> <?php if (!empty($product->get_sale_price())): ?>
                                  <?php echo number_format($product->get_sale_price(), 0, '.', ','); ?>
                                <?php endif; ?> </span>
                              <?php echo $woo_currency; ?>
                            </div>
                          <?php } else { ?>
                            <div class="price">
                              <span> <?php if (!empty($product->get_regular_price())): ?>
                                  <?php echo number_format($product->get_regular_price(), 0, '.', ','); ?>
                                <?php endif; ?></span>
                              <?php echo $woo_currency; ?>
                            </div>
                          <?php } ?>
                        <?php else: ?>
                          <div class="price">
                            <?php echo $product->get_price_html(); ?>
                          </div>
                        <?php endif; ?>
                        <?php if (!$product->is_type('variable')) { ?>
                          <a type="submit" name="add-to-cart" value="<?php echo $post_id; ?>"
                            class="btn btn-success-2 shadow-none single_add_to_cart_button"><span> + Buy </span></a>
                        <?php } else { ?>
                        <?php } ?>
                      </div>
                      <a href="<?php the_permalink(); ?>" class="btn btn-secondary rounded-pill"> <?php esc_html_e( 'View Product', 'kavehTheme'); ?> </a>
                    </div>
                  </div>
                </div>
                <!-- End Slide -->
                <?php
              endwhile;
              wp_reset_postdata();
            else:
              echo 'No posts found.';
            endif;
            ?>
          <?php } ?>
        </div>
        <!-- Start Pagination -->
        <div class="swiper-pagination end-0"></div>
        <!-- End Pagination -->
      </div>
      <style>
        .rand-offer {
          max-width: 315px !important;
        }

        .product-eight .image img {
          width: 187px;
          margin-right: auto;
          margin-left: auto;
        }

        .product-eight .image:not(.full-width) {
          min-height: 268px;
        }
      </style>

      <?php
  }


}
