<?php

namespace Elementor;

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

class lahze extends Widget_Base {

    public function get_name() {
        return 'lahze';
    }
    
    public function get_title() {
        return __( 'پیشنهاد لحظه ای 1', 'woolentor' );
    }


    public function get_icon() {
		return 'eicon eicon-bag-medium';
    }
    
    public function get_categories() {
        return [ 'farnam' ];
    }

    public function get_script_depends() {
        return [
            'woolentor-widgets-scripts',
            'slick',
        ];
    }

    protected function register_controls() {

        $this->start_controls_section(
            'woolentor-products',
            [
                'label' => esc_html__( 'تنظیمات محصول', 'woolentor' ),
            ]
        );
        
            $this->add_control(
			'widget_title',
			[
				'label' => __( 'عنوان', 'plugin-domain' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => __( 'پیشنهاد لحظه ای', 'plugin-domain' ),
				'placeholder' => __( 'متن خود را وارد کنید', 'plugin-domain' ),
			]
		);

            $this->add_control(
                'woolentor_product_grid_product_filter',
                [
                    'label' => esc_html__( 'فیلتر شده', 'woolentor' ),
                    'type' => Controls_Manager::SELECT,
                    'default' => 'recent',
                    'options' => [
                        'recent' => esc_html__( 'آخرین محصولات', 'woolentor' ),
                        'featured' => esc_html__( 'محضولات ویژه', 'woolentor' ),
                        'best_selling' => esc_html__( 'محصولات پر فروش', 'woolentor' ),
                        'sale' => esc_html__( 'محصولات تخفیفی', 'woolentor' ),
                        'top_rated' => esc_html__( 'محصولات محبوب', 'woolentor' ),
						 'show_byid'     => esc_html__( 'انتخاب محصول', 'woolentor' ),

                    ],
                ]
            );
			    $this->add_control(
                'woolentor_product_id',
                [
                    'label'         => __( 'چند محصول انتخاب کنید', 'woolentor' ),
                    'type'          => Controls_Manager::SELECT2,
                    'label_block'   => true,
                    'multiple'      => true,
                    'options'       => woolentor_post_name( 'product' ),
                    'condition'     => [
                        'woolentor_product_grid_product_filter' => 'show_byid',
                    ]
                ]
            );

                   $this->add_control(
                'woolentor_product_ids_manually',
                [
                    'label'         => __( 'Product IDs', 'woolentor' ),
                    'type'          => Controls_Manager::TEXT,
                    'label_block'   => true,
                    'condition'     => [
                        'woolentor_product_grid_product_filter' => 'show_byid_manually',
                    ]
                ]
            );
            $this->add_control(
              'woolentor_product_grid_row',
              [
                 'label'   => __( 'ستون ( فعلا فقط ۱ )', 'woolentor' ),
                 'type'    => Controls_Manager::NUMBER,
                 'default' => 1,
                 'min'     => 1,
                 'max'     => 20,
                 'step'    => 1,
              ]
            );

            $this->add_control(
              'woolentor_product_grid_products_count',
              [
                 'label'   => __( 'تعداد محصولات', 'woolentor' ),
                 'type'    => Controls_Manager::NUMBER,
                 'default' => 4,
                 'min'     => 1,
                 'max'     => 100,
                 'step'    => 1,
              ]
            );

            $this->add_control(
                'woolentor_product_grid_categories',
                [
                    'label' => esc_html__( 'دسته بندی محصولات', 'woolentor' ),
                    'type' => Controls_Manager::SELECT2,
                    'label_block' => true,
                    'multiple' => true,
                    'options' => woolentor_woocommerce_product_categories(),
                ]
            );

        $this->end_controls_section();


        

             
       $this->start_controls_section(
            'farnam_product_style_1',
            [
                'label' => esc_html__( 'تنظیمات فعال سازی', 'woolentor' ),
            ]
        );

		       $this->add_control(
			'farnamoneshow1',
			[
				'label' => __( 'نمایش قیمت', 'plugin-domain' ),
				'type' => \Elementor\Controls_Manager::SWITCHER,
				'label_on' => __( 'نمایش', 'your-plugin' ),
				'label_off' => __( 'مخفی', 'your-plugin' ),
				'return_value' => 'yes',
				'default' => 'yes',
			]
		);


		
        $this->end_controls_section();


        
	       $this->start_controls_section(
            'farnam_product_style_2',
            [
                'label' => esc_html__( 'تنظیمات استایل و ظاهر', 'woolentor' ),
            ]
        );
             


$this->add_control(
'color_farnam_1',
			[
				'label' => __( 'رنگ کادر اسلایدر', 'plugin-domain' ),
				'type' => Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .lahze-offer' => 'border-color: {{VALUE}} !important',
				],
			]
           );
		   
		   $this->add_control(
'color_farnam_2',
			[
				'label' => __( 'رنگ پس زمینه نوار اسلایدر', 'plugin-domain' ),
				'type' => Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .loader-bar-2' => 'background: {{VALUE}} !important',
				],
			]
           );
		   
