<?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_browsing_history') != true) 
{
	class kingdom_browsing_history extends WP_Widget 
	{
		private $the_theme = null;
		private $the_widget = array();
		private $alias = 'browsing_history';
		
	    private $default_config = array(
	        'title' => ''
	    );
	    
	    public function __construct() 
	    {
			$this->the_theme = kingdom();
			$this->the_widget = $this->the_theme->cfg['widgets'][$this->alias];
			
			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);
			}
			// cookie is set in single-product.php
	    }

	    public function widget( $args, $instance ) 
	    {

	        extract( $args );
			
			$values = get_option( 'widget_' . ( $this->the_theme->alias ) . '-' . $this->alias );
			if( isset($values["_multiwidget"]) ) unset($values["_multiwidget"]);
			$values = $values[key($values)];

			$viewed_products = ! empty( $_COOKIE['kingdom_recently_viewed'] ) ? $_COOKIE['kingdom_recently_viewed'] : array();
			//die( var_dump( "<pre>", $viewed_products  , "</pre>" ) . PHP_EOL .  __FILE__ . ":" . __LINE__  ); 
			$viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );

			if ( empty( $viewed_products ) ) {
				return;
			}
			
			$number = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : 6;

			$query_args = array(
				'posts_per_page' => $number,
				'no_found_rows'  => 1,
				'post_status'    => 'publish',
				'post_type'      => 'product',
				'post__in'       => $viewed_products,
				'orderby'        => 'post__in',
			);

			if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
				$query_args['tax_query'] = array(
					array(
						'taxonomy' => 'product_visibility',
						'field'    => 'name',
						'terms'    => 'outofstock',
						'operator' => 'NOT IN',
					),
				);
			}

			$r = new WP_Query( $query_args );
			$html = array();
			if ( $r->have_posts() ) {
				$html[] = $before_widget;
				$html[] = '<div class="container kd-browsing-history">';
				$html[] = 	$before_title . ( str_replace( "\\", '', html_entity_decode($values['title']) ) ) . $after_title;
				$html[] = 	'<ul class="kd-nb-of-column-' . ( count($r->posts) ) . '">';
				while ( $r->have_posts() ) {
					$r->the_post();
					global $product;
					
					$html[] = '<li>';
					$html[] = 	'<a href="' . ( esc_url( $product->get_permalink() ) ) . '">';
					$html[] = 		$product->get_image();
					$html[] = 	'</a>';
					$html[] = '</li>';
				}
				$html[] = 	'</ul>';
				
				$html[] = '<div class="kd-browsing-history-cursor kd-nb-of-column-' . ( count($r->posts) ) . '">';
				$html[] = 	'<div class="kd-nb-of-column-' . ( count($r->posts) ) . ' kd-browsing-history-cursor-pointer"><i class="micon icon-arrow-up5"></i></div>';
				$html[] = '</div>';
				$html[] = '</div>';
				$html[] = $after_widget;

				echo implode( "\n", $html );
			}

			wp_reset_postdata();
	    }
	    
	    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 );
	    }
	}
  
	// register the widgets
	add_action( 'widgets_init', create_function( '', 'return register_widget("kingdom_' . ( $current_widget ) . '");' ) );
}