<?php
	wp_reset_postdata();
	$number    		= isset( $instance['numberposts'] ) ? intval($instance['numberposts']) : 5;
	if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
	
	global $product, $post, $woocommerce_loop,$wp_query;
	$related = $product->get_related( $number );
	if ( sizeof( $related ) == 0 ) return;
	$args = apply_filters( 'woocommerce_related_products_args', array(
		'post_type'            => 'product',
		'ignore_sticky_posts'  => 1,
		'no_found_rows'        => 1,
		'posts_per_page'       => $number,
		'post__in'             => $related,
		'post__not_in'         => array( $post->id )
	) );
	$num_post  = count($related);
	$relate = new WP_Query( $args );
	if ($relate->have_posts()) :
	$i = 0;
	$j = 0;
	$k = 0;
?>		
	<div id="<?php echo $widget_id; ?>" class="carousel slide sw-related-product" data-ride="carousel">
		<ul class="list-unstyled carousel-indicators">
		<?php while( $relate->have_posts() ) : $relate->the_post(); 
				if( $j % 3 == 0 ){
			?>
				<li data-target="#<?php echo $widget_id; ?>" data-slide-to="<?php echo $k; ?>" class="<?php if( $j == 0 ){echo 'active'; } ?>"></li>
				
			<?php $k++; } $j++;  endwhile; wp_reset_postdata(); ?>
		</ul>
		<div class="carousel-inner">
			<?php 
			while ($relate->have_posts()) : $relate->the_post();
			global $product, $post;
			$rating_count = $product->get_rating_count();
			$review_count = $product->get_review_count();
			$average      = $product->get_average_rating();
			if( $i % 3 == 0 ){ 
			?>
			<div class="item <?php if( $i == 0 ){ echo 'active'; } ?>">
			<?php } ?>
				<div class="item-detail">
					<div class="item-img">
						<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute();?>">
							<?php if( has_post_thumbnail() ){  
								echo (get_the_post_thumbnail( $relate->post->ID, 'shop_thumbnail')) ? get_the_post_thumbnail( $relate->post->ID, 'shop_thumbnail' ) : '<img src="'.get_template_directory_uri().'/assets/img/placeholder/shop_thumbnail.png" alt="No thumb"/>' ;
							}else{ 
								echo '<img src="'.get_template_directory_uri().'/assets/img/placeholder/shop_thumbnail.png" alt="No thumb"/>' ;
							} ?>
						</a>
					</div>
					<div class="item-content">
						<h4><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute();?>"><?php the_title(); ?></a></h4>
						<div class="star"><?php echo ( $average > 0 ) ?'<span style="width:'. ( $average*16 ).'px"></span>' : ''; ?></div>
						<p><?php echo $product->get_price_html(); ?></p>
						<div class="review">
							<span><?php echo $count; ?> <?php esc_html_e(' review(s)', 'furnicom'); ?></span>					
						</div>
					</div>
				</div>
			<?php if( ( $i+1 )%3==0 || ( $i+1 ) == $num_post  ){?> </div><?php } ?>
			<?php $i++; endwhile; ?>
		</div>
	</div>
			<?php
	endif;
	wp_reset_postdata();
?>