		   $this->add_control(
'color_farnam_3',
			[
				'label' => __( 'رنگ نوار اسلایدر', 'plugin-domain' ),
				'type' => Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .slide-progress' => 'background: {{VALUE}} !important',
				],
			]
           );
		   $this->add_control(
'color_farnam_4',
			[
				'label' => __( 'رنگ پس زمینه درصد تخفیف', 'plugin-domain' ),
				'type' => Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .lahze .mizany' => 'background: {{VALUE}} !important',
				],
			]
           );
		   $this->add_control(
'color_farnam_5',
			[
				'label' => __( 'رنگ درصد تخفیف', 'plugin-domain' ),
				'type' => Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .lahze .mizany' => 'color: {{VALUE}} !important',
				],
			]
           );
		   
		   $this->add_responsive_control(
                        'farnamborder1',
                        [
                            'label' => esc_html__( 'گردی دور اسلایدر', 'woolentor' ),
                            'type' => Controls_Manager::DIMENSIONS,
                            'selectors' => [
                                '{{WRAPPER}} .lahze-offer' => 'border-radius: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px !important;',
                            ],
                        ]
                    );

  $this->add_responsive_control(
                        'farnamborder2',
                        [
                            'label' => esc_html__( 'گردی دور درصد تخفیف', 'woolentor' ),
                            'type' => Controls_Manager::DIMENSIONS,
                            'selectors' => [
                                '{{WRAPPER}} .lahze .mizany' => 'border-radius: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px !important;',
                            ],
                        ]
                    );
					

        $this->end_controls_section();

          



    }

    protected function render( $instance = [] ) {

        $settings           = $this->get_settings_for_display();
        $product_type       = $this->get_settings_for_display('woolentor_product_grid_product_filter');
        $per_page           = $this->get_settings_for_display('woolentor_product_grid_products_count');
        $custom_order_ck    = $this->get_settings_for_display('custom_order');
        $orderby            = $this->get_settings_for_display('orderby');
        $order              = $this->get_settings_for_display('order');
        $columns            = $this->get_settings_for_display('woolentor_product_grid_column');
        $rows               = $this->get_settings_for_display('woolentor_product_grid_row');
        $tabuniqid          = $this->get_id();
        $proslider          = $this->get_settings_for_display('proslider');
        $producttab          = $this->get_settings_for_display('producttab');

        $is_rtl = is_rtl();
        $direction = $is_rtl ? 'rtl' : 'ltr';
        $slider_settings = [
            'arrows' => ('yes' === $settings['slarrows']),
            'dots' => ('yes' === $settings['sldots']),
            'autoplay' => ('yes' === $settings['slautolay']),
            'autoplay_speed' => absint($settings['slautoplay_speed']),
            'animation_speed' => absint($settings['slanimation_speed']),
            'pause_on_hover' => ('yes' === $settings['slpause_on_hover']),
            'rtl' => $is_rtl,
        ];

        $slider_responsive_settings = [
            'product_items' => $settings['slitems'],
            'scroll_columns' => $settings['slscroll_columns'],
            'tablet_width' => $settings['sltablet_width'],
            'tablet_display_columns' => $settings['sltablet_display_columns'],
            'tablet_scroll_columns' => $settings['sltablet_scroll_columns'],
            'mobile_width' => $settings['slmobile_width'],
            'mobile_display_columns' => $settings['slmobile_display_columns'],
            'mobile_scroll_columns' => $settings['slmobile_scroll_columns'],

        ];

        $slider_settings = array_merge($slider_settings, $slider_responsive_settings);

        // WooCommerce Category
        $args = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'ignore_sticky_posts'   => 1,
            'posts_per_page'        => $per_page,
        );

        switch( $product_type ){

            case 'sale':
                $args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
            break;

            case 'featured':
                $args['tax_query'][] = array(
                    'taxonomy' => 'product_visibility',
                    'field'    => 'name',
                    'terms'    => 'featured',
                    'operator' => 'IN',
                );
            break;

            case 'best_selling':
                $args['meta_key']   = 'total_sales';
                $args['orderby']    = 'meta_value_num';
                $args['order']      = 'desc';
            break;

            case 'top_rated': 
                $args['meta_key']   = '_wc_average_rating';
                $args['orderby']    = 'meta_value_num';
                $args['order']      = 'desc';          
            break;

            case 'mixed_order':
                $args['orderby']    = 'rand';
            break;

            case 'show_byid':
                $args['post__in'] = $settings['woolentor_product_id'];
            break;
			
            default: /* Recent */
                $args['orderby']    = 'date';
                $args['order']      = 'desc';
            break;
        }

        // Custom Order
        if( $custom_order_ck == 'yes' ){
            $args['orderby'] = $orderby;
            $args['order'] = $order;
        }

        $get_product_categories = $settings['woolentor_product_grid_categories']; // get custom field value
        $product_cats = str_replace(' ', '', $get_product_categories);

        if ( "0" != $get_product_categories) {
            if( is_array($product_cats) && count($product_cats) > 0 ){
                $field_name = is_numeric($product_cats[0])?'term_id':'slug';
                $args['tax_query'] = array(
                    array(
                        'taxonomy' => 'product_cat',
                        'terms' => $product_cats,
                        'field' => $field_name,
                        'include_children' => false
                    )
                );
            }
        }

        $products = new \WP_Query( $args );

        $tabmenu = 'yes';

        if( ($proslider == 'yes') && ( $producttab != 'yes' ) ){
            $collumval = 'slide-item ht-col-xs-12';
        }else{
            $collumval = 'product-list';
            if( $columns !='' ){
                if( $columns == 5){
                    $collumval = 'product-list';
                }else{
                    $colwidth = round(12/$columns);
                    $collumval = 'ht-col-lg-'.$colwidth.'product-list';
                }
            }
        }

        ?>
          
        <div class="ps2 product-style htpp">

            <?php if ( $producttab == 'yes' ) { ?>
                <div class="product-tab-list ht-text-center">
  
                    </ul>
                </div>
            <?php }; ?>

            <?php if( is_array( $product_cats ) && (count( $product_cats ) > 0) && ( $producttab == 'yes' ) ): ?>
                
            <?php
                $j=0;
                foreach( $product_cats as $cats ):
                    $j++;
                    $field_name = is_numeric($product_cats[0])?'term_id':'slug';
                    $args['tax_query'] = array(
                        array(
                            'taxonomy' => 'product_cat',
                            'terms' => $cats,
                            'field' => $field_name,
                            'include_children' => false

                        )
                    );
                    $products = new \WP_Query( $args );
                    ?>
                
                <?php endforeach;?>

            <?php else:?>
                <div class="ht-row">
				
				
                 <div class="lahze-offer">
				 <h2> 		<?php echo '' . $settings['widget_title'] . ''; ?> <i class="mdi mdi-ticket-percent"></i></h2>
