<?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_shop_by_brand') != true) 
{
	class kingdom_shop_by_brand extends WP_Widget 
	{
		private $the_theme = null;
		private $the_widget = array();
		private $alias = 'shop_by_brand';
		
	    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);
			}

			//add_action( 'pa_brand_add_form_fields', array( $this, 'add_new_meta_field' ), 10, 2 );
			add_action( 'pa_brand_edit_form_fields', array( $this, 'edit_meta_field' ), 10, 2 );

			add_action( 'edited_pa_brand', array( $this, 'save_taxonomy' ), 10, 2 );  
			add_action( 'create_pa_brand', array( $this, 'save_taxonomy' ), 10, 2 );

	    	add_filter( 'manage_pa_brand_custom_column', array( $this, 'add_column_content' ), 15, 3 );
	    	add_filter( 'manage_edit-pa_brand_columns',  array( $this, 'add_taxonomy_columns' ) );

			add_action( 'wp_ajax_kingdom_get_brands_by_id', array( $this, 'get_brands_by_id' ) );  
			add_action( 'wp_ajax_nopriv_kingdom_get_brands_by_id', array( $this, 'get_brands_by_id' ) );
	    }

	    function add_taxonomy_columns( $original_columns ) 
	    {
			$new_columns = $original_columns;
			array_splice( $new_columns, 1 );
			$new_columns['kingdom_taxonomy_image'] = esc_html__( 'Image', 'kingdom' );
			return array_merge( $new_columns, $original_columns );
		}

	    public function add_column_content( $row, $column_name, $term_id  )
	    {
	    	if ( 'kingdom_taxonomy_image' === $column_name ) {
	    		$attachment = (int) get_term_meta( $term_id, '_kingdom_attachment_image', true );
				if( $attachment > 0 ){
					$image = wp_get_attachment_image( $attachment, array( 300, 100 ) );
					echo $image;
				}
			}
			return $row;
	    }

	    public function save_taxonomy( $term_id )
	    {
	    	if( isset($_POST['kingdom-attachment-image']) && (int) $_POST['kingdom-attachment-image'] > 0 ){
	    		update_term_meta( $term_id, '_kingdom_attachment_image', $_POST['kingdom-attachment-image'] );
	    	}
	    }
		
	    public function upload_image( $input, $val )
	    {
	    	$html = array();

			$html[] = '<div class="' . ( $this->the_theme->alias ) . '-upload-box-wrapper">';
            $html[] =   '<div class="' . ( $this->the_theme->alias ) . '-upload-image">';

            $img_founded = false;
            if( (int)$val > 0 ){
            	$img_founded = true;
                $html[] = wp_get_attachment_image( $val, 'medium' );
            }
            $html[] =   '</div>';
            $html[] =   '<input type="hidden" class="' . ( $input ) . '" name="' . ( $input ) . '" value="' . ( (int)$val ) . '" />';

	        $html[] =   '<a href="#upload" target="blank" class="button button-primary ' . ( $this->the_theme->alias ) . '-upload-custom-img ' . ( $img_founded == true ? 'hidden' : '' ) . '">Upload Image</a>';
	         $html[] =   '<a href="#delete" target="blank" class="button button-primary ' . ( $this->the_theme->alias ) . '-delete-custom-img ' . ( $img_founded == false ? 'hidden' : '' ) . '">Delete Image</a>';
            $html[] = '</div>';

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

		public function edit_meta_field( $term )
		{
			$html = array();
	
			$html[] = '<tr class="form-field">';
			$html[] = 	'<th scope="row" valign="top"><label for="term_meta[custom_term_meta]">Brand logo</label></th>';
			$html[] = 	'<td>';

			$attachment = (int) get_term_meta( $term->term_id, '_kingdom_attachment_image', true );
			$html[] = 	$this->upload_image( $this->the_theme->alias . '-attachment-image', $attachment );

			$html[] = 		'<p class="description">Enter a value for this field</p>';
			$html[] = 	'</td>';
			$html[] = '</tr>';

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

		public function add_new_meta_field()
		{
			$html = array();

			$html[] = '<div class="' . ( $this->the_theme->alias ) . '-upload-box-wrapper">';
            $html[] =   '<div class="' . ( $this->the_theme->alias ) . '-upload-image">';

            $val = 0;
            if( (int)$val > 0 ){
                $html[] = wp_get_attachment_image( $val, array( '75', '75' ) );
            }
            $html[] =   '</div>';
            $html[] =   '<input type="hidden" name="' . ( $this->the_theme->alias ) . '-attachment-image" value="' . ( (int)$val ) . '" />';
            $html[] =   '<a href="#upload" target="blank" class="button button-primary ' . ( $this->the_theme->alias ) . '-upload-custom-img">Upload Image</a>';
            $html[] =   '<a href="#delete" target="blank" class="button button-primary ' . ( $this->the_theme->alias ) . '-delete-custom-img">Delete Image</a>';
            $html[] = '</div>';

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

		public function get_brands_by_id()
		{
			$brand_id = isset($_REQUEST['brand_id']) ? (int)$_REQUEST['brand_id'] : 0;

			if( $brand_id > 0 ){
				$term = get_term( $brand_id, 'product_cat' );
				die( $this->get_brands_by_categ( $term ) );
			}

			die("invalid term!");
		}

		public function get_brands_by_categ( $term )
		{
			$html = array();
			$prefix = $this->the_theme->db->prefix;
			$limit = 10;
			$product_cat = $term->term_id;

			$allterms= get_terms( 'product_cat', sprintf( 'orderby=count&hide_empty=0&fields=ids&child_of=%d', $product_cat ) );
			$allterms = ! empty($allterms) ? $allterms : array(0);
			$allterms = implode(', ', array_map(array($this, 'prepareForInList'), $allterms));
   
			//and tr2.object_id = tr.object_id
			$sql = "select t.term_id, t.name, count(tr.object_id) as nb from {$prefix}terms as t
				left join {$prefix}term_taxonomy as tt on t.term_id = tt.term_id
				left join {$prefix}term_relationships as tr on tr.term_taxonomy_id = tt.term_taxonomy_id
				where 1=1
				and tt.taxonomy = 'pa_brand'
				and tr.object_id IN (
				select tr2.object_id from {$prefix}term_relationships as tr2
				left join {$prefix}term_taxonomy as tt2 on tr2.term_taxonomy_id = tt2.term_taxonomy_id
				where 1=1
				and tt2.taxonomy = 'product_cat'
				and tt2.term_id IN ( $allterms )
				)
				group by t.term_id
				order by nb desc, t.term_id asc limit $limit;";
			//var_dump('<pre>', $sql, '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;


			$brands = $this->the_theme->db->get_results( $sql );

			if( count($brands) == 0 ){
				$html[] = '<div class="kd-show-by-brands-no-brands">No brands for category: <strong>' . ( $term->name ) . '</strong></div>';
			}else{
				if( $brands && count($brands) > 0 ){
					$html[] = '<ul class="kd-show-by-brands-list">';
					$cc = 0;
					$grid_size = 5;
					foreach ( $brands as $brand ) {
						$link = '';
						$add_logo_url = admin_url('term.php?taxonomy=pa_brand&tag_ID=' . ( $brand->term_id ) . '&post_type=product');
						$term = get_term( $brand->term_id, 'pa_brand' );
						$term_link = get_term_link( $term, 'pa_brand' );
						$extra_css_class = '';
						if( $cc == 0 ){
							$extra_css_class = 'kd-show-by-brands-zero-left';
						}

						elseif( $cc == ($grid_size - 1) ){
							$extra_css_class = 'kd-show-by-brands-zero-right kd-show-by-brands-no-vertical';
						}

						elseif( $cc > ceil($grid_size / 2) ){
							$extra_css_class = 'kd-show-by-brands-no-horizontal';
						}

						
						if( $cc == ( $grid_size * 2 - 1) ){
							$extra_css_class = 'kd-show-by-brands-no-vertical kd-show-by-brands-no-horizontal';
						}

						$html[] = '<li class="' . ( $extra_css_class ) . '">';

  						$attachment = (int) get_term_meta( $brand->term_id, '_kingdom_attachment_image', true );
						if( $attachment > 0 ){
							$image = wp_get_attachment_image( $attachment, array( 300, 150 ) );
							$html[] = 	'<a href="' . ( $term_link ) . '" class="kd-show-by-brands-image">';
							$html[] = 	$image;
							$html[] = 	'</a>';
						}else{
							$html[] = 	'<a href="' . ( $term_link ) . '" class="kd-show-by-brands-link-no-img">' . ( $brand->name ) . '</a>';
						}

						if( $attachment == 0 ){
							if(current_user_can('manage_options')) {
								$html[] = 	'<a href="' . ( $add_logo_url ) . '" target="_blank" class="kd-show-by-brands-no-img-admin">Add brand logo</a>';
							}
						}
						$html[] = '</li>';

						$cc++;
					}
					$html[] = '</ul>';
				}

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

		}

	    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)];

			$html = array();

			$html[] = $before_widget;
			$html[] = '<div class="container kd-show-by-brands">';
			$html[] = 	$before_title . ( str_replace( "\\", '', html_entity_decode($values['title']) ) ) . $after_title;
			$html[] = 	'<header>';
			$html[] = 		'<ul class="kd-show-by-brands-categs">';
			$html[] = 			'<li class="kd-show-by-brands-title">' . ( $values['title'] ) . '</li>';

			$first_categ = array();
			if( $values['select_order'] && count($values['select_order']) > 0 ){
				$cc = 0;
				foreach ($values['select_order'] as $term_id => $status) {

					if( $status == 'show' ){
						$term = get_term( $term_id, 'product_cat' );

						if( $term ){
							if( count($first_categ) == 0 ){
								$first_categ = $term;
							}

							$html[] = 		'<li><a data-termid="' . ( $term_id ) . '" href="#' . ( $term->slug ) . '" ' . ( $first_categ->term_id == $term_id ? 'class="kd_is_active"' : "" ) .'>' . ( $term->name ) . '</a></li>';
						}
					}

					$cc++;
				}
			}
			
			$html[] = 		'</ul>';
			//$html[] = 		'<a href="#show-all" class="kd-show-by-brands-show-all-btn">View All</a>';
			//$html[] = 		'<a href="#hide-all" class="kd-show-by-brands-hide-all-btn">Hide All</a>';
			$html[] = 	'</header>';

			$html[] = 	'<div class="kd-show-by-brands-ajax-response">' . ( $this->get_brands_by_categ( $first_categ ) ) . '</div>';

			$html[] = '</div>';
			$html[] = $after_widget;

			echo implode( "\n", $html );
	    }
	    
	    public function parse_output($instance)
	    {
	        $html = array();
	        
	        return implode("\n", $html);
	    }
	    
	    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] = $_REQUEST[$key];  
				}
	        } 
	        return $instance;
	    }
	
	    public function form( $instance ) 
	    { 
	    	echo $this->the_theme->print_widget_fields( $this->the_widget[$this->alias]['options'], $instance );
	    }
	    
		public function prepareForInList($v) {
			return "'".$v."'";
		}
	}
  	
  	
	// register the widgets
	add_action( 'widgets_init', create_function( '', 'return register_widget("kingdom_' . ( $current_widget ) . '");' ) );

	
}