<?php

if( ! function_exists( 'kloud_get_default_product_shortcode_atts' ) ) {
	function kloud_get_default_product_shortcode_atts() {
		return array(
	        'post_type'  => 'product',
	        'layout' => 'grid',
	        'include'  => '',
	        'custom_query'  => '',
	        'taxonomies'  => '',
	        'pagination'  => '',
	        'items_per_page'  => 12,
	        'columns'  => 4,
	        'sale_countdown'  => 0,
	        'offset'  => '',
	        'orderby'  => 'date',
	        'order'  => 'DESC',
	        'meta_key'  => '',
	        'exclude'  => '',
	        'class'  => '',
            'space' => '30',
	        'ajax_page' => '',
			'speed' => '5000',
			'slides_per_view' => '1',
			'wrap' => '',
			'autoplay' => 'no',
            'hide_dots' => ' ',
			'hide_pagination_control' => '',
			'hide_prev_next_buttons' => '',
			'scroll_per_page' => 'yes',
			'carousel_js_inline' => 'no',
	        'img_size' => 'shop_catalog',
	        'force_not_ajax' => 'no',
	    );
	}
}



/**
* ------------------------------------------------------------------------------------------------
* Shortcode function to display posts teaser
* ------------------------------------------------------------------------------------------------
*/

if( ! function_exists( 'kloud_shortcode_posts_teaser' )) {
	function kloud_shortcode_posts_teaser($atts, $query = false) {
		global $woocommerce_loop;
		$posts_query = $el_class = $args = $my_query = $title_out = $output = '';
		$posts = array();
		extract( shortcode_atts( array(
			'el_class' => '',
			'posts_query' => '',
			'style' => 'default',
			'title' => '',
		), $atts ) );

		if( ! $query ) {
			list( $args, $query ) = vc_build_loop_query( $posts_query ); //
		}

		$carousel_id = 'teaser-' . rand(100,999);

		if( $title != '' ) {
			$title_out = '<h3 class="title teaser-title">' . $title . '</h3>';
		}

		ob_start();

		if($query->have_posts()) {
			echo wp_kses_post($title_out);
			?>
				<div id="<?php echo esc_html( $carousel_id ); ?>">
					<div class="posts-teaser teaser-style-<?php echo esc_attr( $style ); ?> <?php echo esc_attr( $el_class ); ?>">

						<?php
							$_i = 0;
							while ( $query->have_posts() ) {
								$_i++;
								$query->the_post(); // Get post from query
								?>
									<div class="post-teaser-item teaser-item-<?php echo esc_attr( $_i ); ?>">

										<?php if( has_post_thumbnail() ) {
											?>
												<a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_post_thumbnail( ( $_i == 1 ) ? 'large' : 'medium' ); ?></a>
											<?php
										} ?>

										<a href="<?php echo esc_url( get_permalink() ); ?>" class="post-title"><?php the_title(); ?></a> 

										<?php kloud_post_meta(array(
											'author' => 0,
											'labels' => 1,
											'cats' => 0,
											'tags' => 0
										)); ?>

									</div>
								<?php
							}	
						?>

					</div> <!-- end posts-teaser -->
				</div> <!-- end #<?php echo esc_html( $carousel_id ); ?> -->
				<?php

		}
		wp_reset_postdata();

		$output = ob_get_contents();
		ob_end_clean();

		return $output; 
	}

	insert_shortcode( 'kloud_posts_teaser', 'kloud_shortcode_posts_teaser' );
}



/**
* ------------------------------------------------------------------------------------------------
* Shortcode function to display posts as a slider or as a grid
* ------------------------------------------------------------------------------------------------
*/

if( ! function_exists( 'kloud_shortcode_posts' ) ) {

	function kloud_shortcode_posts( $atts ) {
		return kloud_generate_posts_slider( $atts );
	}

	insert_shortcode( 'kloud_posts', 'kloud_shortcode_posts' );
}