<div class="loader-bar-2">
</div>



<style>

.owl-demo .item img {
  display: block;
  width: 100%;
  height: auto;
}

.slide-progress {
	width: 0;
	max-width: 100%;
	height: 2px;
	background: #2DCEA2;
	border-radius: 90px;
}
</style>
<div class="owl-demo">
    <div class="slide-progress"></div>
   <div class="owl-offer199 niki-11 owl-carousel">

                        <div class="<?php echo esc_attr( $collumval );?>">
                            <?php
                                $k=1;
                                if( $products->have_posts() ):
                                    while( $products->have_posts() ): $products->the_post();
                            ?>
<div class="product-list-1 ps3 jjj-112 lahze">

<a  href="<?php the_permalink(); ?>">
	<?php the_post_thumbnail('woocommerce_thumbnail'); ?>
<h3><?php the_title(); ?></h3>
</a>

<div class="list-meta">
<span >
<?php global $product;
$units_sold = get_post_meta( $product->id, 'total_sales', true ); ?>
</span> <?php if ( 'yes' === $settings['farnamoneshow1'] ) { ?>

<span class="list-meta-2">

<div class="min-mike-6">


<?php global $product; if( $product->is_on_sale() ) { ?>
<span class="mizany">
	<?php echo apply_filters( 'woocommerce_sale_flashtwo', $post, $product ); ?>



</span>

<?php } ?>
<div class="risk-meta-price-98">
<?php echo $product->get_price_html(); ?></div></div>
</span>
<?php } ?>
</div>

</div>

                           <?php if ($k % $rows == 0 && ($products->post_count != $k)) { ?>
                            </div>
                            <div class="<?php echo esc_attr($collumval );?>">
                                <?php } $k++; endwhile; wp_reset_postdata();  endif; ?>
                            </div>
                    <?php if( $proslider == 'yes' ){ echo '</div>';} ?>
                </div>       </div></div>
				
				<script>
//Init the carousel
initSlider();

function initSlider() {
  $(".owl-offer199").owlCarousel({
     loop:true,
     autoplay:true,
    autoplayTimeout:5000,
    autoplayHoverPause:true,
    rtl: true,
    nav:false,
	  onInitialized: startProgressBar,
    onTranslate: resetProgressBar,
    onTranslated: startProgressBar,
        margin:10,
    dots: false,
    responsive:{
        0:{
            items:1
        },
		   600:{
            items:1
        },
		   800 :{
            items:1
        },
        1200:{
            items:1
        },
        1300:{
            items:1
        }
    }
	  });

}

function startProgressBar() {
  // apply keyframe animation
  $(".slide-progress").css({
    width: "100%",
    transition: "width 5000ms"
  });
}

function resetProgressBar() {
  $(".slide-progress").css({
    width: 0,
    transition: "width 0s"
  });
}


</script>
				
				</div>
            <?php endif;?>

        </div>  


        <?php

    }


}


