<?php

/**
 * 
 *
 * @version $Id$
 * @copyright 2003 
 **/

class rhc_color_key_shortcode {
	function rhc_color_key_shortcode(){
		add_shortcode( 'rhc_color_key', array(&$this,'handle_shortcode'));
	}
	function handle_shortcode($atts, $template=null, $code=""){
		extract(shortcode_atts(array(
			'calendar_id'			=> '',
			'container_class'		=> 'rhc rhc_color_key_container',
			'row_class'				=> 'row-fluid',
			'item_class'			=> '',
			'columns'				=> 3, //allowed columns 1, 2, 3, 4, 6, 12
			'taxonomy'				=> RHC_CALENDAR,
			'hide_empty'			=> '1',
			'orderby'				=> 'name',
			'order'					=> 'ASC',
			'parent'				=> '',
			'child_of'				=> 0,
			'feed'					=> '0',
			'counter'				=> '1'
		), $atts));
		
		foreach(array('hide_empty') as $bool_field){
			$$bool_field = '1'==$$bool_field?true:false;
		}
		foreach(array('parent','child_of') as $int_field){
			$$int_field = intval($$int_field);
		}
	
		$parent = 0==$parent?'':$parent;
	
		$orderby = in_array( $orderby, array('id','name','slug','count','none') )? $orderby : 'name';
		$order = 'desc'==strtolower($order) ? 'DESC' : 'ASC';		
		
		$columns = intval($columns);
		$columns = $columns<1 ? 1 : $columns;
		if( !in_array($columns,array(1,2,3,4,6,12))){
			$columns=3;
		}
		if(empty($item_class)){
			$columns = $columns>12?12:$columns;
			$span = 12/$columns;
			$item_class = 'span'.$span;
		}
		
		$taxonomies = array($taxonomy);
		
		$args = array(
		    'orderby'           => $orderby, 
		    'order'             => $order,
		    'hide_empty'        => $hide_empty, 
		    'exclude'           => array(), 
		    'exclude_tree'      => array(), 
		    'include'           => array(),
		    'number'            => '', 
		    'fields'            => 'all', 
		    'slug'              => '', 
		    'parent'            => $parent,
		    'hierarchical'      => true, 
		    'child_of'          => $child_of, 
		    'get'               => '', 
		    'name__like'        => '',
		    'description__like' => '',
		    'pad_counts'        => false, 
		    'offset'            => '', 
		    'search'            => '', 
		    'cache_domain'      => 'core'
		); 
		
		if( $feed=='1' || $counter!='1' ){
			$default = apply_filters('rhc_color_key_template', '<span class="rhc-color-key-term-color" style="background-color: {bgcolor};"></span><span>{name}</span>' );
		}else{
			$default = apply_filters('rhc_color_key_template', '<span class="rhc-color-key-term-color" style="background-color: {bgcolor};"></span><span>{name} ({count})</span>' );
		}
	
		$template = null===$template || empty($template) ? $default : $template;

		$out='';
		
		if( $feed=='1' && post_type_exists('rhc_source') ){
			$source_terms = $this->get_terms_by_post_type( $taxonomies, array('rhc_source') ) ;
			if( is_array($source_terms) && count( $source_terms ) > 0 ){
				$include = array();
				foreach( $source_terms as $t ){
					$include[] = $t->term_id;
				}
				$args['include'] = $include;		
			}
		}

		$terms = get_terms($taxonomies, $args);			
		if(is_array($terms) && count($terms)>0 ){
			$out.= sprintf('<div class="%s">', $container_class);
			$j=0;
			$total = count($terms);
			foreach($terms as $i => $t){
				if( 0==fmod($j,$columns) ){
					$out.= sprintf('<div class="%s">', $row_class );
				}

				$out.= sprintf('<div class="%s">%s</div>',
					$item_class,
					$this->inject_values( $template, $t )
				);			
				
				$j++;
				if( ($columns-1)==fmod(($j-1),$columns) || $j>=$total ){
					$out.='</div>';
				}
			}
			$out.='</div>';
		}
		
		return $out;
	}

	function get_terms_by_post_type( $taxonomies, $post_types ) {
	    global $wpdb;
	
	    $query = $wpdb->prepare(
	        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
	        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
	        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
	        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
	        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
	        GROUP BY t.term_id",
	        join( "', '", $post_types ),
	        join( "', '", $taxonomies )
	    );
	
	    $results = $wpdb->get_results( $query );
	
	    return $results;
	}
	
	function inject_values($template,$term){
		$term->bgcolor = get_term_meta($term->term_id, 'background_color', true);
		$term->bgcolor = empty($term->bgcolor) ? 'transparent' : $term->bgcolor;	
		foreach(array('term_id','name','slug','taxonomy','count','bgcolor') as $field){
			$replace = '{'.$field.'}';
			$template = str_replace($replace, $term->$field, $template);
		}
		return $template;
	}
}
?>