<?php



use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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


class Productstablekaveh extends Widget_Base{

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

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

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

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

  protected function register_controls(){
    
    $this->start_controls_section(
        'contentproductstablekaveh',
        [
          'label' => esc_html__( 'Element Content', 'kavehTheme' ),
                  'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]
      );
      $this->add_control(
        'kaveh_section_switchproductstablekaveh',
        [
            'label' => esc_html__('Show Title Section', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'yes' => esc_html__('Yes', 'kavehTheme'),
            'no' => esc_html__('No', 'kavehTheme'),
            'return_value' => 'yes',
            'default' => 'yes',

        ]
      );
      $this->add_control(
        'img1productstablekaveh',
        [
          'label' => esc_html__( 'Image Before Title', 'kavehTheme' ),
          'type' => \Elementor\Controls_Manager::MEDIA,
          'condition' => [
            'kaveh_section_switchproductstablekaveh' => 'yes',
        ],
          'selectors' => [
            '{{WRAPPER}} .price-day-girder .section-heading .detail::before' => 'background: url({{url}})0 0 no-repeat',
          ],

        ]
      );
      $this->add_control(
          'titleproductstablekaveh',
          [
              'label' => esc_html__( 'Subtitle', 'kavehTheme' ),
              'type' => \Elementor\Controls_Manager::TEXT,
              'condition' => [
                'kaveh_section_switchproductstablekaveh' => 'yes',
            ],
              'default' => esc_html__( 'Daily Price', 'kavehTheme' ),
      
          ]
      ); 
      $this->add_control(
        'tagheading1productstablekaveh',
        [
          'label' => esc_html__( 'Subtitle Tag', 'kavehTheme' ),
          'type' => \Elementor\Controls_Manager::SELECT,
          'condition' => [
            'kaveh_section_switchproductstablekaveh' => 'yes',
        ],
          'default' => 'H3',
          'options' => [
            'H1'  => esc_html__( 'H1', 'kavehTheme' ),
            'H2' => esc_html__( 'H2', 'kavehTheme' ),
            'H3' => esc_html__( 'H3', 'kavehTheme' ),
            'H4' => esc_html__( 'H4', 'kavehTheme' ),
            'H5' => esc_html__( 'H5', 'kavehTheme' ),
            'H6' => esc_html__( 'H6', 'kavehTheme' ),
            'p' => esc_html__( 'p', 'kavehTheme' ),
            'div' => esc_html__( 'div', 'kavehTheme' ),
            'span' => esc_html__( 'span', 'kavehTheme' ),
          ],
        ]
      );
      $this->add_control(
        'title2productstablekaveh',
        [
            'label' => esc_html__( 'Title', 'kavehTheme' ),
            'type' => \Elementor\Controls_Manager::TEXT,
            'condition' => [
              'kaveh_section_switchproductstablekaveh' => 'yes',
          ],
            'default' => esc_html__( 'Steel Beam', 'kavehTheme' ),
    
        ]
    );
    $this->add_control(
      'tagheading2productstablekaveh',
      [
        'label' => esc_html__( 'Title Tag', 'kavehTheme' ),
        'type' => \Elementor\Controls_Manager::SELECT,
        'default' => 'H3',
        'condition' => [
          'kaveh_section_switchproductstablekaveh' => 'yes',
      ],
        'options' => [
          'H1'  => esc_html__( 'H1', 'kavehTheme' ),
          'H2' => esc_html__( 'H2', 'kavehTheme' ),
          'H3' => esc_html__( 'H3', 'kavehTheme' ),
          'H4' => esc_html__( 'H4', 'kavehTheme' ),
          'H5' => esc_html__( 'H5', 'kavehTheme' ),
          'H6' => esc_html__( 'H6', 'kavehTheme' ),
          'p' => esc_html__( 'p', 'kavehTheme' ),
          'div' => esc_html__( 'div', 'kavehTheme' ),
          'span' => esc_html__( 'span', 'kavehTheme' ),
        ],
      ]
    );

    $this->add_control(
      'kaveh_percentage_switchproductstablekaveh',
      [
          'label' => esc_html__('Show Price Change Percentage', 'kavehTheme'),
          'type' => \Elementor\Controls_Manager::SWITCHER,
          'yes' => esc_html__('Yes', 'kavehTheme'),
            'no' => esc_html__('No', 'kavehTheme'),
          'return_value' => 'yes',
          'default' => 'yes',

      ]
    );
          // 1. Post Type Selection
      $post_types = get_post_types(['public' => true], 'objects');
      $post_type_options = [];
      foreach ($post_types as $post_type) {
        $post_type_options[$post_type->name] = $post_type->label;
      }
      $this->add_control(
        'post_type_productstablekaveh',
        [
            'label' => esc_html__('Content Type', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'product',
            'options' => $post_type_options,
        ]
      );

      // 2. Exclude Out of Stock Products (for WooCommerce only)
      $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',
            'condition' => [
                'post_type_productstablekaveh' => 'product',
            ],
        ]
      );

      // 3. Show Only Onsale Products
      $this->add_control(
        'show_onsale_products_productstablekaveh',
        [
            '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',
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
            ],
        ]
      );

      // 4. Taxonomy Filters
      $taxonomies = get_taxonomies(['public' => true], 'objects');
      $taxonomy_options = [];
      foreach ($taxonomies as $taxonomy) {
        $taxonomy_options[$taxonomy->name] = $taxonomy->label;
      }
      $this->add_control(
        'taxonomy_filter_productstablekaveh',
        [
            'label' => esc_html__('Filter by Taxonomy', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $taxonomy_options,
        ]
      );
      // Add a control for selecting taxonomy terms
      $this->add_control(
      'taxonomy_terms_productstablekaveh',
      [
        'label' => esc_html__('Select Taxonomy Terms', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => [], // Initially empty, populated dynamically
        'condition' => [
            'taxonomy_filter_productstablekaveh!' => '', // Show only if a taxonomy is selected
        ],
      ]
      );

      // 5. Product Attributes Control
      $attribute_taxonomies = wc_get_attribute_taxonomies();
      $attribute_options = [];
      foreach ($attribute_taxonomies as $attribute) {
        $attribute_options[$attribute->attribute_name] = $attribute->attribute_label;
      }
      $this->add_control(
        'product_attributes_productstablekaveh',
        [
            'label' => esc_html__('Filter by Product Attribute', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $attribute_options,
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
            ],
        ]
      );



      // Add a control for selecting product attribute terms
      $this->add_control(
      'product_attribute_terms_productstablekaveh',
      [
        'label' => esc_html__('Select Attribute Values', 'kavehTheme'),
        'type' => \Elementor\Controls_Manager::SELECT2,
        'multiple' => true,
        'options' => [], // Initially empty, populated dynamically
        'condition' => [
            'product_attributes_productstablekaveh!' => '', // Show only if an attribute is selected
        ],
      ]
      );

      // 6. Advanced Sorting
      $this->add_control(
        'psortproductstablekaveh',
        [
            'label' => esc_html__('Sort By', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'date',
            'options' => [
                'date' => esc_html__('Date', 'kavehTheme'),
                'title' => esc_html__('Title', 'kavehTheme'),
                'rand' => esc_html__('Random', 'kavehTheme'),
                'comment_count' => esc_html__('Comment Count', 'kavehTheme'),
                'menu_order' => esc_html__('Menu Order', 'kavehTheme'),
                '_price' => esc_html__('Price', 'kavehTheme'),
                '_wc_average_rating' => esc_html__('Most Popular', 'kavehTheme'),
                'total_sales' => esc_html__('Sales Volume', 'kavehTheme'),
            ],
        ]
      );

      // 7. Sort Order
      $this->add_control(
        'psortiproductstablekaveh',
        [
            'label' => esc_html__('Sort Order', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'desc',
            'options' => [
                'asc' => esc_html__('Ascending', 'kavehTheme'),
                'desc' => esc_html__('Descending', 'kavehTheme'),
            ],
        ]
      );

      // 8. Pagination and Limits
      $this->add_control(
        'posts_per_page_productstablekaveh',
        [
            'label' => esc_html__('Number of Products', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::NUMBER,
            'default' => 6,
            'min' => 1,
            'max' => 100,
        ]
      );


      // 9. Meta Query (Custom Fields)
      $this->add_control(
        'meta_key_productstablekaveh',
        [
            'label' => esc_html__('Meta Key', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'description' => esc_html__('Meta key for filtering (optional)', 'kavehTheme'),
        ]
      );

      $this->add_control(
        'meta_value_productstablekaveh',
        [
            'label' => esc_html__('Meta Value', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'description' => esc_html__('Meta value for filtering (optional)', 'kavehTheme'),
        ]
      );

      // 10. Date Query
      $this->add_control(
        'date_query_productstablekaveh',
        [
            'label' => esc_html__('Filter by Date', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'none',
            'options' => [
                'none' => esc_html__('None', 'kavehTheme'),
                'today' => esc_html__('Today', 'kavehTheme'),
                'last_7_days' => esc_html__('Last 7 Days', 'kavehTheme'),
                'last_30_days' => esc_html__('Last 30 Days', 'kavehTheme'),
                'custom' => esc_html__('Custom', 'kavehTheme'),
            ],
        ]
      );

      // 11. Exclusions
      $this->add_control(
        'exclude_posts_productstablekaveh',
        [
            'label' => esc_html__('Exclude Posts', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'description' => esc_html__('Separate post IDs with commas (optional)', 'kavehTheme'),
        ]
      );

      // 12. Custom Query Parameters
      $this->add_control(
        'custom_query_productstablekaveh',
        [
            'label' => esc_html__('Custom WP_Query Parameters', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::TEXTAREA,
            'description' => esc_html__('Enter custom parameters as JSON (optional)', 'kavehTheme'),
        ]
      );

      $this->add_control(
        'pcol1productstablekaveh',
        [
            'label' => esc_html__('First Table Column', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'code',
            'options' => [
                'code' => esc_html__('Product ID', 'kavehTheme'),
                'feature' => esc_html__('Feature', 'kavehTheme'),
            ],
        ]
      );
      $this->add_control(
        'product_attribute_column_1_productstablekaveh',
        [
            'label' => esc_html__('First Column', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $attribute_options,
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
                'pcol1productstablekaveh' => 'feature', // Only show for products
            ],
        ]
      );
      $this->add_control(
        'product_attribute_column_3_productstablekaveh',
        [
            'label' => esc_html__('Third Column', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $attribute_options,
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
            ],
        ]
      );
      $this->add_control(
        'product_attribute_column_4_productstablekaveh',
        [
            'label' => esc_html__('Fourth Column', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $attribute_options,
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
            ],
        ]
      );
      $this->add_control(
        'product_attribute_column_5_productstablekaveh',
        [
            'label' => esc_html__('Fifth Column', 'kavehTheme'),
            'type' => \Elementor\Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => $attribute_options,
            'condition' => [
                'post_type_productstablekaveh' => 'product', // Only show for products
            ],
        ]
      );

            $this->end_controls_section();
                
      $this->start_controls_section(
        'styleproductstablekaveh',
        [
          'label' => esc_html__( 'Title Style', 'kavehTheme' ),
          'tab' => \Elementor\Controls_Manager::TAB_STYLE,
          'condition' => [
            'kaveh_section_switchproductstablekaveh' => 'yes',
        ],
        ]
      );
      $this->add_group_control(
        \Elementor\Group_Control_Typography::get_type(),
        [
          'name' => 'title1_productstablekaveh',
          'label' => esc_html__( 'Subtitle Typography', 'kavehTheme' ),
          'selector' => '{{WRAPPER}} .price-day-girder .section-heading-sub-title',
        ]
      );
      $this->add_control(
        't1colorproductstablekaveh',
        [
          'label' => esc_html__( 'Subtitle Color', 'kavehTheme' ),
          'type' => \Elementor\Controls_Manager::COLOR,
          'selectors' => [
            '{{WRAPPER}} .price-day-girder .section-heading-sub-title' => 'color: {{VALUE}}',
          ],
        ]
      );
      $this->add_group_control(
        \Elementor\Group_Control_Typography::get_type(),
        [
          'name' => 'title2productstablekaveh',
          'label' => esc_html__( 'Title Typography', 'kavehTheme' ),
          'selector' => '{{WRAPPER}} .price-day-girder .section-heading-title',
        ]
      );
      $this->add_control(
        't2colorproductstablekaveh',
        [
          'label' => esc_html__( 'Title Color', 'kavehTheme' ),
          'type' => \Elementor\Controls_Manager::COLOR,
          'selectors' => [
            '{{WRAPPER}} .price-day-girder .section-heading-title' => 'color: {{VALUE}}',
          ],
        ]
      );
      $this->end_controls_section();
      $this->start_controls_section(
        'style2productstablekaveh',
        [
          'label' => esc_html__( 'Products Style', 'kavehTheme' ),
          'tab' => \Elementor\Controls_Manager::TAB_STYLE,
        ]
      );
      $this->add_control(
        'trcolorproductstablekaveh',
        [
          'label' => esc_html__( 'Row Border Color', 'kavehTheme' ),
          'type' => \Elementor\Controls_Manager::COLOR,
          'selectors' => [
            '{{WRAPPER}} .table tbody tr td:first-child::after' => 'background-color: {{VALUE}}',
          ],
        ]
      );
      $this->end_controls_section();
        }
 

  protected function render(){
    $settings = $this->get_settings_for_display();
    $clsid = $this->get_id();
    ?>
<div class="price-day-girder">
      <div class="container">
      <?php if("yes"===$settings['kaveh_section_switchproductstablekaveh']){?>
        <!-- Start Heading -->
        <div class="section-heading d-flex align-items-sm-center justify-content-sm-between flex-column flex-sm-row">
          <div class="detail position-relative">
            <<?php echo  esc_attr($settings['tagheading1productstablekaveh']); ?> class="section-heading-sub-title"><?php echo  esc_html($settings['titleproductstablekaveh']); ?></<?php echo  esc_attr($settings['tagheading1productstablekaveh']); ?>>
            <<?php echo  esc_attr($settings['tagheading2productstablekaveh']); ?> class="section-heading-title"><?php echo  esc_html($settings['title2productstablekaveh']); ?></<?php echo  esc_attr($settings['tagheading2productstablekaveh']); ?>>
          </div>
        </div>
        <!-- End Heading -->
         <?php } ?>
        <?php
// Build query arguments
    $args = [
        'post_type' => $settings['post_type_productstablekaveh'],
        'posts_per_page' => $settings['posts_per_page_productstablekaveh'],
        'orderby' => $settings['psortproductstablekaveh'],
        'order' => $settings['psortiproductstablekaveh']
    ];

    // Handle WooCommerce specific options
    if ($settings['post_type_productstablekaveh'] === 'product') {
        // Exclude out of stock products
        if ($settings['kaveh_exclude_out_of_stock'] === 'yes') {
            $args['meta_query'][] = [
                'key' => '_stock_status',
                'value' => 'outofstock',
                'compare' => '!='
            ];
        }

        // Show only on-sale products
        if ($settings['show_onsale_products_productstablekaveh'] === 'yes') {
            $args['meta_query'][] = [
                'relation' => 'OR',
                [
                    'key' => '_sale_price',
                    'value' => '',
                    'compare' => '!='
                ],
                [
                    'key' => '_min_variation_sale_price',
                    'value' => '',
                    'compare' => '!='
                ]
            ];
        }

        // Handle product attributes
        if (!empty($settings['product_attributes_productstablekaveh']) && !empty($settings['product_attribute_terms_productstablekaveh'])) {
            $tax_query = [];
            foreach ($settings['product_attributes_productstablekaveh'] as $attribute) {
                $tax_query[] = [
                    'taxonomy' => 'pa_' . $attribute,
                    'field' => 'term_id',
                    'terms' => $settings['product_attribute_terms_productstablekaveh']
                ];
            }
            if (!empty($tax_query)) {
                $args['tax_query'][] = [
                    'relation' => 'AND',
                    $tax_query
                ];
            }
        }
    }

    // Handle taxonomy filters
    if (!empty($settings['taxonomy_filter_productstablekaveh']) && !empty($settings['taxonomy_terms_productstablekaveh'])) {
        $tax_query = [];
        foreach ($settings['taxonomy_filter_productstablekaveh'] as $taxonomy) {
            $tax_query[] = [
                'taxonomy' => $taxonomy,
                'field' => 'term_id',
                'terms' => $settings['taxonomy_terms_productstablekaveh']
            ];
        }
        if (!empty($tax_query)) {
            $args['tax_query'][] = [
                'relation' => 'AND',
                $tax_query
            ];
        }
    }

    // Handle meta query
    if (!empty($settings['meta_key_productstablekaveh']) && !empty($settings['meta_value_productstablekaveh'])) {
        $args['meta_query'][] = [
            'key' => $settings['meta_key_productstablekaveh'],
            'value' => $settings['meta_value_productstablekaveh']
        ];
    }

    // Handle date query
    if ($settings['date_query_productstablekaveh'] !== 'none') {
        $date_query = [];
        switch ($settings['date_query_productstablekaveh']) {
            case 'today':
                $date_query = [
                    'after' => '1 day ago'
                ];
                break;
            case 'last_7_days':
                $date_query = [
                    'after' => '1 week ago'
                ];
                break;
            case 'last_30_days':
                $date_query = [
                    'after' => '1 month ago'
                ];
                break;
        }
        if (!empty($date_query)) {
            $args['date_query'] = $date_query;
        }
    }

    // Handle exclusions
    if (!empty($settings['exclude_posts_productstablekaveh'])) {
        $excluded_ids = array_map('trim', explode(',', $settings['exclude_posts_productstablekaveh']));
        $args['post__not_in'] = array_map('intval', $excluded_ids);
    }

    // Handle custom query parameters
    if (!empty($settings['custom_query_productstablekaveh'])) {
        $custom_args = json_decode($settings['custom_query_productstablekaveh'], true);
        if (is_array($custom_args)) {
            $args = array_merge($args, $custom_args);
        }
    }

    // Execute the query
    $query = KavehCustomQuery::get_cached_query($args);
    ?>

        <div class="table-responsive">
        <table class="table">
            <thead>
            <tr>
            <th>
              <?php
                if ($settings['pcol1productstablekaveh'] === 'feature' && !empty($settings['product_attribute_column_1_productstablekaveh'])) {
                  $attr_name = wc_sanitize_taxonomy_name($settings['product_attribute_column_1_productstablekaveh'][0]);
                  $label = wc_attribute_label('pa_' . $attr_name);
                  echo esc_html($label);
                } else {
                  echo 'Product ID';
                }
              ?>
            </th>
                <th>Name</th>
                <?php 
                $attribute_columns = [
                    'product_attribute_column_3_productstablekaveh',
                    'product_attribute_column_4_productstablekaveh',
                    'product_attribute_column_5_productstablekaveh'
                ];
                foreach ($attribute_columns as $column_key) {
                    if (!empty($settings[$column_key])) {
                    foreach ($settings[$column_key] as $attr_name) {
                        $taxonomy = wc_sanitize_taxonomy_name($attr_name);
                        $label = wc_attribute_label($taxonomy);
                        echo '<th>' . esc_html($label) . '</th>';
                    }
                    }
                }
                ?>
                <th>Price (<?= get_woocommerce_currency_symbol();?>)</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php
                if ($query->have_posts()) :
                while ($query->have_posts()) : $query->the_post();
                    global $product;
                    $pr_id = get_the_ID();
                    ?>
                    <tr class="product-<?php echo $pr_id; ?>">
                    <td>
                      <span class="badge badge-danger rounded-pill">
                        <?php
                          if ($settings['pcol1productstablekaveh'] === 'feature' && !empty($settings['product_attribute_column_1_productstablekaveh'])) {
                            $attr_name = wc_sanitize_taxonomy_name($settings['product_attribute_column_1_productstablekaveh'][0]);
                            $terms = get_the_terms(get_the_ID(), 'pa_' . $attr_name);
                            if (!empty($terms) && !is_wp_error($terms)) {
                              echo esc_html(wp_list_pluck($terms, 'name')[0]);
                            } else {
                              echo '-';
                            }
                          } else {
                            echo esc_html($product->get_sku() ?: '-');
                          }
                        ?>
                      </span>
                    </td>

                    <td class="name">
                        <a href="<?= esc_url(get_permalink()); ?>" class="fw-bold"><?= esc_html(get_the_title()); ?></a>
                    </td>
                    <?php
                        foreach ($attribute_columns as $column_key) {
                        if (!empty($settings[$column_key])) {
                            foreach ($settings[$column_key] as $attr_name) {
                            $taxonomy = 'pa_' . wc_sanitize_taxonomy_name($attr_name);
                            $terms = get_the_terms(get_the_ID(), $taxonomy);
                            echo '<td>';
                            if (!empty($terms) && !is_wp_error($terms)) {
                                $term_names = wp_list_pluck($terms, 'name');
                                echo '<span class="badge badge-secondary">' . esc_html(implode(', ', $term_names)) . '</span>';
                            } else {
                                echo '-';
                            }
                            echo '</td>';
                            }
                        }
                        }
                    ?>
                    <td class="price fw-bold">
                      <div class="d-flex align-items-center justify-content-start gap-2">
                        <?php

                          $current_price = floatval($product->get_price());
                          $icon = '';
                          $percentage = null;

                       if("yes"===$settings['kaveh_percentage_switchproductstablekaveh']){

                          if ($product->is_type('variable')) {
                            $variations = $product->get_children();
                            $first_variation_id = reset($variations); // Only the first variation

                            if ($first_variation_id) {
                              $history = get_post_meta($first_variation_id, '_kaveh_price_history', true);
                              if (is_array($history) && count($history) >= 2) {
                                $recent = array_slice($history, -2, 2);
                                $previous = floatval($recent[0]['price']);
                                $latest   = floatval($recent[1]['price']);

                                if ($previous > 0 && $latest != $previous) {
                                  $diff = $latest - $previous;
                                  $percentage = round(($diff / $previous) * 100);

                                  if ($diff > 0) {
                                    $icon = '<i class="icon-angle-up-fill text-success"></i>';
                                    $percentage = '+' . $percentage;
                                    ?>
                                    <style>
                                      <?php echo '.product-' . $pr_id ?> .price-change {
                                        color: #49be78;
                                        direction: ltr;
                                      }
                                    </style>
                                    <?php
                                  } elseif ($diff < 0) {
                                    $icon = '<i class="icon-angle-down-fill text-danger"></i>';
                                    ?>
                                    <style>
                                      <?php echo '.product-' . $pr_id ?> .price-change {
                                        color: #ee273a;
                                        direction: ltr;
                                      }
                                    </style>
                                    <?php
                                  }
                                }
                              }
                            }
                          } else {
                            $history = get_post_meta($product->get_id(), '_kaveh_price_history', true);
                            if (is_array($history) && count($history) >= 2) {
                              $recent = array_slice($history, -2, 2);
                              $previous = floatval($recent[0]['price']);
                              $latest   = floatval($recent[1]['price']);

                              if ($previous > 0 && $latest != $previous) {
                                $diff = $latest - $previous;
                                $percentage = round(($diff / $previous) * 100);

                                if ($diff > 0) {
                                  $icon = '<i class="icon-angle-up-fill text-success"></i>';
                                  $percentage = '+' . $percentage;
                                  ?>
                                  <style>
                                    <?php echo '.product-' . $pr_id ?> .price-change {
                                      color: #49be78;
                                      direction: ltr;
                                    }
                                  </style>
                                  <?php
                                } elseif ($diff < 0) {
                                  $icon = '<i class="icon-angle-down-fill text-danger"></i>';
                                  ?>
                                  <style>
                                    <?php echo '.product-' . $pr_id ?> .price-change {
                                      color: #ee273a;
                                      direction: ltr;
                                    }
                                  </style>
                                  <?php
                                }
                              }
                            }
                          }
                        }

                          if (!is_null($percentage)) {
                            echo '<span class="price-change" style="font-size:13px;font-weight: 300;">' . esc_html($percentage) . '%</span>';
                          }

                          if ($icon) {
                            echo '<span class="price-icon">' . $icon . '</span>';
                          }

                          echo '<span class="price-current">' . number_format($current_price) . '</span>';
                        ?>
                      </div>
                    </td>

 


                    <td class="icons d-flex align-items-center">

                      <?php
                        $product_url = $product->is_type('variable')
                            ? get_permalink($product->get_id()) // Link to product page
                            : $product->add_to_cart_url();      // Add to cart link
                      ?>
                      <a href="<?= esc_url($product_url); ?>">
                        <i class="icon-cart-3"></i>
                      </a>


                        <a class="show-price-chart" data-product-id="<?php echo esc_attr($product->get_id()); ?>">
                          <i class="icon-chart"></i>
                        </a>

                        <a id="eyeid" type="button" value="<?php echo $pr_id; ?>" class="rounded-circle text-center d-block eyeid"
                          data-bs-toggle="modal" data-bs-target="#modal-product">
                          <i class="isax isax-eye3"></i>
                        </a>

                    </td>
                    </tr>
                    <?php
                endwhile;
                wp_reset_postdata();
                endif;
            ?>
            </tbody>
        </table>
        </div>
                        
      </div>
    </div>
    <style>
      .show-price-chart{
        cursor : pointer ;
      }
      .price-day-girder .table tbody tr td.price i {
    margin-left: 0px;
}
.price-day-girder .section-heading .detail::before {
    content: "";
    top: 0;
    right: 0;
    width: 39px;
    height: 62px;
    -webkit-background-size: 100% 100% !important;
    -moz-background-size: 100% 100% !important;
    -o-background-size: 100% 100% !important;
    background-size: 100% 100% !important;
    object-fit: contain;
}
    </style>
    <?php
  }


}
