<?php

class kavehAjaxes
{
  private $options;

  public function __construct()
  {
    $this->options = kaveh_get_options();

    add_action('wp_ajax_kaveh_ajax_update_cart_kk_remove', [$this, 'kaveh_ajax_update_cart_kk_remove']);
    add_action('wp_ajax_nopriv_kaveh_ajax_update_cart_kk_remove', [$this, 'kaveh_ajax_update_cart_kk_remove']);

    add_action('wp_ajax_kaveh_ajax_remove_cart_item', [$this, 'kaveh_ajax_remove_cart_item']);
    add_action('wp_ajax_nopriv_kaveh_ajax_remove_cart_item', [$this, 'kaveh_ajax_remove_cart_item']);

    add_action('wp_ajax_kaveh_ajax_update_cart_kk', [$this, 'kaveh_ajax_update_cart_kk']);
    add_action('wp_ajax_nopriv_kaveh_ajax_update_cart_kk', [$this, 'kaveh_ajax_update_cart_kk']);

    add_action('wp_ajax_kaveh_product_search', [$this, 'kaveh_product_search']);
    add_action('wp_ajax_nopriv_kaveh_product_search', [$this, 'kaveh_product_search']);

    add_action('wp_ajax_kaveh_quick_view', [$this, 'kaveh_quick_view']);
    add_action('wp_ajax_nopriv_kaveh_quick_view', [$this, 'kaveh_quick_view']);

    add_action('wp_ajax_kaveh_shop_filters', [$this, 'kaveh_shop_filters']);
    add_action('wp_ajax_nopriv_kaveh_shop_filters', [$this, 'kaveh_shop_filters']);

    add_action('wp_ajax_kaveh_ajax_add_to_cart', [$this, 'kaveh_ajax_add_to_cart']);
    add_action('wp_ajax_nopriv_kaveh_ajax_add_to_cart', [$this, 'kaveh_ajax_add_to_cart']);
    
    // Clear filter cache when products are updated
    add_action('save_post', [$this, 'clear_filter_cache']);
    add_action('woocommerce_product_set_stock_status', [$this, 'clear_filter_cache']);
    add_action('woocommerce_variation_set_stock_status', [$this, 'clear_filter_cache']);
  }
  
  /**
   * Clear filter cache when products are updated
   */
  public function clear_filter_cache($post_id = null) {
    // Only clear cache for product posts
    if ($post_id && get_post_type($post_id) !== 'product') {
      return;
    }
    
    // Delete all filter cache transients
    global $wpdb;
    $wpdb->query(
      "DELETE FROM {$wpdb->options} 
       WHERE option_name LIKE '_transient_kaveh_shop_filter_%' 
       OR option_name LIKE '_transient_timeout_kaveh_shop_filter_%'"
    );
  }

  public function kaveh_product_search()
  {
    $search_query = sanitize_text_field($_POST['search']);
    $args = array(
      'post_type' => 'product',
      'post_status' => 'publish',
      'posts_per_page' => 8,
      's' => $search_query,
      'orderby' => 'relevance',
      'tax_query' => array(
        array(
          'taxonomy' => 'product_visibility',
          'field' => 'name',
          'terms' => 'exclude-from-search',
          'operator' => 'NOT IN',
        ),
      ),
    );

    $query = new WP_Query($args);
    $results = array();

    if ($query->have_posts()) {
      while ($query->have_posts()) {
        $query->the_post();
        $product = wc_get_product(get_the_ID());

        if (!$product) {
          continue;
        }

        $categories = get_the_terms(get_the_ID(), 'product_cat');
        $category = array();
        if ($categories && !is_wp_error($categories)) {
          $category = array(
            'name' => $categories[0]->name,
            'slug' => $categories[0]->slug,
            'link' => get_term_link($categories[0]->term_id, 'product_cat')
          );
        }

        $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'woocommerce_thumbnail');
        if (!$thumbnail_url) {
          $thumbnail_url = wc_placeholder_img_src();
        }

        $results[] = array(
          'id' => $product->get_id(),
          'name' => $product->get_name(),
          'permalink' => get_permalink(),
          'price_html' => $product->get_price_html(),
          'thumbnail' => $thumbnail_url,
          'category' => $category,
          'sku' => $product->get_sku(),
          'stock' => $product->is_in_stock(),
          'on_sale' => $product->is_on_sale()
        );
      }
    }

