<?php
/*
Element: Products Hot Deal
*/
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;

class PLS_Elementor_HotDealProducts extends PLS_Elementor_Widget_Base {
	/**
	 * Retrieve the widget name.
	 *
	 * @return string Widget name.
	 */
	public function get_name() {
        return 'pls-products-hotdeal';
    }

	/**
     * Get widget title.
     *
     * Retrieve Hot Deal Products widget title.
     *
     * @since 1.0.0
     * @access public
     *
     * @return string Widget title.
     */
    public function get_title() {
        return esc_html__( 'Products Hotdeal', 'modave-core' );
    }

    /**
     * Get widget icon.
     *
     * Retrieve Hot Deal Products widget icon.
     *
     * @since 1.0.0
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon() {
        return 'pls-icon eicon-countdown';
    }
	
	/**
	 * Get widget keywords.
	 *
	 * Retrieve the list of keywords the list widget belongs to.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return array Widget keywords.
	 */
	public function get_keywords() {
		return [ 'woocommerce', 'hot deal', 'products','deal of the day' ];
	}
	
	/**
     * Register Hot Deal Products widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function register_controls() {
		
		$this->start_controls_section(
            'content_section',
            [
                'label' => esc_html__( 'General', 'modave-core' ),
            ]
        );
		$this->add_control(
            'heading',
            [
                'label' 	=> esc_html__('Heading', 'modave-core'),
                'type' 		=> Controls_Manager::TEXT,
				'default' 	=> esc_html__( 'Deals Of the Day', 'modave-core' ),
            ]
        );
		$this->add_control(
            'layout',
            [
                'label' 	=> esc_html__( 'Layout', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'slider'	=> esc_html__( 'Slider', 'modave-core' ),
					'grid'		=> esc_html__( 'Grid', 'modave-core' ),
				],
                'default' 	=> 'slider',
            ]
        );
		$this->add_control(
            'product_deal_style',
            [
                'label' 	=> esc_html__( 'Products Deal Style', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'simple'			=> esc_html__( 'Simple Deal', 'modave-core' ),
					'deal-with-timer'	=> esc_html__( 'Deal With Timer', 'modave-core' ),
				],
                'default' 		=> 'simple',
				'description' 	=> esc_html__( 'Select product deal style.', 'modave-core' ),
            ]
        );
		$this->add_control(
            'deal_end_date',
            [
                'label' 	=> esc_html__('Deal End Date', 'modave-core'),
                'type' 		=> Controls_Manager::DATE_TIME,
				'condition' => [
					'product_deal_style' => [ 'deal-with-timer' ],
				],
				'description'	=> esc_html__( 'Enter deal end date like YYYY-MM-DD', 'modave-core' ),
            ]
        );
		$this->add_control(
            'hide_element',
            [
                'label' 	=> esc_html__('Hide Elements After Deal Ends.', 'modave-core'),
                'type' 		=> Controls_Manager::SWITCHER,
				'default' 	=> 0,
				'condition' => [
					'product_deal_style' => [ 'deal-with-timer' ],
				],
				'description' 	=> esc_html__( 'Hot deals section hide after end deal time.', 'modave-core' ),
            ]
        );
		$this->add_control(
            'product_view_mode',
            [
                'label' 	=> esc_html__( 'Product View Mode', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'vertical'		=> esc_html__( 'Vertical', 'modave-core' ),
					'horizontal'	=> esc_html__( 'Horizontal', 'modave-core' ),
				],
                'default' 	=> 'vertical',
            ]
        );
		$this->add_control(
            'product_style',
            [
                'label' 	=> esc_html__( 'Products Hover Style', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'default'			=> esc_html__( 'Default', 'modave-core' ),
					'product-style-1'	=> esc_html__( 'Products Hover Style 1', 'modave-core' ),
					'product-style-2'	=> esc_html__( 'Products Hover Style 2', 'modave-core' ),
					'product-style-3'	=> esc_html__( 'Products Hover Style 3', 'modave-core' ),
					'product-style-4'	=> esc_html__( 'Products Hover Style 4', 'modave-core' ),
					'product-style-5'	=> esc_html__( 'Products Hover Style 5', 'modave-core' ),
				],
                'default' 		=> 'default',
				'description' 	=> esc_html__( 'Select product hover style.', 'modave-core' ),
				'condition' => array(
					'product_view_mode' => 'vertical',
				),
            ]
        );
		$this->add_control(
			'product_border',
			[
				'label' 	=> esc_html__( 'Show Product Border', 'modave-core' ),
				'type' 		=> Controls_Manager::SWITCHER,
				'default' 	=> 0,
				'condition' => array(
					'product_view_mode' => 'horizontal',
				),
			]
		);
		$this->add_control(
			'show_stock_progressbar',
			[
				'label' 	=> esc_html__( 'Show Stock Progressbar', 'modave-core' ),
				'type' 		=> Controls_Manager::SWITCHER,
				'default' 	=> 0,
			]
		);
		$this->add_control(
			'show_countdown',
			[
				'label' 	=> esc_html__( 'Show Countdown', 'modave-core' ),
				'type' 		=> Controls_Manager::SWITCHER,
				'default' 	=> 'yes',
			]
		);
		$this->add_control(
			'show_view_more_button',
			[
				'label' 	=> esc_html__( 'Show View All Button', 'modave-core' ),
				'type' 		=> Controls_Manager::SWITCHER,
				'default' 	=> 'yes',
			]
		);
		$this->add_control(
			'view_more_button_text',
			[
				'label' 	=> esc_html__( 'View All Button Text', 'modave-core' ),
				'type' 		=> Controls_Manager::TEXT,
				'default' 	=> 'View All Deals',
				'condition' => [
					'show_view_more_button' => 'yes'
				],
			]
		);
		$this->add_control(
			'view_more_button_link',
			[
				'label' 	=> esc_html__( 'View More Button Link', 'modave-core' ),
				'type' 		=> Controls_Manager::URL,				
				'condition' => [
					'show_view_more_button' => 'yes'
				],
			]
		);
		$this->end_controls_section();
		
		$this->start_controls_section(
			'section_content_product_query',
			array(
				'label'     => esc_html__( 'Products Query', 'modave-core' ),
				'tab'       => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
            'data_source',
            [
                'label' 	=> esc_html__( 'Data source', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'sale_products'			=> esc_html__( 'On Sale Products', 'modave-core' ),	
					'hotdeal_products'		=> esc_html__( 'Schedule Products', 'modave-core' ),									
					'products'				=> esc_html__( 'List of Products', 'modave-core' ),
				],
                'default' 		=> 'sale_products',
				'description' 	=> esc_html__( 'Select data source for your product grid', 'modave-core' ),
            ]
        );
		$this->add_control(
            'product_ids',
            [
                'label'			=> esc_html__('Include Specific Products', 'modave-core'),
                'type'			=> 'pls_autocomplete',
				'search'		=> 'pls_core_elementor_search_post',
				'render'		=> 'pls_core_elementor_render_post',
				'post_type'		=> 'product',
				'multiple'		=> true,
				'label_block'	=> true,
				'description' 	=> esc_html__( 'Add product by title.', 'modave-core' ),
				'condition'		=> [
					'data_source'	=> [ 'products' ],
				],
            ]
        );
		$this->add_control(
            'categories',
            [
                'label'			=> esc_html__( 'Specific Category', 'modave-core' ),
                'type'			=> 'pls_autocomplete',
				'search'		=> 'pls_core_elementor_search_taxonomies',
				'render'		=> 'pls_core_elementor_render_taxonomies',
				'taxonomy'		=> array('product_cat'),
				'multiple'		=> true,
				'label_block'	=> true,
                'description'	=> esc_html__( 'Select specific categories.', 'modave-core' ),
            ]
        );
		
		$this->add_control(
            'limit',
            [
                'label' 	=> esc_html__('Number Of Products', 'modave-core'),
                'type' 		=> Controls_Manager::NUMBER,
				'default' 	=> 6,
            ]
        );
		$this->add_control(
            'orderby',
            [
                'label' 	=> esc_html__( 'Order By', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'date'	=> esc_html__( 'Date', 'modave-core' ),
					'title'	=> esc_html__( 'Title', 'modave-core' ),
					'name'	=> esc_html__( 'Name(Slug)', 'modave-core' ),
					'rand'	=> esc_html__( 'Random', 'modave-core' ),
					'ID'	=> esc_html__( 'ID', 'modave-core' ),
				],
				'default' 	=> 'date',
            ]
        );
		$this->add_control(
            'order',
            [
                'label' 	=> esc_html__( 'Sort By', 'modave-core' ),
                'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'DESC'	=> esc_html__( 'Descending', 'modave-core' ),
					'ASC'	=> esc_html__( 'Ascending', 'modave-core' ),
				],
				'default' 	=> 'DESC',
            ]
        );		
		$this->end_controls_section();
		
		$this->start_controls_section(
			'section_content_grid',
			array(
				'label'     => esc_html__( 'Grid Settings', 'modave-core' ),
				'tab'       => Controls_Manager::TAB_CONTENT,
				'condition' => array(
					'layout' => 'grid',
				),
			)
		);
		$this->add_responsive_control(
			'grid_columns',
			[
				'label'			=> esc_html__( 'Columns', 'modave-core' ),
				'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'1'		=> esc_html__( '1', 'modave-core' ),
					'2'		=> esc_html__( '2', 'modave-core' ),
					'3'		=> esc_html__( '3', 'modave-core' ),
					'4'		=> esc_html__( '4', 'modave-core' ),
					'5'		=> esc_html__( '5', 'modave-core' ),
					'6'		=> esc_html__( '6', 'modave-core' ),
					'7'		=> esc_html__( '7', 'modave-core' ),
				],
				'default' 			=> '4',
				'tablet_default' 	=> '3',
				'mobile_default' 	=> '2',
			]
		);		
		$this->end_controls_section();
		
		$this->start_controls_section(
			'section_content_slider',
			array(
				'label'     => esc_html__( 'Slider Settings', 'modave-core' ),
				'tab'       => Controls_Manager::TAB_CONTENT,
				'condition' => array(
					'layout' => 'slider',
				),
			)
		);
		$this->add_responsive_control(
			'slides_to_show',
			[
				'label'			=> esc_html__( 'Slides to Show', 'modave-core' ),
				'type' 		=> Controls_Manager::SELECT,
                'options' 	=> [
					'1'		=> esc_html__( '1', 'modave-core' ),
					'2'		=> esc_html__( '2', 'modave-core' ),
					'3'		=> esc_html__( '3', 'modave-core' ),
					'4'		=> esc_html__( '4', 'modave-core' ),
					'5'		=> esc_html__( '5', 'modave-core' ),
					'6'		=> esc_html__( '6', 'modave-core' ),
					'7'		=> esc_html__( '7', 'modave-core' ),
				],
				'default' 			=> '4',
				'tablet_default' 	=> '3',
				'mobile_default' 	=> '2',
			]
		);
		$this->add_control(
			'slider_autoplay',
			[
				'label'     => esc_html__( 'Autoplay', 'modave-core' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 0,
			]
		);
		$this->add_control(
			'slider_pause_on_hover',
			[
				'label'     => esc_html__( 'Pause On Hover', 'modave-core' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 0,
				'condition' => [
					'slider_autoplay' => [ 'yes' ],
				],
			]
		);
		$this->add_control(
			'slider_loop',
			[
				'label'     => esc_html__( 'Loop', 'modave-core' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 0,
			]
		);
		$this->add_control(
			'slider_navigation',
			[
				'label'     => esc_html__( 'Nav', 'modave-core' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
			]
		);
		$this->add_control(
			'slider_dots',
			[
				'label'     => esc_html__( 'Dots', 'modave-core' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 0,
			]
		);
		$this->end_controls_section();
		
		$this->start_controls_section(
			'heading_style_section',
			[
				'label' => esc_html__( 'Heading', 'modave-core' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);
		
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'heading_typography',
				'label'    => esc_html__( 'Typography', 'modave-core' ),
				'selector' => '{{WRAPPER}} .section-heading h2',
			]
		);
		
		$this->add_responsive_control(
			'heading_margin',
			[
				'label'			=> esc_html__( 'Margin Bottom', 'modave-core' ),
				'type'			=> Controls_Manager::SLIDER,
				'size_units' 	=> [ 'px' ],
				'range' 		=> [
					'px' 	=> [ 'min' => 10, 'max' => 100 ],
				],
				'selectors'		=> [
					'{{WRAPPER}} .section-heading' => 'margin-bottom: {{SIZE}}{{UNIT}};',
				],
			]
		);		
		$this->end_controls_section();
	}
	
	protected function render() {
		
		$settings = $this->get_settings();
		$settings = wp_parse_args( $settings, [ 
			'slides_to_show_tablet' 	=> 3,
			'slides_to_show_mobile' 	=> 2,
			'grid_columns_tablet' 		=> 3,
			'grid_columns_mobile' 		=> 2
		]);
		extract( $settings );
		
		$settings['id'] 	= pls_uniqid( 'pls-products-hotdeal-' );
		$class				= array( 'pls-element', 'pls-products-hotdeal', 'woocommerce' );
		$class[]	 		= ( $product_border ) ? 'pls-product-border' : '';
		
		$settings['show_view_more_button'] 	= $show_view_more_button ? true : false;
		$settings['view_all_btn']['url']	= 'href="'.wc_get_page_permalink( 'shop' ).'"';
		
		$settings['date'] 		= '';
		$settings['isToday']	= 'no';
		$settings['timezone'] 	= pls_timezone_string();
		if( ! empty( $deal_end_date ) ){
			$deal_end_date = date( 'Y-m-d H:i:s', strtotime( '+23 hours 59 minutes', strtotime( $deal_end_date ) ) );
			if( $hide_element && strtotime( $deal_end_date ) < time() ){
				return;
			}
			//echo date('Y.m.d');
			$isToday = date( 'Ymd' ) == date( 'Ymd', strtotime( $deal_end_date ) );
			if( $isToday ){
				$settings['isToday'] = 'yes';
			}
			$settings['date'] = $deal_end_date;
		} 
		
		//Get Products
        global $woocommerce_loop, $wpdb;
		$product_ids_on_sale = array();
		
		switch ( $data_source ) {
			case 'sale_products';
				$product_ids_on_sale   = wc_get_product_ids_on_sale();
				$product_ids_on_sale[] = 0;
				$product_ids_on_sale      = $product_ids_on_sale;
			break;
			case 'products';
				if ( is_array($product_ids) && !empty( $product_ids ) ) {
					$product_ids_on_sale = $product_ids;
				}elseif($product_ids != '' ) {
					$product_ids_on_sale = explode( ',', $product_ids );
				}
				break;
			case 'hotdeal_products';
				// Get products on sale
				$product_ids_raw = $wpdb->get_results(
				"SELECT posts.ID, posts.post_parent
				FROM `$wpdb->posts` posts
				INNER JOIN `$wpdb->postmeta` ON (posts.ID = `$wpdb->postmeta`.post_id)
				INNER JOIN `$wpdb->postmeta` AS mt1 ON (posts.ID = mt1.post_id)
				WHERE
					posts.post_status = 'publish'
					AND  (mt1.meta_key = '_sale_price_dates_to' AND mt1.meta_value >= ".time().") 
					GROUP BY posts.ID 
					ORDER BY posts.post_title" );

				$product_ids_on_sale = array();

				foreach ( $product_ids_raw as $product_raw ) {
					if( ! empty( $product_raw->post_parent ) ) {
						$product_ids_on_sale[] = $product_raw->post_parent;
					} else {
						$product_ids_on_sale[] = $product_raw->ID;  
					}
				}
				$product_ids_on_sale = array_unique( $product_ids_on_sale );
				$product_ids_on_sale = $product_ids_on_sale;
		}
		
		//Hot deal products
		$query_args = array(
						'post_type'				=> 'product',
						'post_status'			=> 'publish',
						'ignore_sticky_posts'	=> 1,
						'posts_per_page' 		=> $limit,
						'orderby' 			    => $orderby,
						'order' 				=> $order,
						'post__in'			    => array_merge( array( 0 ), $product_ids_on_sale ),
					);
		$meta_query		= WC()->query->get_meta_query();
		$tax_query   	= WC()->query->get_tax_query();	
		
		if( apply_filters( 'pls_hotdeal_hide_outofstock_products', true ) ){
			$tax_query[] = array(
				array(
					'taxonomy' => 'product_visibility',
					'field'    => 'name',
					'terms'    => 'outofstock',
					'operator' => 'NOT IN',
				),
			);
		}
		
		if( ! empty( $categories ) ):
			$tax_query[] = array(
				array(
					'taxonomy' => 'product_cat',
					'field'    => 'term_id',
					'terms'    => $categories
				)
			);		
		endif;
		
		$query_args['meta_query']	= $meta_query;
		$query_args['tax_query']	= $tax_query;
		$the_query 					= new WP_Query( $query_args );		
		$settings['query'] 			= $the_query;
		
		$link_url = '';		
		if( ! empty( $settings['view_more_button_link']['url']) ) {
			$link_url = pls_core_elementor_get_url_data( $settings['view_more_button_link'] );			
		}
		
		if ( ! empty( $settings['categories'] ) ) {	
			$term_link = get_term_link( (int)trim($categories[0]), 'product_cat' );
			if ( ! is_wp_error( $term_link ) ) {
				$settings['view_all_btn']['url'] 	= 'href="'.$term_link.'"';		
			}					
		}
		
		if( ! empty( $link_url['url'] ) ){
			$settings['view_all_btn'] 	= $link_url;
		}
		
		if( $product_style != 'default' ){
			pls_set_loop_prop( 'product-style', $product_style );
		}
		
		if( 'horizontal' == $product_view_mode ) {
			remove_action( 'woocommerce_before_shop_loop_item_title', 'pls_wc_product_sale_countdown', 15 );
			add_action( 'woocommerce_after_shop_loop_item', 'pls_wc_product_sale_countdown', 20 );
		}
		
		pls_set_loop_prop( 'products_view', 'grid-view' );
		pls_set_loop_prop( 'product_view_mode', $product_view_mode );
		if( 'grid' == $layout ){
			pls_set_loop_prop( 'products-columns', $grid_columns );
			pls_set_loop_prop( 'products-columns-tablet', $grid_columns_tablet );
			pls_set_loop_prop( 'products-columns-mobile', $grid_columns_mobile );
			wc_set_loop_prop( 'columns', $grid_columns );
			
		}else{
			$unique_id 		= pls_uniqid( 'section-' );
			pls_set_loop_prop( 'name', 'pls-slider' );
			pls_set_loop_prop( 'products-columns', $slides_to_show );
			pls_set_loop_prop( 'slider_navigation', $slider_navigation );
			pls_set_loop_prop( 'slider_dots', $slider_dots );
			pls_set_loop_prop( 'slides_to_show', $slides_to_show );
			pls_set_loop_prop( 'slides_to_show_tablet', $slides_to_show_tablet );
			pls_set_loop_prop( 'slides_to_show_mobile', $slides_to_show_mobile );
			pls_set_loop_prop( 'unique_id', $unique_id );
			pls_set_loop_prop( 'slider_options', pls_slider_attributes( $settings) );
		}
		
		pls_set_loop_prop( 'product-countdown', 0 );
		
		if( $show_countdown == 'yes' ){
			pls_set_loop_prop( 'product-countdown', 1 );
		}
		
		if( $show_stock_progressbar ){
			pls_set_loop_prop( 'products-stock-progressbar', 1 );
		}
		
		$settings['class'] 			= implode( ' ', array_filter( $class ) );
		
		pls_init_woocommerce_loop_hook();
		pls_core_get_templates( 'elements-widgets/woo-products-hotdeal', $settings );
	}
}

$widgets_manager->register( new PLS_Elementor_HotDealProducts() );