if( ! function_exists( 'kloud_generate_posts_slider' )) {
	function kloud_generate_posts_slider($atts, $query = false) {
		global $woocommerce_loop, $kloud_loop;
		$posts_query = $el_class = $args = $my_query = $speed = '';
		$slides_per_view = $wrap = $scroll_per_page = $title_out = '';
		$autoplay = $hide_pagination_control = $hide_prev_next_buttons = $output = '';
		$posts = array();

		$parsed_atts = shortcode_atts( array_merge( kloud_get_owl_atts(), array(
			'el_class' => '',
			'posts_query' => '',
	        'img_size' => 'large',
            'blog_layout' => '1',
			'title' => '',
            'review' => false,
            'like' => false,
            'thumbnail_show' => false,
		) ), $atts );

		extract( $parsed_atts );

		$kloud_loop['img_size'] = $img_size;
        $kloud_loop['blog_layout'] = $blog_layout;
        $kloud_loop['like'] = $like;
        $kloud_loop['review'] = $review;
        $kloud_loop[ 'thumbnail_show'] = $thumbnail_show;
		if( ! $query ) {
			list( $args, $query ) = vc_build_loop_query( $posts_query ); //
		}

		$carousel_id = 'carousel-' . rand(100,999);

		if( $title != '' ) {
			$title_out = '<h3 class="title slider-title">' . $title . '</h3>';
		}
        if ( $blog_layout == '1' ){ $layout = "default"; }else {
            $layout = "border-bottom";
        }
		ob_start();

		if($query->have_posts()) {
			echo wp_kses_post($title_out);
			?>
				<div id="<?php echo esc_attr( $carousel_id ); ?>" class="vc_carousel_container kloud-blog-holder <?php echo esc_attr($layout); ?>">
					<div class="owl-carousel post-slider  product-items <?php echo esc_attr( $el_class ); if ($blog_layout == '2') echo "ct-margin" ?>">

						<?php
							while ( $query->have_posts() ) {
								$query->the_post(); // Get post from query
								?>
									<div class="product-item owl-carousel-item">
										<div class="owl-carousel-item-inner">	
											<?php if ( $blog_layout == '1' ){ ?>
                                                <div class="post-item layout-1">
												<?php get_template_part( 'framework/templates/blog/entry' ); ?>
                                                </div>
											<?php } elseif ($blog_layout == '2') {?>
                                                <div class="post-item layout-2">
												<?php get_template_part( 'framework/templates/blog/entry2' ); ?>
                                                </div>
											<?php }  ?>

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

							unset( $woocommerce_loop['slider'] );

						?>

					</div> <!-- end product-items -->
				</div> <!-- end #<?php echo esc_html( $carousel_id ); ?> -->

			<?php

				$parsed_atts['carousel_id'] = $carousel_id;
				kloud_owl_carousel_init( $parsed_atts );

		}
		wp_reset_postdata();
		unset($kloud_loop['img_size']);

		$output = ob_get_contents();
		ob_end_clean();

		return $output; 
	}
}


/**
* ------------------------------------------------------------------------------------------------
* Shortcode function to display posts as a slider or as a grid
* ------------------------------------------------------------------------------------------------
*/

if( ! function_exists( 'kloud_shortcode_products' ) ) {
	insert_shortcode( 'kloud_products', 'kloud_shortcode_products' );
	function kloud_shortcode_products($atts, $query = false) {
		global $woocommerce_loop, $kloud_loop;
	    $parsed_atts = shortcode_atts( kloud_get_default_product_shortcode_atts(), $atts );

	    extract( $parsed_atts );

		$kloud_loop['img_size'] = $img_size;

	    $is_ajax = (defined( 'DOING_AJAX' ) && DOING_AJAX && $force_not_ajax != 'yes' );

	    $parsed_atts['force_not_ajax'] = 'no'; // :)

	    $encoded_atts = json_encode( $parsed_atts );

		$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

		if( $ajax_page > 1 ) $paged = $ajax_page;

		$ordering_args = WC()->query->get_catalog_ordering_args( $orderby, $order );

		$meta_query   = WC()->query->get_meta_query();

		if( $post_type == 'featured' ) {
			$meta_query[] = array(
				'key'   => '_featured',
				'value' => 'yes'
			);
		}

		if( $orderby == 'post__in' ) {
			$ordering_args['orderby'] = $orderby;
		}

	    $args = array(
	    	'post_type' 			=> 'product',
	    	'status' 				=> 'published',
			'ignore_sticky_posts' 	=> 1,
	    	'paged' 			  	=> $paged,	
			'orderby'             	=> $ordering_args['orderby'],
			'order'               	=> $ordering_args['order'],
	    	'posts_per_page' 		=> $items_per_page,
	    	'meta_query' 			=> $meta_query
		);

		if( ! empty( $ordering_args['meta_key'] ) ) {
			$args['meta_key'] = $ordering_args['meta_key'];
		}


		if( $post_type == 'ids' && $include != '' ) {
			$args['post__in'] = explode(',', $include);
		}

		if( ! empty( $exclude ) ) {
			$args['post__not_in'] = explode(',', $exclude);
		}

		if( ! empty( $taxonomies ) ) {
			$taxonomy_names = get_object_taxonomies( 'product' );
			$terms = get_terms( $taxonomy_names, array(
				'orderby' => 'name',
				'include' => $taxonomies
			));

			if( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
				$args['tax_query'] = array('relation' => 'OR');
				foreach ($terms as $key => $term) {
					$args['tax_query'][] = array(
				        'taxonomy' => $term->taxonomy,     
				        'field' => 'slug',                  
				        'terms' => array( $term->slug ),   
				        'include_children' => true,        
				        'operator' => 'IN'  
					);
				}
			}
		}

		if( ! empty( $order ) ) {
			$args['order'] = $order;
		}

		if( ! empty( $offset ) ) {
			$args['offset'] = $offset;
		}


		if( $post_type == 'sale' ) {
			$args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
		}

		if( $post_type == 'bestselling' ) {
			$args['orderby'] = 'meta_value_num';
			$args['meta_key'] = 'total_sales';
		}

		$woocommerce_loop['timer']   = $sale_countdown;


		$products                    = new WP_Query( $args );

		// Simple products carousel
		

		$woocommerce_loop['columns'] = $columns;
		$woocommerce_loop['masonry'] = false;
        if($columns =="2") {
            $vccolumns = "col-md-6 col-sm-6 col-xs-6";
            $columns_layout = "6";
        }elseif($columns == "3" ) {
            $vccolumns = "col-md-4 col-sm-6 col-xs-6";
            $columns_layout = "4";
        }elseif($columns == "4" ) {
           $vccolumns = "col-md-3 col-sm-6 col-xs-6" ;
           $columns_layout = "3";
        }elseif($columns == "5" ) {
           $vccolumns = " col-md-20 col-sm-6 col-xs-6" ; 
           $columns_layout = "20";
        }else {
             $vccolumns = " col-md-2 col-sm-6 col-xs-6" ; 
           $columns_layout = "2";
        }
        
		if ( $pagination == 'more-btn' ) {
			$woocommerce_loop['masonry'] = true;
		}

		if ( $pagination != 'arrows' ) {
			$woocommerce_loop['loop'] = $items_per_page * ( $paged - 1 );
		}
        $carousel_id = 'carousel-' . rand(100,999);
		$class .= ' pagination-' . $pagination;
		$class .= ' grid-columns-' . $columns;
		if( $woocommerce_loop['masonry'] ) {
			$class .= ' grid-masonry';
		}
        $classne = $data = $sizer = '';
        if ($layout != "carousel") {
       	$classne = ' jws-masonry';
       	$data  = 'data-masonry=\'{"selector":".tb-products-grid ", "columnWidth":".grid-sizer","layoutMode":"fitRows"}\'';
       	$sizer = '<div class="grid-sizer size-'.$columns_layout.'"></div>';
        }
		ob_start();

		if(!$is_ajax) echo '<div class="kloud-products-element ' .$pagination.'">';

	    if(!$is_ajax && $pagination != 'more-btn') echo '<div class="kloud-products-loader"><div class="overlay-loader">
                <div>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div></div>';
	    if(!$is_ajax) echo '<div class="products elements-grid row kloud-products-holder ' . esc_attr( $class) . ''.esc_attr( $classne ).'" data-paged="1" data-atts="' . esc_attr( $encoded_atts ) . '" '.wp_kses_post( $data ).' >';
		
		if ( $products->have_posts() ) : 
            if( $layout == 'carousel' ) echo '<div id="ptcarousel" ><div class="owl-carousel  product-items owl-theme owl-loaded"> ';
             echo wp_kses_post( $sizer );
			while ( $products->have_posts() ) :
			    
				$products->the_post();
				wc_get_template_part( 'content', 'productvc' ); 
    
                
			endwhile; 
            if( $layout == 'carousel' ) echo '</div></div> ';
		endif;

    	if(!$is_ajax) echo '</div>';

		woocommerce_reset_loop();
		wp_reset_postdata();

		if ( $products->max_num_pages > 1 && !$is_ajax ) {
			?>
		    	<div class="products-footer">
		    		<?php if ($pagination == 'more-btn'): ?>
		    			<a href="#" class=" kloud-products-load-more"><?php _e('Load More', 'kloud'); ?></a>
                        <p style="display: none;" class="loaded-all"><?php esc_html_e('All Product Loaded.' , 'kloud') ?></p>
		    		<?php elseif ($pagination == 'arrows'): ?>
		    			<a href="#" class="btn kloud-products-load-prev disabled"><?php _e('Prev', 'kloud'); ?></a>
		    			<a href="#" class="btn kloud-products-load-next"><?php _e('Next', 'kloud'); ?></a>
		    		<?php endif ?>
		    	</div>
                <div class="clear"></div>
		    <?php 
		}

    	if(!$is_ajax) echo '</div>';
        if ($layout == "carousel") {
           $items = array();
			$items['desktop'] = ($slides_per_view > 0) ? $slides_per_view : 1;
			$items['desktop_small'] = ($items['desktop'] > 1) ? $items['desktop'] - 1 : 1;
			$items['tablet'] = ($items['desktop_small'] > 1) ? $items['desktop_small'] -1 : 2;
			$items['mobile'] = ($items['tablet'] > 2) ? $items['tablet'] - 2 : 1;

			if($items['mobile'] > 2) {
				$items['mobile'] = 2;
			}

			?>
            
			<script type="text/javascript">
				jQuery( document ).ready(function( $ ) {

	                var owl = $("#ptcarousel .owl-carousel");

					$( window ).bind( "vc_js", function() {
						owl.trigger('refresh.owl.carousel');
					} );

					var options = {
	            		rtl: $('body').hasClass('rtl'),
			            items: <?php echo esc_js( $items['desktop'] ); ?>, 
			            responsive: {
			            	979: {
			            		items: <?php echo esc_js( $items['desktop'] ); ?>,
                                margin: 30,

			            	},
			            	768: {
			            		items: <?php echo esc_js( $items['desktop_small'] ); ?>,
                                margin: 10,
			            	},
			            	479: {
			            		items: <?php echo esc_js( $items['tablet'] ); ?>,
                                margin: 5,
			            	},
			            	0: {
			            		items: <?php echo esc_js( $items['tablet'] ); ?>,
                                margin: 0,
			            	}
			            },
			            autoplay: <?php echo wp_kses_post(($autoplay == 'no') ? 'true' : 'false'); ?>,
			            autoplayTimeout: <?php echo wp_kses_post(); ?>,
			            dots: <?php echo wp_kses_post(($hide_dots == 'yes') ? 'false' : 'true'); ?>,
			            nav: <?php echo wp_kses_post(($hide_prev_next_buttons == 'yes') ? 'false' : 'true'); ?>,
			            slideBy:  <?php echo wp_kses_post(($scroll_per_page == 'yes') ? '\'page\'' : 1); ?>,
			            navText:['<span class="ion-ios-arrow-thin-left"></span>','<span class="ion-ios-arrow-thin-right"></span>'],
			            loop: <?php echo wp_kses_post(($wrap == 'yes') ? 'true' : 'false'); ?>,
                        margin: <?php echo wp_kses_post($space); ?>,
			            onRefreshed: function() {
			            	$(window).resize();
			            }
					};

	                owl.owlCarousel(options);

				});
			</script>
           <?php
        
        }
        
		$output = ob_get_clean();

	    if( $is_ajax ) {
	    	$output =  array(
	    		'items' => $output,
	    		'status' => ( $products->max_num_pages > $paged ) ? 'have-posts' : 'no-more-posts'
	    	);
	    }
	    
	    return $output;

	}
}