    wp_reset_postdata();
    wp_send_json(array(
      'success' => true,
      'data' => $results
    ));
    die();
  }

  public function kaveh_ajax_update_cart_kk_remove()
  {
    if (isset($_POST['cart_item_key']) && isset($_POST['quantity'])) {
      $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
      $quantity = intval($_POST['quantity']);
      WC()->cart->set_quantity($cart_item_key, $quantity, true);
      WC()->cart->calculate_totals();
      WC()->cart->maybe_set_cart_cookies();
      $fragments = WC_AJAX::get_refreshed_fragments();
      wp_send_json_success(array(
        'fragments' => $fragments
      ));
    }
    wp_send_json_error(__('Invalid request.', 'kavehTheme'));
    die();
  }

  public function kaveh_ajax_update_cart_kk()
  {
    if (isset($_POST['cart_item_key']) && isset($_POST['quantity'])) {
      $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
      $quantity = intval($_POST['quantity']);
      WC()->cart->set_quantity($cart_item_key, $quantity, true);
      WC()->cart->calculate_totals();
      WC()->cart->maybe_set_cart_cookies();
      $fragments = WC_AJAX::get_refreshed_fragments();
      wp_send_json_success(array(
        'fragments' => $fragments
      ));
    }
    wp_send_json_error(__('Invalid request.', 'kavehTheme'));
    die();
  }

  public function kaveh_shop_filters()
  {
    // Validate request method
    if (!wp_doing_ajax() || empty($_POST)) {
      wp_send_json_error('Invalid request method.');
      return;
    }

    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'kaveh_shop_filter_nonce')) {
      wp_send_json_error('Security check failed.');
      return;
    }

    // Sanitize and validate inputs
    $paged = isset($_POST['page']) ? absint($_POST['page']) : 1;
    if ($paged < 1) {
      $paged = 1;
    }

    $sortt = isset($_POST['sortt']) ? sanitize_text_field($_POST['sortt']) : 'sort-1';
    $onsalee = isset($_POST['onsalee']) ? sanitize_text_field($_POST['onsalee']) : 'false';
    $onstock = isset($_POST['onstock']) ? sanitize_text_field($_POST['onstock']) : 'false';
    
    // Sanitize category IDs
    $catIdss = isset($_POST['catIds']) ? $_POST['catIds'] : array();
    if (is_string($catIdss)) {
      $catIdss = explode(',', $catIdss);
    }
    $catIdss = array_map('absint', array_filter($catIdss));
    
    // Sanitize brand IDs
    $brandIds = isset($_POST['brandIds']) ? $_POST['brandIds'] : array();
    if (is_string($brandIds)) {
      $brandIds = explode(',', $brandIds);
    }
    $brandIds = array_map('absint', array_filter($brandIds));
    
    $counttax = isset($_POST['count']) ? absint($_POST['count']) : 0;
    
    // Handle attribute data
    $attrId = array();
    $taxIds = array();
    if (isset($_POST['attrId']) && isset($_POST['taxIds'])) {
      $serializedAttrId = stripslashes(sanitize_text_field($_POST['attrId']));
      $serializedTaxIds = stripslashes(sanitize_text_field($_POST['taxIds']));
      $attrId = json_decode($serializedAttrId, true);
      $taxIds = json_decode($serializedTaxIds, true);
      
      // Validate JSON decode
      if (json_last_error() !== JSON_ERROR_NONE) {
        $attrId = array();
        $taxIds = array();
      }
    }
    
    // Sanitize price range
    $pricemin = isset($_POST['pricemin']) ? floatval($_POST['pricemin']) : 0;
    $pricemax = isset($_POST['pricemax']) ? floatval($_POST['pricemax']) : 999999999;
    
    // Validate price range
    if ($pricemin < 0) $pricemin = 0;
    if ($pricemax < 0) $pricemax = 999999999;
    if ($pricemin > $pricemax) {
      $temp = $pricemin;
      $pricemin = $pricemax;
      $pricemax = $temp;
    }

    try {
      // Create cache key for this specific filter combination
      $cache_key = 'kaveh_shop_filter_' . md5(serialize(array(
        'catIds' => $catIdss,
        'brandIds' => $brandIds,
        'attrId' => $attrId,
        'taxIds' => $taxIds,
        'pricemin' => $pricemin,
        'pricemax' => $pricemax,
        'onsalee' => $onsalee,
        'onstock' => $onstock,
        'sortt' => $sortt,
        'paged' => $paged
      )));
      
      // Try to get cached result (cache for 5 minutes)
      $cached_result = get_transient($cache_key);
      if ($cached_result !== false && !WP_DEBUG) {
        wp_send_json_success(array('html' => $cached_result));
        return;
      }
      
      // Use WooCommerce standard query building
      $query_args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'posts_per_page' => 9,
        'paged' => $paged,
        'meta_query' => array('relation' => 'AND'),
        'tax_query' => array('relation' => 'AND'),
        'no_found_rows' => false, // We need pagination
        'update_post_meta_cache' => false, // Don't cache meta for performance
        'update_post_term_cache' => false, // Don't cache terms for performance
      );

      // Add WooCommerce default meta queries
      $query_args['meta_query'] = array_merge(
        $query_args['meta_query'],
        WC()->query->get_meta_query()
      );

      // Handle price filtering using WooCommerce method
      if ($pricemin > 0 || $pricemax < 999999999) {
        $query_args['meta_query'][] = array(
          'key' => '_price',
          'value' => array($pricemin, $pricemax),
          'compare' => 'BETWEEN',
          'type' => 'NUMERIC',
        );
      }

      // Handle stock status
      if ($onstock === 'true') {
        $query_args['meta_query'][] = array(
          'key' => '_stock_status',
          'value' => 'instock',
          'compare' => '=',
        );
      }

      // Handle sale products
      if ($onsalee === 'true') {
        $sale_product_ids = wc_get_product_ids_on_sale();
        if (!empty($sale_product_ids)) {
          $query_args['post__in'] = $sale_product_ids;
        } else {
          $query_args['post__in'] = array(0); // No sale products
        }
      }

      // Add WooCommerce default tax queries
      $query_args['tax_query'] = array_merge(
        $query_args['tax_query'],
        WC()->query->get_tax_query()
      );

      // Handle category filtering
      if (!empty($catIdss) && is_array($catIdss)) {
        $query_args['tax_query'][] = array(
          'taxonomy' => 'product_cat',
          'field' => 'term_id',
          'terms' => $catIdss,
          'operator' => 'IN',
        );
      }

      // Handle brand filtering
      if (!empty($brandIds) && is_array($brandIds)) {
        $query_args['tax_query'][] = array(
          'taxonomy' => 'brands',
          'field' => 'term_id',
          'terms' => $brandIds,
          'operator' => 'IN',
        );
      }

      // Handle attribute filtering
      if (!empty($taxIds) && is_array($taxIds) && !empty($attrId) && is_array($attrId)) {
        $in = 0;
        foreach ($taxIds as $taxId) {
          if (isset($attrId[$in]) && !empty($taxId) && is_array($taxId)) {
            $filtered_terms = array_filter(array_map('sanitize_text_field', $taxId));
            if (!empty($filtered_terms)) {
              $query_args['tax_query'][] = array(
                'taxonomy' => sanitize_text_field($attrId[$in]),
                'field' => 'slug',
                'terms' => $filtered_terms,
                'operator' => 'IN',
              );
            }
          }
          $in++;
        }
      }

      // Handle sorting using WooCommerce standards
      switch ($sortt) {
        case 'sort-2': // Newest
          $query_args['orderby'] = 'date';
          $query_args['order'] = 'DESC';
          break;
        case 'sort-3': // Cheapest
          $query_args['meta_key'] = '_price';
          $query_args['orderby'] = 'meta_value_num';
          $query_args['order'] = 'ASC';
          break;
        case 'sort-4': // Most expensive
          $query_args['meta_key'] = '_price';
          $query_args['orderby'] = 'meta_value_num';
          $query_args['order'] = 'DESC';
          break;
        case 'sort-5': // Best selling
          $query_args['meta_key'] = 'total_sales';
          $query_args['orderby'] = 'meta_value_num';
          $query_args['order'] = 'DESC';
          break;
        default: // Default to newest
          $query_args['orderby'] = 'date';
          $query_args['order'] = 'DESC';
          break;
      }

      // Apply WooCommerce product visibility
      $product_visibility_terms = wc_get_product_visibility_term_ids();
      if (!empty($product_visibility_terms['exclude-from-catalog'])) {
        $query_args['tax_query'][] = array(
          'taxonomy' => 'product_visibility',
          'field' => 'term_taxonomy_id',
          'terms' => $product_visibility_terms['exclude-from-catalog'],
          'operator' => 'NOT IN',
        );
      }

      // Handle out-of-stock products ordering if option is enabled
      $options = kaveh_get_options();
      if (isset($options['move_outofstock_to_end']) && $options['move_outofstock_to_end'] === '1') {
        // Use a temporary filter to modify the query clauses for stock ordering
        add_filter('posts_clauses', function($posts_clauses) use ($query_args) {
          global $wpdb;
          
          // Only apply to our specific query by checking if we're in the right context
          if (wp_doing_ajax() && isset($_POST['action']) && $_POST['action'] === 'kaveh_shop_filters') {
            $posts_clauses['join'] .= " LEFT JOIN $wpdb->postmeta AS stock_meta ON ($wpdb->posts.ID = stock_meta.post_id AND stock_meta.meta_key = '_stock_status') ";
            
            // Get the original orderby
            $original_orderby = $posts_clauses['orderby'];
            
            // Modify orderby to prioritize stock status (instock first, then outofstock)
            $posts_clauses['orderby'] = "CASE WHEN stock_meta.meta_value = 'instock' THEN 0 WHEN stock_meta.meta_value = 'onbackorder' THEN 1 ELSE 2 END, " . $original_orderby;
          }
          
          return $posts_clauses;
        }, 2000);
      }

      // Execute query
      $products = new WP_Query($query_args);
      
      // Remove the stock ordering filter after query execution to prevent affecting other queries
      if (isset($options['move_outofstock_to_end']) && $options['move_outofstock_to_end'] === '1') {
        remove_all_filters('posts_clauses', 2000);
      }
      
      if ($products->have_posts()) {
        ob_start();
        
        // Use WooCommerce hooks
        do_action('woocommerce_before_shop_loop');
        woocommerce_product_loop_start();

        while ($products->have_posts()) {
          $products->the_post();
          do_action('woocommerce_shop_loop');
          wc_get_template_part('content', 'product');
        }
        
        woocommerce_product_loop_end();
        do_action('woocommerce_after_shop_loop');
        
        // Handle pagination
        $total_pages = $products->max_num_pages;
        if ($total_pages > 1) {
          // Get current page URL for proper pagination
          $current_url = home_url(add_query_arg(array(), $GLOBALS['wp']->request));
          if (is_shop()) {
            $base_url = get_permalink(wc_get_page_id('shop'));
          } elseif (is_product_category()) {
            $base_url = get_term_link(get_queried_object());
          } elseif (is_tax('brands')) {
            $base_url = get_term_link(get_queried_object());
          } else {
            $base_url = $current_url;
          }
          
          echo '<div class="pg1 d-block mx-auto text-center">';
          echo paginate_links(array(
            'base' => add_query_arg('page', '%#%', $base_url),
            'format' => '',
            'current' => $paged,
            'total' => $total_pages,
            'prev_text' => '&laquo;',
            'next_text' => '&raquo;',
            'type' => 'plain',
            'end_size' => 2,
            'mid_size' => 1,
          ));
          echo '</div>';
        }
        
        $output = ob_get_clean();
        
        // Cache the result for 5 minutes (300 seconds)
        set_transient($cache_key, $output, 300);
        
        wp_send_json_success(array('html' => $output));
      } else {
        $no_products_html = '<div class="no-products-found">';
        $no_products_html .= '<p>' . esc_html__('No products found matching your criteria.', 'kavehTheme') . '</p>';
        $no_products_html .= '</div>';
        wp_send_json_success(array('html' => $no_products_html));
      }
    } catch (Exception $e) {
      error_log('Kaveh Shop Filter Error: ' . $e->getMessage());
      wp_send_json_error(array(
        'message' => __('An error occurred while filtering products. Please try again.', 'kavehTheme'),
        'error' => $e->getMessage()
      ));
    } finally {
      wp_reset_postdata();
    }
  }

  public function kaveh_ajax_remove_cart_item()
  {
    $cart_item_key = $_POST['product_id'];
    $cart = WC()->cart;
    $cart->remove_cart_item($cart_item_key);
    ob_start();
    ?>
    <ul class="tot-aj-cc">
      <?php
      if (WC()->cart->get_cart_contents_count() == 0) {
        ?>
        <div class="align-items-center">
          <img class="mx-auto w-50 d-block text-center position-relative mn-r"
            src="<?php echo KAVEH_TEMPLATE_URI . '/assets/images/emptybag.png'; ?>" alt="<?php esc_attr_e('empty cart', 'kavehTheme'); ?>">
          <h6 class="text-center position-relative mn-r"><?php _e('No products in the cart', 'kavehTheme'); ?></h6>
        </div>
        <?php
      }
      ?>
      <?php
      foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];
        $product_id = $cart_item['product_id'];
        $variation_id = $cart_item['variation_id'];
        $quantity = $cart_item['quantity'];
        $price = WC()->cart->get_product_price($product);
        $subtotal = WC()->cart->get_product_subtotal($product, $cart_item['quantity']);
        $link = $product->get_permalink($cart_item);
        $meta = wc_get_formatted_cart_item_data($cart_item);
        $sale_price = $product->get_sale_price();
        $normal_price = $product->get_regular_price();
        ?>
        <li class="position-relative">
          <a href="<?php echo wc_get_cart_remove_url($cart_item_key); ?>" type="button"
            class="delete position-absolute text-center rounded-pill fw-light remove"
            data-cart-item-key="<?php echo esc_attr($cart_item_key); ?>" aria-label="<?php esc_attr_e('Remove this item', 'kavehTheme'); ?>" data-product_id="<?php if ($variation_id == 0):
                 echo $product_id;
               else:
                 echo $variation_id;
               endif; ?>"> <?php _e('Remove', 'kavehTheme'); ?> </a>
          <img src="<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'thumbnail');
          echo $image[0]; ?>" alt="<?php esc_attr_e('product', 'kavehTheme'); ?>" />
          <div class="detail">
            <h2>
              <a href="javascript:void(0)"> <?php echo $product->name; ?> </a>
            </h2>
            <?php if (!$product->is_type('variable')) { ?>
              <?php if (!empty($sale_price)) { ?>
                <div class="offer">
                  <?php echo number_format($normal_price, 0, '.', ','); ?>
                </div>
              <?php } ?>
              <div class="price">
                <?php echo number_format($sale_price, 0, '.', ','); ?>
                <span> <?php echo get_woocommerce_currency_symbol(); ?> </span>
              </div>
            <?php } else {
              $price_v = $product->get_price_html();
              echo str_replace("&ndash;", "<span class=\"dashvar\"> – </span>", $price_v);
            } ?>
          </div>
        </li>
        <?php
      }
      ?>
    </ul>
    <?php
    $conttent = ob_get_clean();
    $response = array(
      'result' => 'success',
      'cart_count' => WC()->cart->get_cart_contents_count(),
      'cart_total' => WC()->cart->total,
      'cart_contents' => $conttent,
    );

    wp_send_json($response);
    die();
  }

  public function kaveh_quick_view()
  {
    $idofpost = $_POST['postid'];
    global $product;
    $product = wc_get_product($idofpost);
    $sale_price = $product->get_sale_price();
    $normal_price = $product->get_regular_price();
    $stocka = $product->get_stock_status();
    $product_type = $product->get_type();
    $sale_price_dates_from = $sale_price_dates_to = '';
    ?>
    <div class="modal-body position-relative d-flex flex-column flex-lg-row overflow-hidden hideme">
      <div class="icons d-flex align-items-center position-absolute">
        <button type="button" class="d-flex align-items-center justify-content-center" data-bs-dismiss="modal">
          <i class="isax isax-close-square5"></i>
        </button>
      </div>
      <div class="right">
        <div class="gallery position-relative">
          <?php if ("instock" == $stocka) {
            if (!empty($sale_price)) { ?>
              <div class="offer position-absolute">
                <?php 
                /* translators: %s: discount percentage */
                printf(
                  __('Discount %s%%', 'kavehTheme'),
                  round((($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100)
                );
                ?>
              </div>
            <?php }
          } ?>
          <div class="d-flex position-relative">
            <div class="swiper swiper-modal-product overflow-hidden">
              <div class="swiper-wrapper">
                <?php
                $attachment_ids = $product->get_gallery_image_ids();
                if ($attachment_ids && $product->get_image_id()) {
                  $cou = 0;
                  foreach ($attachment_ids as $attachment_id) {
                    if ($cou < 4) {
                      ?>
                      <div class="swiper-slide">
                        <div class="gallery-item">
                          <img src="<?php echo wp_get_attachment_image_url($attachment_id, 'full'); ?>" class="w-100 d-block"
                            data-gallery="gallery-origin<?php echo $idofpost; ?>">
                        </div>
                      </div>
                      <?php
                      $cou += 1;
                    }
                  }
                }
                ?>
              </div>
            </div>
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
            <div class="gallery-origin">
              <img src="<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($idofpost), 'full');
              echo $image[0]; ?>" id="gallery-origin<?php echo $idofpost; ?>" class="w-100 d-block">
            </div>
          </div>
          <button type="button">
          </button>
        </div>
        <a href="<?php echo get_permalink($idofpost); ?>" class="btn-view btn btn-primary d-none d-lg-inline-block">
          <?php _e('More product details', 'kavehTheme'); ?>
          <i class="isax isax-arrow-left5"></i>
        </a>
      </div>
      <div class="left w-100">
        <h2 class="name"> <?php echo $product->get_title(); ?> </h2>
        <br>
        <?php
        if ("instock" == $stocka) {
          if ($date_from = get_post_meta($product->get_id(), '_sale_price_dates_from', true)) {
            $sale_price_dates_from = date('Y-m-d 00:00:00', $date_from);
          }
          if ($date_to = get_post_meta($product->get_id(), '_sale_price_dates_to', true)) {
            $sale_price_dates_to = date('Y-m-d 23:59:59', $date_to);
          }
          $deal_start_date = $sale_price_dates_from;
          $deal_start_time = strtotime($deal_start_date);
          $deal_end_date = $sale_price_dates_to;
          $deal_end_time = strtotime($deal_end_date, current_time('timestamp'));
          $current_time = strtotime('NOW', current_time('timestamp'));
          $time_diff = ($deal_end_time - $current_time); ?>
          <?php if (!empty($deal_end_date)) { ?>
            <ul class="timear d-flex align-items-center" data-time="<?php echo $deal_end_date; ?>">
              <li class="text-center">
                <span class="second d-block rounded-circle text-center text-white"> 00 </span>
                <?php _e('Seconds', 'kavehTheme'); ?>
              </li>
              <li class="text-center">
                <span class="minute d-block rounded-circle text-center text-white"> 00 </span>
                <?php _e('Minutes', 'kavehTheme'); ?>
              </li>
              <li class="text-center">
                <span class="hour d-block rounded-circle text-center text-white"> 00 </span>
                <?php _e('Hours', 'kavehTheme'); ?>
              </li>
              <li class="text-center">
                <span class="day d-block rounded-circle text-center text-white"> 00 </span>
                <?php _e('Days', 'kavehTheme'); ?>
              </li>
            </ul>
          <?php }
        } ?>
        <div class="row align-items-center">
          <div class="col-sm-6">
            <!-- Start Status -->
            <div class="status d-flex align-items-center">
              <span class="label fw-bold"> <?php _e('Status', 'kavehTheme'); ?> </span>
              <?php if ("instock" == $stocka): ?>
                <div class="badge rounded-pill fw-light"> <?php _e('In stock', 'kavehTheme'); ?> </div>
              <?php elseif ("onbackorder" == $stocka): ?>
                <div class="badge rounded-pill fw-light obstock"> <?php _e('On pre-order', 'kavehTheme'); ?> </div>
              <?php else: ?>
                <div class="badge rounded-pill fw-light oustock namo"> <?php _e('Out of stock', 'kavehTheme'); ?> </div>
              <?php endif; ?>
            </div>
            <br>
            <?php echo wp_trim_words($product->get_short_description(), 64); ?>
            <!-- End Status -->
            <div class="woocommerce mt-4">
              <?php
              if ($product->is_type('variable')) {
                ?>
                <a class="modaladdto" href="<?php echo get_permalink($idofpost); ?>"><?php _e('Select options', 'kavehTheme'); ?></a>
                <?php
              } else {
                woocommerce_template_single_add_to_cart();
              }
              ?>
            </div>
          </div>
          <div class="col-sm-6">
            <?php
            $i = 0;
            $product_attributes = $product->get_attributes();
            if (!empty($product_attributes)):
              ?>
              <div class="options">
                <div class="title"> <?php _e('Product features', 'kavehTheme'); ?> </div>
                <?php
                foreach ($product_attributes as $attribute):
                  $attribute_slug = $attribute->get_name();
                  if ($i < 6):
                    ?>
                    <ul>
                      <li>
					            <?php echo wc_attribute_label( $attribute_slug ) ?> : <span dir="ltr" style="display: inline-block;"><?php echo $product->get_attribute( $attribute_slug ) ?></span>
                      </li>
                    </ul>
                    <?php
                    $i++;
                  endif;
                endforeach;
                ?>
              </div>
            <?php endif; ?>
          </div>
          <div class="col-lg-6"></div>
          <div class="col-lg-6"></div>
        </div>
      </div>
    </div>
    <script>
      // Swiper Gallery Image Modal Product
      new Swiper(".swiper-modal-product", {
        slidesPerView: 3,
        spaceBetween: 11,
        direction: "vertical",
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
      });
    </script>
    <?php
    die();
  }

  public function kaveh_ajax_add_to_cart()
  {
    $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
    $variation_id = absint($_POST['variation_id']);
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
      do_action('woocommerce_ajax_added_to_cart', $product_id);

      if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
        wc_add_to_cart_message(array($product_id => $quantity), true);
      }
      WC_AJAX::get_refreshed_fragments();
    } else {
      $data = array(
        'error' => true,
        'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
      );
      echo wp_send_json($data);
    }
    die();
  }
}