<?php

use \Elementor\Group_Control_Image_Size;

class Product_Amazon_SLID extends \Elementor\Widget_Base {

	public function get_name() {
		return 'product-amazon_slid';
	}

	public function get_title() {
		return __( 'product amazon slid', 'leora' );
	} 

	public function get_icon() {
		return ' eicon-image-rollover';
	}

	public function get_categories() {
		return [ 'elementor-widget-be-shop' ];
	}
	public function get_script_depends() {
		return [ 'elementor-hello-world' ];
	}
	protected function register_controls()
    {
        $this->init_content_general_controls();
    }

    protected function init_content_general_controls()
  {
		$this->start_controls_section(
			'section_content',
			[
				'label' => __( 'Content', 'leora' ),
			]
		);
		$this->add_control(
			'title',
			[
				'label' => __( 'Title', 'leora' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => 'Edible and drinkable',
			]
		);
		$this->add_control(
			'title_self',
			[
				'label' => __( 'title self', 'leora' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => 'تــــخــــفـــــیــــف تـــا',
			]
		);
		$this->add_control(
			'title_self_discount',
			[
				'label' => __( 'self discount', 'leora' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => '34%',
			]
		);
		$this->add_control(
			'title_show_more',
			[
				'label' => __( 'title show more', 'leora' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => 'View all offers',
			]
		);
		$this->add_control(
			'more_link',
			[
				'label' => __( 'more Link', 'leora' ),
				'type' => \Elementor\Controls_Manager::URL,
				'placeholder' => __( 'https://your-link.com', 'leora' ),
				'show_external' => true,
				'default' => [
					'url' => '',
					'is_external' => true,
					'nofollow' => true,
				],
			]
		);
		$this->add_control(
			'countdown',
			[
			  'label' => __( 'countdown', 'leora' ),
			  'type' => \Elementor\Controls_Manager::SWITCHER,
			  'label_on' => __( 'Show', 'leora' ),
			  'label_off' => __( 'Hide', 'leora' ),
			  'return_value' => 'yes',
			  'default' => 'yes',
			]
		  );

		$this->end_controls_section();
        $this->start_controls_section(
            'leora-products',
            [
                'label' => esc_html__( 'Product Settings', 'leora' ),
            ]
        );
            $this->add_control(
                'my_plugin_product_grid_product_filter',
                [
                    'label' => esc_html__( 'Filter By', 'leora' ),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'recent',
                    'options' => [
                        'recent' => esc_html__( 'Recent Products', 'leora' ),
                        'featured' => esc_html__( 'Featured Products', 'leora' ),
                        'best_selling' => esc_html__( 'Best Selling Products', 'leora' ),
                        'sale' => esc_html__( 'Sale Products', 'leora' ),
                        'top_rated' => esc_html__( 'Top Rated Products', 'leora' ),
                        'mixed_order' => esc_html__( 'Mixed order Products', 'leora' ),
                    ],
                ]
            );
            $this->add_control(
              'my_plugin_product_grid_products_count',
              [
                 'label'   => __( 'Products Count', 'leora' ),
                 'type'    => \Elementor\Controls_Manager::NUMBER,
                 'default' => 6,
                 'min'     => 1,
                 'max'     => 100,
                 'step'    => 1,
              ]
            );

            $this->add_control(
                'my_plugin_product_grid_categories',
                [
                    'label' => esc_html__( 'Product Categories', 'leora' ),
                    'type' => \Elementor\Controls_Manager::SELECT2,
                    'label_block' => true,
                    'multiple' => true,
                    'options' => my_plugin_taxonomy_list(),
                ]
            );

            $this->add_control(
                'custom_order',
                [
                    'label' => esc_html__( 'Custom order', 'leora' ),
                    'type' => \Elementor\Controls_Manager::SWITCHER,
                    'return_value' => 'yes',
                    'default' => 'no',
                ]
            );

            $this->add_control(
                'orderby',
                [
                    'label' => esc_html__( 'Orderby', 'leora' ),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'none',
                    'options' => [
                        'none'          => esc_html__('None','leora'),
                        'ID'            => esc_html__('ID','leora'),
                        'date'          => esc_html__('Date','leora'),
                        'name'          => esc_html__('Name','leora'),
                        'title'         => esc_html__('Title','leora'),
                        'comment_count' => esc_html__('Comment count','leora'),
                        'rand'          => esc_html__('Random','leora'),
                    ],
                    'condition' => [
                        'custom_order' => 'yes',
                    ]
                ]
            );

            $this->add_control(
                'order',
                [
                    'label' => esc_html__( 'order', 'leora' ),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'DESC',
                    'options' => [
                        'DESC'  => esc_html__('Descending','leora'),
                        'ASC'   => esc_html__('Ascending','leora'),
                    ],
                    'condition' => [
                        'custom_order' => 'yes',
                    ]
                ]
            );

        $this->end_controls_section();


		$this->start_controls_section(
			'section_style',
			[
				'label' => __( 'general', 'leora' ),
				'tab' => \Elementor\Controls_Manager::TAB_STYLE,
			]
		);
		$this->add_control(
			'background_color',
			[
				'label' => __( 'background color', 'leora' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .woo-list-slider-owl.mb-3' => 'background-color: {{VALUE}}',
				],
			]
		);
		$this->add_control(
			'title_color_1',
			[
				'label' => __( 'Title', 'leora' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .title' => 'color: {{VALUE}}',
					'{{WRAPPER}} .box_shop_5_amz .head_card_title' => 'color: {{VALUE}}',
				],
			]
		);
		$this->add_control(
			'title_color_4',
			[
				'label' => __( 'show more', 'leora' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				
				'selectors' => [
					'{{WRAPPER}} .title' => 'color: {{VALUE}}',
					'{{WRAPPER}} .box_shop_5_amz .head_card_more' => 'color: {{VALUE}}',
				],
			]
		);
		$this->add_control(
			'border_radius_amz_cat',
			[
				'label' => __( 'border radius', 'leora' ),
				'type' => \Elementor\Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%' ],
				'range' => [
					'px' => [
						'min' => 0,
						'max' => 100,
						'step' => 1,
					],
					'%' => [
						'min' => 0,
						'max' => 100,
					],
				],
				'default' => [
					'unit' => 'px',
					'size' => 15,
				],
				'selectors' => [
					'{{WRAPPER}} .woo-list-slider-owl.mb-3' => 'border-radius: {{SIZE}}{{UNIT}};',
				],
			]
		);
		$this->end_controls_section();
	}

	protected function render() { ?>
		<script>	
	$('.amazonboxs--slide .amazonslide').owlCarousel({
        rtl:true,
        loop:false,
        margin:0,
        dots:false,
        navText: ['<i class="fal fa-chevron-right"></i>', '<i class="fal fa-chevron-left"></i>'],
        nav:true,
        responsive:{ 0:{ items:2, nav:false, }, 600:{ items:3, nav:false, }, 1000:{ items:5 } }
    });
		</script>

		<?php 
		$settings = $this->get_settings_for_display();
		$settings           = $this->get_settings_for_display();
        $product_type       = $this->get_settings_for_display('my_plugin_product_grid_product_filter');
        $per_page           = $this->get_settings_for_display('my_plugin_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');
		$producttab          = $this->get_settings_for_display('producttab');
		$bg_image = '';
		$bg_image_mobile = '';
        // WooCommerce Category
        $args = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'ignore_sticky_posts'   => 1,
            'posts_per_page'        => $per_page,
		);
		// background image 
		if ( ! empty( $settings['bg_image']['id'] ) ) {
			$bg_image = \Elementor\Group_Control_Image_Size::get_attachment_image_src( $settings['bg_image']['id'], 'bg_image', $settings );
		  } elseif ( ! empty( $settings['bg_image']['url'] ) ) {
			$bg_image = $settings['bg_image']['url'];
		  }
		  $this->add_render_attribute( 'background_image', 'style', [
			'background-image: url(' . $bg_image . ');',
			] );
		// background image mobile
		if ( ! empty( $settings['bg_image_mobile']['id'] ) ) {
			$bg_image_mobile = \Elementor\Group_Control_Image_Size::get_attachment_image_src( $settings['bg_image_mobile']['id'], 'bg_image_mobile', $settings );
		  } elseif ( ! empty( $settings['bg_image_mobile']['url'] ) ) {
			$bg_image_mobile = $settings['bg_image_mobile']['url'];
		  }
		  $this->add_render_attribute( 'background_image_mobile', 'style', [
			'background-image: url(' . $bg_image_mobile . ');',
			] );
        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;

            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['my_plugin_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 );
		if ( $producttab == 'yes' ) { 
				$m=0;
				if( is_array( $product_cats ) && count( $product_cats ) > 0 ){

					// Category retrive
					$catargs = array(
						'orderby'    => 'name',
						'order'      => 'ASC',
						'hide_empty' => true,
						'slug'       => $product_cats,
					);
					$prod_categories = get_terms( 'product_cat', $catargs);

					foreach( $prod_categories as $prod_cats ){
						$m++;
						$field_name = is_numeric( $product_cats[0] ) ? 'term_id' : 'slug';
						$args['tax_query'] = array(
							array(
								'taxonomy' => 'product_cat',
								'terms' => $prod_cats,
								'field' => $field_name,
								'include_children' => false
							),
						);
						if( 'featured' == $product_type ){
							$args['tax_query'][] = array(
								'taxonomy' => 'product_visibility',
								'field'    => 'name',
								'terms'    => 'featured',
								'operator' => 'IN',
							);
						}

					}
				}
			 };
		 if( is_array( $product_cats ) && (count( $product_cats ) > 0) && ( $producttab == 'yes' ) ):
                $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
                        )
                    );
                    if( 'featured' == $product_type ){
                        $args['tax_query'][] = array(
                            'taxonomy' => 'product_visibility',
                            'field'    => 'name',
                            'terms'    => 'featured',
                            'operator' => 'IN',
                        );
                    }
                    $products = new \WP_Query( $args );

                    if( $products->have_posts() ):
                    ?>
                <?php endif; endforeach;?>

            <?php else:?>
			<?php 			
			$k=1; 
            if( $products->have_posts() ): ?>
            <div class="container box_shop_5_amz">
			<?php if ($settings['title']): ?>
			<div class="row">
				<div class="col-12">
					<div class="head_card_box">
						<div class="head_card_title"><?php echo $settings['title']; ?></div>
						<a href="<?php echo $settings['more_link']['url']; ?>" class="head_card_more">
							<?php echo $settings['title_show_more']; ?>
							<i class="fal fa-arrow-left" aria-hidden="true"></i>
						</a>
					</div>
				</div>
			</div>
			<?php endif; ?>
            <section class="woo-list-slider-owl mb-3">
                <div class="boxs--slide amazonboxs--slide">
                    <div class="boxs--slide-container owl-carousel amazonslide owl-theme">
                    <?php while( $products->have_posts() ): $products->the_post(); ?>
                    <a href="<?php echo get_permalink() ?>">
                        <div class="item wrapper--products">
                            <div class="wrapper--products-slide woo-product-box">
                                <span href="<?php echo get_permalink() ?>" class="woo-product-box_img" title="<?php the_title() ?>">
                                <?php the_post_thumbnail( array(300, 300) , array('alt'=>''.get_the_title(),'title'=>''.get_the_title().'')); ?>
                                </span>
                            </div>
                        </div>
                        </a>
                    <?php $k++; endwhile; wp_reset_postdata(); ?>
                    </div>
                </div>
            </section>
            </div>
            <?php
					wp_reset_postdata();
				 endif;
			endif;
	}

}
