<?php
namespace Elementor;

class Dina_Categories_Showcase extends Widget_Base {
	
	public function get_name() {
		return 'dina-categories-showcase';
	}
	
	public function get_title() {
		return __( 'Categories Showcase (Dinakala)', 'dina-kala' );
	}
	
	public function get_icon() {
		return 'fal fa-th';
	}

	public function get_help_url() {
		return 'https://i-design.ir/docs/dinakala/?p=3922';
	}
	
	public function get_categories() {
		return [ 'dina-kala' ];
	}
	
	protected function register_controls() {

		// Start Title Section
		$this->start_controls_section(
			'section_title',
			[
				'label' => __( 'Title settings', 'dina-kala' ),
			]
		);

		$this->add_control(
			'title',
			[
				'label'       => __( 'Title', 'dina-kala' ),
				'label_block' => true,
				'type'        => Controls_Manager::TEXT,
				'placeholder' => __( 'Enter your title', 'dina-kala' ),
				'default'     => __( 'Categories', 'dina-kala' ),
			]
		);

		$this->add_control(
			'icon',
			[
				'label'   => __( 'Icon', 'dina-kala' ),
				'type'    => 'dina_iconpicker',
				'default' => ''
			]
		);

		$this->add_control(
			'custom_icon',
			[
				'label' => __( 'Or custom icon (Suitable size: 32px by 32px)', 'dina-kala' ),
				'type'  => Controls_Manager::MEDIA,
			]
		);

		$this->add_control(
			'middle_title',
			[
				'label'        => __( 'Show title in the middle', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'title_tag',
			[
				'label'   => __( 'Block title tag', 'dina-kala' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'h2',
				'options' => [
					'div' => __( 'div', 'dina-kala' ),
					'h1'  => __( 'h1', 'dina-kala' ),
					'h2'  => __( 'h2', 'dina-kala' ),
					'h3'  => __( 'h3', 'dina-kala' ),
					'h4'  => __( 'h4', 'dina-kala' ),
				],
			]
		);

		$this->add_control(
			'white_title',
			[
				'label'        => __( 'White title (Suitable for background mode)', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		if ( dina_opt( 'dina_dark_mode' ) ) {
			$this->add_control(
				'dark_title',
				[
					'label'        => __( 'Dark title (Suitable for dark mode and white background)', 'dina-kala' ),
					'type'         => Controls_Manager::SWITCHER,
					'label_on'     => __( 'On', 'dina-kala' ),
					'label_off'    => __( 'Off', 'dina-kala' ),
					'return_value' => 'yes',
					'default'      => '',
				]
			);
		}

		$this->add_control(
			'remove_underline',
			[
				'label'        => __( 'Remove the title underline', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->add_control(
			'title_style',
			[
				'label'   => __( 'Block title style', 'dina-kala' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'default',
				'options' => [
					'default'           => __( 'Default', 'dina-kala' ),
					'line'              => __( 'Line', 'dina-kala' ),
					'short-line'        => __( 'Short line', 'dina-kala' ),
					'dashed-line'       => __( 'Dashed line', 'dina-kala' ),
					'dotted-line'       => __( 'Dotted line', 'dina-kala' ),
					'double-line'       => __( 'Double lines', 'dina-kala' ),
					'double-short-line' => __( 'Double short lines', 'dina-kala' ),
				],
				'condition' => [
					'remove_underline' => '',
				],
			]
		);

		$this->add_control(
			'inherit_color',
			[
				'label'        => __( 'Inheriting title border color from template color', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition' => [
					'remove_underline' => '',
				],
			]
		);

		$this->add_control(
			'title_border_color',
			[
				'label'     => __( 'Title border color', 'dina-kala' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#17A2B8',
				'selectors' => [
					'{{WRAPPER}} ' => '--dina-block-title-color: {{VALUE}}',
				],
				'condition' => [
					'inherit_color' => '',
				],
			]
		);

		$this->end_controls_section();
		// End Title Section

		// Start Products Section
		$this->start_controls_section(
			'section_products',
			[
				'label' => __( 'Products', 'dina-kala' ),
			]
		);

		$this->add_control(
			'taxonomy',
			[
				'label'   => __( 'Product taxonomy', 'dina-kala' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [
					'category' => __( 'Products category', 'dina-kala' ),
					'tag'      => __( 'Products tag', 'dina-kala' ),
					'brand'    => __( 'Products brand', 'dina-kala' )
				],
				'default' => 'category',
			]
		);

		$this->add_control(
			'product_cat',
			[
				'label'       => __( 'Categories', 'dina-kala' ),
				'description' => __( 'Select up to 4 categories to display.', 'dina-kala' ),
				'type'        => 'dina_autocomplete',
				'search'      => 'dina_get_taxonomies_by_query',
				'render'      => 'dina_get_taxonomies_title_by_id',
				'taxonomy'    => 'product_cat',
				'multiple'    => true,
				'label_block' => true,
				'condition'   => [
					'taxonomy' => 'category',
				],
			]
		);

		$this->add_control(
			'product_tag',
			[
				'label'       => __( 'Product tag', 'dina-kala' ),
				'description' => __( 'Select up to 4 tags to display.', 'dina-kala' ),
				'type'        => 'dina_autocomplete',
				'search'      => 'dina_get_taxonomies_by_query',
				'render'      => 'dina_get_taxonomies_title_by_id',
				'taxonomy'    => 'product_tag',
				'multiple'    => true,
				'label_block' => true,
				'condition'   => [
					'taxonomy' => 'tag',
				],
			]
		);

		if ( dina_opt( 'product_brand' ) ) {
			$this->add_control(
				'product_brand',
				[
					'label'       => __( 'Product brand', 'dina-kala' ),
					'description' => __( 'Select up to 4 brands to display.', 'dina-kala' ),
					'type'        => 'dina_autocomplete',
					'search'      => 'dina_get_taxonomies_by_query',
					'render'      => 'dina_get_taxonomies_title_by_id',
					'taxonomy'    => dina_opt( 'product_brand_taxonomy' ),
					'multiple'    => true,
					'label_block' => true,
					'condition'   => [
						'taxonomy' => 'brand',
					],
				]
			);
		}

		$this->add_control(
			'prod_sort',
			[
				'label'   => __( 'Product sorting', 'dina-kala' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'latest',
				'options' => [
					'latest'          => __( 'Latest products', 'dina-kala' ),
					'latest-updated'  => __( 'Latest updated products', 'dina-kala' ),
					'random'          => __( 'Random products', 'dina-kala' ),
					'viewed'          => __( 'Most viewed products', 'dina-kala' ),
					'saled'           => __( 'Best selling products', 'dina-kala' ),
					'price-desc'      => __( 'Price (Descending)', 'dina-kala' ),
					'price-asc'       => __( 'Price (Ascending)', 'dina-kala' ),
					'coming_soon'     => __( 'Coming soon products', 'dina-kala' ),
					'discounted'      => __( 'Discounted products', 'dina-kala' ),
					'rand_discounted' => __( 'Random discounted products', 'dina-kala' ),
					'special'         => __( 'Special products', 'dina-kala' ),
					'rand_special'    => __( 'Random special products', 'dina-kala' ),
					'menu_order'      => __( 'By title (Menu Order)', 'dina-kala' ),
				],
			]
		);

		$this->add_control(
			'out_prod',
			[
				'label'        => __( 'Show in stock products', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->add_control(
			'term_title_tag',
			[
				'label'   => __( 'Taxonomy title tag', 'dina-kala' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'h3',
				'options' => [
					'div' => __( 'div', 'dina-kala' ),
					'h1'  => __( 'h1', 'dina-kala' ),
					'h2'  => __( 'h2', 'dina-kala' ),
					'h3'  => __( 'h3', 'dina-kala' ),
					'h4'  => __( 'h4', 'dina-kala' ),
				],
			]
		);

		$this->add_control(
			'view_all',
			[
				'label'        => __( 'Display view all button', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->end_controls_section();
		// End Products Section

		// Start Style Section
		$this->start_controls_section(
			'style_section',
			[
				'label' => __( 'Style settings', 'dina-kala' ),
			]
		);

		$this->add_control(
			'white_box',
			[
				'label'        => __( 'White box style', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->end_controls_section();
		// End Style Section
	}

	public function dina_category_showcase_query( $prod_sort, $taxonomy, $terms, $out_prod ) {

		if ( empty( $terms ) || ! taxonomy_exists( $taxonomy ) ) {
			return new WP_Query();
		}

		$args = array(
			'posts_per_page'         => 4,
			'post_type'              => 'product',
			'post_status'            => 'publish',
			'no_found_rows'          => true,
			'update_post_term_cache' => false,
		);
	
		$tax_query = array(
			'relation' => 'AND',
			array(
				'taxonomy' => 'product_visibility',
				'field'    => 'name',
				'terms'    => 'exclude-from-catalog',
				'operator' => 'NOT IN',
			),
			array(
				'taxonomy' => $taxonomy,
				'field'    => 'term_id',
				'terms'    => $terms,
			),
		);
	
		switch ( $prod_sort ) {
			case 'latest':
				$args['order'] = 'DESC';
				break;
			case 'latest-updated':
				$args['orderby'] = 'modified';
				$args['order'] = 'DESC';
				break;
			case 'menu_order':
				$args['orderby'] = 'menu_order title';
				$args['order'] = 'ASC';
				break;
			case 'saled':
				$args['meta_key'] = 'total_sales';
				$args['orderby'] = 'meta_value_num';
				$args['order'] = 'DESC';
				break;
			case 'discounted':
				$args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
				$args['order'] = 'DESC';
				break;
			case 'coming_soon':
				$args['meta_key'] = 'dina_coming';
				$args['meta_value'] = 'on';
				$args['order'] = 'DESC';
				break;
			case 'rand_discounted':
				$args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
				$args['orderby'] = 'rand';
				break;
			case 'viewed':
				$meta_key = dina_opt( 'views_meta_key' );
				if ( ! empty( $meta_key ) ) {
					$args['meta_key'] = $meta_key;
					$args['orderby'] = 'meta_value_num';
					$args['order'] = 'DESC';
				}
				break;
			case 'price-desc':
				$args['meta_key'] = '_price';
				$args['orderby'] = 'meta_value_num';
				$args['order'] = 'DESC';
				break;
			case 'price-asc':
				$args['meta_key'] = '_price';
				$args['orderby'] = 'meta_value_num';
				$args['order'] = 'ASC';
				break;
			case 'random':
				$args['orderby'] = 'rand';
				break;
			case 'special':
				$tax_query[] = array(
					'taxonomy' => 'product_visibility',
					'field'    => 'name',
					'terms'    => 'featured',
				);
				$args['order'] = 'DESC';
				break;
			case 'rand_special':
				$tax_query[] = array(
					'taxonomy' => 'product_visibility',
					'field'    => 'name',
					'terms'    => 'featured',
				);
				$args['orderby'] = 'rand';
				break;
		}
	
		if ( 'yes' === $out_prod ) {
			$args['meta_query'] = array(
				'relation' => 'AND',
				array(
					'key'     => '_stock_status',
					'value'   => 'outofstock',
					'compare' => 'NOT IN',
				),
			);
		}
	
		$args['tax_query'] = $tax_query;
	
		return new \WP_Query( $args );
	}
	
	protected function render() {

        $settings = $this->get_settings_for_display();

		switch ( $settings['taxonomy'] ) {
			case 'category':
				$taxonomy = 'product_cat';
				$terms    = $settings['product_cat'];
				break;
			case 'tag':
				$taxonomy = 'product_tag';
				$terms    = $settings['product_tag'];
				break;
			case 'brand':
				$taxonomy = dina_opt( 'product_brand_taxonomy' );
				$terms    = $settings['product_brand'];
				break;
			default:
				$taxonomy = 'product_cat';
				$terms    = $settings['product_cat'];
		}

		$prod_sort = $settings['prod_sort'];
		$out_prod  = $settings['out_prod'];
		$terms     = is_array( $terms ) ? array_slice( $terms, 0, 4 ) : '';

		if ( ! empty( $terms ) ) {
			
			$block_classes  = 'dina-terms-showcase';
			$block_classes .= 'yes' === $settings['white_title'] ? ' white-title' : '';
			$block_classes .= 'yes' === $settings['white_box'] ? ' white-box' : '';
			$block_classes .= isset( $settings['dark_title'] ) && 'yes' === $settings['dark_title'] ? ' dark-title' : '';
			$block_classes .= 'yes' === $settings['middle_title'] ? ' dina-middle-title' : ' dina-right-title';

			$term_count  = count( $terms );
			switch ( $term_count ) {
				case 1:
					$col_class = 'col-12';
					break;
				case 2:
					$col_class = 'col-md-6 col-12';
					break;
				case 3:
					$col_class = 'col-md-4 col-12';
					break;
				case 4:
					$col_class = 'col-md-3 col-12';
					break;
				default:
					$col_class = 'col-md-3 col-12';
			}
		?>
			<div class="<?php echo $block_classes ?>">
				
				<?php if ( ! empty( $settings['title'] ) ) {
					
					$block_title_style = 'block-title-';
					if ( ! empty( $settings['remove_underline'] ) ) {
						$block_title_style .= 'none';
					} elseif ( ! empty( $settings['title_style'] ) && $settings['title_style'] != 'default' ) {
						$block_title_style .= $settings['title_style'];
					} else {
						$block_title_style .= dina_opt('block_title_style');
					}

					if ( 'yes' === $settings['middle_title'] ) {
						$block_title_style .= ' dina-center-title';
					}
				?>
					<div class="block-title <?= $block_title_style ?>">
						<?php echo ! isset ( $settings['title_tag'] ) ? '<h2 class="block-title-con">' : '<' . $settings['title_tag'] . ' class="block-title-con">'; ?>
							<?php if ( ! empty( $settings['custom_icon']['url'] ) ) { ?>
								<img src="<?php echo $settings['custom_icon']['url']; ?>" width="32" height="32" alt="<?php echo $settings['title']; ?>" class="cust-icon">
							<?php } elseif ( ! empty( $settings['icon'] ) ) { ?>
								<i class="fal fa-<?php echo $settings['icon']; ?>" aria-hidden="true"></i>
							<?php } ?>
							<?php echo $settings['title']; ?>
						<?php echo ! isset ( $settings['title_tag'] ) ? '</h2>' : '</' . $settings['title_tag'] . '>'; ?>
					</div>
				<?php } ?>

				<div class="row">

					<?php foreach ( $terms as $term_id ) {
						$term = get_term( $term_id, $taxonomy );
						if ( $term && ! is_wp_error( $term ) ) {
							$term_title = $term->name;
							$term_link  = get_term_link( (int)$term_id, $taxonomy );
						}
						
						$productsquery = $this->dina_category_showcase_query( $prod_sort, $taxonomy, $term_id, $out_prod );
					?>

					<div class="<?= $col_class ?> dina-terms-showcase-term">
					
						<?php

						$term_title_tag = isset( $settings['term_title_tag'] ) ? $settings['term_title_tag'] : 'h3';
						echo '<' . $term_title_tag . ' class="dina-terms-showcase-term-title">';
						echo esc_html( $term_title );
						echo '</' . $term_title_tag . '>';

						if ( $productsquery->have_posts() ) {
							echo '<div class="row">';
							while ( $productsquery->have_posts() ) :
								$productsquery->the_post();
								$product = wc_get_product( get_the_ID() );
								?>
									<div class="col-6 dina-terms-showcase-product">
										<a href="<?= esc_url( get_permalink( $product->get_id() ) ); ?>" title="<?= esc_html( $product->get_name() ) ?>">
											<?= $product->get_image('thumbnail'); ?>
										</a>
									</div>
								<?php
							endwhile;
							echo '</div>';
						} else {
							echo '<p>' . __( 'No products found.', 'dina-kala' ) . '</p>';
						}

						if ( 'yes' === $settings['view_all'] && $term_link && ! is_wp_error( $term_link ) ) {
							?>
							<a href="<?= esc_url( $term_link ); ?>" class="dina-terms-showcase-view-all"><?= __( 'View All', 'dina-kala' ); ?></a>
							<?php
						}
						wp_reset_postdata();
						?>
							
					</div>

					<?php } ?>
				</div>
			</div>
        <?php
		}
	}
}