<?php


use Elementor\Widget_Base;
use Elementor\Controls_Manager;

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


class Digikalaamazingoffertwokaveh extends Widget_Base
{

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

    public function get_title()
    {
        return esc_html__('Digikala Amazing Offer Style Two', 'kavehTheme');
    }

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

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

    protected function register_controls()
    {

        $this->start_controls_section(
            'content1digikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Title Content', 'kavehTheme'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );
        $this->add_control(
            'titledigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Title', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__('Selected Discounted Products', 'kavehTheme'),

            ]
        );
        $this->add_control(
            'tagheadingdigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Title Tag', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'H2',
                '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->end_controls_section();
        $this->start_controls_section(
            'content2digikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Product Settings', 'kavehTheme'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $options = array();
        $orderby = 'name';
        $order = 'asc';
        $hide_empty = true;
        $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) {
            $options[$category->term_id] = $category->name;
        }
        $this->add_control(
            'catproductsdigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Select Category', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => $options,
            ]
        );

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

        $this->end_controls_section();

        $this->start_controls_section(
            'style1_digikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Title Style', 'kavehTheme'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );
        $this->add_control(
            'titlecolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Title Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#080a38',
                'selectors' => [
                    '{{WRAPPER}} .discount-products-title' => 'color: {{VALUE}} !important;',
                ],
            ]
        );
        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'title_digikalaamazingoffertwokaveh',
                'label' => esc_html__('Title Typography', 'kavehTheme'),
                'selector' => '{{WRAPPER}} .discount-products-title',
            ]
        );
        $this->add_control(
            'iconcolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Icon Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ef4056',
                'selectors' => [
                    '{{WRAPPER}} .discount-products-title i' => 'color: {{VALUE}} !important;',
                ],
            ]
        );

        $this->end_controls_section();
        $this->start_controls_section(
            'style2_digikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Product Style', 'kavehTheme'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'bglableoffercolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Discount Label Background Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ef394e',
                'selectors' => [
                    '{{WRAPPER}} .product-nineteen .offer' => 'background-color: {{VALUE}} !important',
                ],
            ]
        );

        $this->add_control(
            'lableoffercolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Discount Label Text Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .product-nineteen .offer' => 'color: {{VALUE}} !important',
                ],
            ]
        );

        $this->add_control(
            'bgprogresscolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Time Progress Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ef394e',
                'selectors' => [
                    '{{WRAPPER}} .product-nineteen .progress-time span' => 'background-color: {{VALUE}} !important',
                ],
            ]
        );

        $this->add_control(
            'timercolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Timer Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ef394e',
                'selectors' => [
                    '{{WRAPPER}} .product-nineteen .timear' => 'color: {{VALUE}} !important',
                ],
            ]
        );

        $this->add_control(
            'salespercentagecolordigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Sales Percentage Color', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'default' => '#ef394e',
                'selectors' => [
                    '{{WRAPPER}} .product-nineteen .sold span' => 'color: {{VALUE}} !important',
                ],
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'style3_digikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Box Style', 'kavehTheme'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'borderboxdigikalaamazingoffertwokaveh',
                'selector' => '{{WRAPPER}} .discount-products-wrapper'
            ]
        );
        $this->add_control(
            'boxradiusdigikalaamazingoffertwokaveh',
            [
                'label' => esc_html__('Border Radius', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .discount-products-wrapper' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );
        $this->end_controls_section();
    }
    public function child_id_with_max_discount($product)
    {
        $max_percentage = 0;
        $child_id_with_max_discount = 0;
        foreach ($product->get_children() as $child_id) {
            $variation = wc_get_product($child_id);
            $price = (float)$variation->get_regular_price();
            $sale = (float)$variation->get_sale_price();
            if ($price != 0 && !empty($sale)) $percentage = ($price - $sale) / $price * 100;
            if ($percentage > $max_percentage) {
                $max_percentage = $percentage;
                $child_id_with_max_discount = $child_id;
                return $child_id_with_max_discount;
            }
        }
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $clsid = $this->get_id();
        ?>
        <!-- Start Discount Products -->
        <section class="discount-products">
            <div class="container">
                <div class="discount-products-wrapper">
                    <<?php echo esc_attr($settings['tagheadingdigikalaamazingoffertwokaveh']); ?>
                    class="discount-products-title py-3 mb-2 d-flex align-items-center justify-content-center">
                    <i class="icon-discount me-2"></i>
                    <?php echo esc_html($settings['titledigikalaamazingoffertwokaveh']); ?>
                </<?php echo esc_attr($settings['tagheadingdigikalaamazingoffertwokaveh']); ?>>
                <div class="discount-products-items d-flex flex-wrap">
                    <?php
                    // WP_Query args
                    $cat_query_args = array(
                        'post_type' => array('product'),
'post_status' => array('publish'),
                        'posts_per_page' => $settings['numberproductsdigikalaamazingoffertwokaveh'],
                        'order' => 'DESC',
                        'orderby' => 'date',
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'product_cat',
                                'field' => 'term_id',
                                'terms' => $settings['catproductsdigikalaamazingoffertwokaveh'],
                            ),
                        ),
                        'meta_query' => array(
                            array(
                                'key' => '_stock_status',
                                'value' => 'outofstock',
                                'compare' => 'NOT IN',
                            ),
                        ),
                    );
                    $cat_query_args['post__in'] = array_merge(array(0), wc_get_product_ids_on_sale());
                    // The Query
                    $pcat_query = new \WP_Query($cat_query_args);

                    // The Loop
                    if ($pcat_query->have_posts()) :?>
                        <?php while ($pcat_query->have_posts()) :
                            $pcat_query->the_post();
                            $product = wc_get_product(get_the_ID());
                            $sale_price = $product->get_sale_price();
                            $normal_price = $product->get_regular_price();
                            ?>

                            <!-- Start Product -->
                            <div class="product-nineteen d-flex flex-column position-relative bg-white rounded-0 w-100">
                                <a href="<?php the_permalink(); ?>" class="stretched-link"
                                   aria-label="name product"></a>
                                <img src="<?php the_post_thumbnail_url('thumbnail'); ?>"
                                     alt="<?php the_title(); ?>"
                                     width="150"
                                     height="150"
                                     class="d-block mx-auto">
                                <div class="d-flex align-items-center justify-content-between mt-3">
                                    <span class="offer d-flex align-items-center justify-content-center text-white rounded-4 fw-bold">
                                        <?php if (class_exists('kavehWoo')) {
                                            $offer_percentage = kavehWoo::showofferpercentage($product);
                                            echo $offer_percentage;
                                        } ?>
                                    </span>
                                    <div class="price d-flex align-items-center fw-bold">
                                        <?php
                                        if ($product->is_type('simple')) {
                                            echo number_format($sale_price, 0, '.', ',');
                                        } elseif ($product->is_type('variable')) {
                                            $sale_price_v = (float)wc_get_product($this->child_id_with_max_discount($product))->get_sale_price();
                                            echo number_format($sale_price_v, 0, '.', ',');
                                        }
                                        ?>
                                        <i class="icon-toman-2"></i>
                                    </div>
                                </div>
                                <del class="last-price text-end d-block">
                                    <?php
                                    if ($product->is_type('simple')) {
                                        echo number_format($normal_price, 0, '.', ',');
                                    } elseif ($product->is_type('variable')) {
                                        $normal_price_v = (float)wc_get_product($this->child_id_with_max_discount($product))->get_regular_price();
                                        echo number_format($normal_price_v, 0, '.', ',');
                                    }
                                    ?>
                                </del>
                                <?php
                                if ($product->is_type('simple')) {
                                    $product_id = $product->get_id();

                                    $sale_start_date = get_post_meta($product_id, '_sale_price_dates_from', true);
                                    $sale_end_date = get_post_meta($product_id, '_sale_price_dates_to', true);
                                    if (!empty($sale_start_date) && !empty($sale_end_date)) { ?>
                                        <div class="progress-time position-relative mt-2 overflow-hidden rounded-pill mb-1">
                                    <span class="position-absolute top-0 end-0 rounded-pill h-100"
                                          style="width:<?php
                                          $current_time = current_time('timestamp');
                                          $total_time = $sale_end_date - $sale_start_date;
                                          $time_remaining = $sale_end_date - $current_time;
                                          if ($time_remaining >= 0 && $total_time > 0) {
                                              $percentage_remaining = ($time_remaining / $total_time) * 100;
                                              echo round($percentage_remaining, 2);
                                          }
                                          ?>%;"></span>
                                        </div>
                                        <?php
                                    } else {
                                    }
                                } elseif ($product->is_type('variable')) {
                                    $max_percentage = 0;
                                    $child_id_with_max_discount = 0;
                                    foreach ($product->get_children() as $child_id) {
                                        $variation = wc_get_product($child_id);
                                        $price = (float)$variation->get_regular_price();
                                        $sale = (float)$variation->get_sale_price();
                                        if ($price != 0 && !empty($sale)) $percentage = ($price - $sale) / $price * 100;
                                        if ($percentage > $max_percentage) {
                                            $max_percentage = $percentage;
                                            $child_id_with_max_discount = $child_id;
                                        }
                                    }
                                    $sale_start_date = get_post_meta($child_id_with_max_discount, '_sale_price_dates_from', true);
                                    $sale_end_date = get_post_meta($child_id_with_max_discount, '_sale_price_dates_to', true);
                                    if (!empty($sale_start_date) && !empty($sale_end_date)) { ?>
                                        <div class="progress-time position-relative mt-2 overflow-hidden rounded-pill mb-1">
                                    <span class="position-absolute top-0 end-0 rounded-pill h-100"
                                          style="width:<?php
                                          $current_time = current_time('timestamp');
                                          $total_time = $sale_end_date - $sale_start_date;
                                          $time_remaining = $sale_end_date - $current_time;
                                          if ($time_remaining >= 0 && $total_time > 0) {
                                              $percentage_remaining = ($time_remaining / $total_time) * 100;
                                              echo round($percentage_remaining, 2);
                                          }
                                          ?>%"></span>
                                        </div>
                                        <?php
                                    } else {
                                    }
                                }
                                ?>
                                <div class="d-flex align-items-center justify-content-between mt-a">
                                    <?php
                                    $product_id = $product->get_id();
                                    $sales_percentage = get_post_meta($product_id, '_sale_price', true) ? round(($product->get_sale_price() / $product->get_regular_price()) * 100) : 0;
                                    ?>
                                    <div class="sold fw-semibold">
                                        <span class="me-1"> <?php echo $sales_percentage ?>% </span>
                                        Sold
                                    </div>
                                    <?php
                                    if ($product->is_type('simple')) {
                                        $product_id = $product->get_id();
                                        $sale_end_date_to = '';
                                        if ($date_to = get_post_meta($product_id, '_sale_price_dates_to', true)) {
                                            $sale_end_date_to = date('Y-m-d 23:59:59', $date_to);
                                        }

                                        if (!empty($sale_end_date)) { ?>
                                            <div class="timear d-flex align-items-center fw-bold"
                                                 data-time="<?php echo $sale_end_date_to ?>">
                                                <span class="second"> 00 </span>:
                                                <span class="minute"> 00 </span>:
                                                <span class="hour"> 00 </span>
                                                <span class="day"> 00 </span>
                                            </div>
                                            <?php
                                        } else {
                                        }
                                    } elseif ($product->is_type('variable')) {
                                        $max_percentage = 0;
                                        $child_id_with_max_discount = 0;
                                        foreach ($product->get_children() as $child_id) {
                                            $variation = wc_get_product($child_id);
                                            $price = (float)$variation->get_regular_price();
                                            $sale = (float)$variation->get_sale_price();
                                            if ($price != 0 && !empty($sale)) $percentage = ($price - $sale) / $price * 100;
                                            if ($percentage > $max_percentage) {
                                                $max_percentage = $percentage;
                                                $child_id_with_max_discount = $child_id;
                                            }
                                        }
                                        $sale_end_date_to = '';
                                        if ($date_to = get_post_meta($child_id_with_max_discount, '_sale_price_dates_to', true)) {
                                            $sale_end_date_to = date('Y-m-d 23:59:59', $date_to);
                                        }
                                        if (!empty($sale_end_date)) { ?>
                                            <div class="timear d-flex align-items-center fw-bold"
                                                 data-time="<?php echo $sale_end_date_to ?>">
                                                <span class="second"> 00 </span>:
                                                <span class="minute"> 00 </span>:
                                                <span class="hour"> 00 </span>
                                                <span class="day"> 00 </span>
                                            </div>
                                            <?php
                                        } else {
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                            <!-- End Product -->

                        <?php
                        endwhile;
                        // Reset Original Post Data after the loop
                        wp_reset_postdata();
                        ?>
                    <?php endif; ?>

                </div>
            </div>
            </div>
        </section>
        <!-- End Discount Products -->
        <?php
    }

}
