<?php 
// Make sure we don't expose any info if called directly
if ( ! function_exists( 'add_action' ) ) {
    die('Direct script access not allowed');
}

if(class_exists('kingdom_filter_amz_customer_reviews') != true) 
{
	class kingdom_filter_amz_customer_reviews extends WP_Widget 
	{
		private $the_theme = null;
		private $the_widget = array();
		private $alias = 'filter_amz_customer_reviews';
		
	    public function __construct() 
	    {
			$this->the_theme = kingdom();
			$this->the_widget = $this->the_theme->cfg['widgets'][$this->alias];
			
			add_filter( 'query_vars', array($this, 'add_query_vars_filter') );
			add_action( 'woocommerce_product_query', array( $this, 'amz_rating_query' ) );
			
			if( isset($this->the_widget) && count($this->the_widget) > 0 ){
				$widget_ops = array(
		            'classname'   => 'widget_' . $this->the_theme->alias . '_' . $this->alias, 
		            'description' => $this->the_widget[$this->alias]['description']
		        );
		        parent::__construct( $this->the_theme->alias . '-' . $this->alias, $this->the_theme->alias . ' - ' . $this->the_widget[$this->alias]['title'], $widget_ops);
			}
	    }

		function add_query_vars_filter( $vars ){
			$vars[] = "filter_amazon_rating";
			return $vars;
		}
		
		function amz_rating_query( $q ){
		
			$filtered_rating = get_query_var('filter_amazon_rating');
			if( isset($filtered_rating) && $filtered_rating > 0 ) {
			    $meta_query = $q->get( 'meta_query' );
				 
				$meta_query[] = array(
	                'key'       => '_kd_amz_rating',
	                'value' 	=> get_query_var('filter_amazon_rating'),
	                'compare'   => '>='
	            );
			
			    $q->set( 'meta_query', $meta_query );  
			}
		}
		
	    public function widget( $args, $instance ) 
	    {

	    	 extract( $args );
		?>
			<?php echo $before_widget;?>
				<h3><?php echo isset($instance['title']) ? $instance['title'] : '';?></h3>
				<?php
				// get current tag 
				$original_tags = get_query_var('filter_amazon_rating');
				 
				$tag_url_base = get_permalink( $this->the_theme->is_woocommerce ? wc_get_page_id( 'shop' ) : 0 ) . '?filter_amazon_rating=';
				
				$tags = array();
				if(trim($original_tags) != ""){
					$tags = explode(",", $original_tags);
				}
				  
				$retHtml = array();
				
				$reviews_nb = range(4, 0);
				
				echo '<ul>';
				foreach( $reviews_nb as $nb ) {
					
					$is_active = null;
					if(in_array($nb, $tags)) {
						$is_active = true;
					}
					  
					echo '<li><a href="#" ' . ( isset($is_active) ? 'class="active"' : '' ) . ' data-rating="' . ( $nb ) . '">' . ( $this->make_rating_stars($nb) ) . ' ' . esc_html__('& Up', 'kingdom') . ' ' . ($instance['show_count'] == 'on' ? '<span class="count">(' . $this->kd_count_amz_rating($nb) . ')</span>' : '') . '</a></li>';
				}
				echo '</ul>';
				?>
			<?php echo $after_widget;?>
			<?php 
	    }
	    
	    public function update( $new_instance, $old_instance )
	    {   
	        $instance = $old_instance;
	        // Strip tags from title and name to remove HTML 
	        if( count($this->the_widget[$this->alias]['options']) > 0 ){
	        	foreach ($this->the_widget[$this->alias]['options'] as $key => $value) {
					$instance[$key] = esc_html( $_REQUEST[$key] );  
				}
	        }
			 
	        return $instance;
	    }
	
	    public function form( $instance ) 
	    {
	    	echo $this->the_theme->print_widget_fields( $this->the_widget[$this->alias]['options'], $instance );
	    }
		
		public function kd_count_amz_rating( $stars )
		{
			global $wpdb;
			
			$rating_count = 0;
			  
			$ratings = $wpdb->get_col( $wpdb->prepare( "
		        SELECT pm.meta_value FROM {$wpdb->postmeta} pm
		        WHERE pm.meta_key = '%s' 
		    ", '_kd_amz_rating' ) );
			  
			foreach( $ratings as $rating ) {
				if( isset($rating) ) {
					$rating = round($rating);
					
					if( $rating >= $stars ) {    
						$rating_count++;
					}
				}
			}
			
			return $rating_count;
		}
		
		private function make_rating_stars( $rating )
		{
			$rating_width = intval($rating) * 20;
			return '<div class="star-rating"><span style="width:' . ( $rating_width ) . '%"></span></div>';
		}
	}
  
	// register the widgets
	add_action( 'widgets_init', create_function( '', 'return register_widget("kingdom_' . ( $current_widget ) . '");' ) );
}