<?php

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

class rhc_venue_map_directory {
	var $request_md5=false;
	function __construct(){
		add_filter('get_calendarize_args_options', array(&$this,'get_calendarize_args_options'), 10, 2);
		
		add_action('wp_ajax_rhc_venue_directory', array(&$this,'get_venues'));
		add_action('wp_ajax_nopriv_rhc_venue_directory', array(&$this,'get_venues'));
		
		//TODO: when saving event, clear cache related to venue.
	}
	
	function get_calendarize_args_options( $options, $atts ){
		
		//
		$atts['venue_directory'] = isset($atts['venue_directory'])?$atts['venue_directory']:'';
		if( isset($atts['venue_directory_terms']) && !empty($atts['venue_directory_terms']) ){
			$extra_args='&terms='.$atts['venue_directory_terms'];
		}else{
			$extra_args='';
		}
		
	 	$json_feed = (object)array(
			'url'	=> admin_url('/admin-ajax.php?action=rhc_venue_directory'.$extra_args),
			'color'	=> '',
			'textColor' => '',
			'fc_click_target'=>'_self',
			'terms'	=> array(),
			'rhc_feed' => 0,
			'venue_directory'=>1
		);
		foreach($options->modes as $i => $m){
			switch( $atts['venue_directory'] ){
				case '1':
					$options->modes[$i]['options']->json_only = '1';
					$options->modes[$i]['options']->json_feed = array( $json_feed );
					break;
				case '2':
					$options->modes[$i]['options']->json_feed[]=$json_feed;
			}
			$options->modes[$i]['options']->gmap_view->venue_link_label = isset($atts['venue_link_label']) ? $atts['venue_link_label'] : __('Get more information','rhcmap');
			$options->modes[$i]['options']->gmap_view->venue_link_target = isset($atts['venue_link_target']) ? $atts['venue_link_target'] : '_blank';

		}				
		return $options;
	}

	function get_venues(){
		global $rhc_plugin;
		$directory_label = $rhc_plugin->get_option('directory_label', __('Business directory','rhc'), true );
		$parent_venue_label = $rhc_plugin->get_option('parent_venue_label', __('Category','rhc'), true );
		//$this->handle_rhc_cache( $_REQUEST );			
		$event = array(
			'id' 			=> 'business-directory',
			'venue_directory' => 1,
			'title' 		=> 'Business directory',
			'start' 		=> date('Y-m-d H:i:s'),
			'end' 			=> date('Y-m-d H:i:s'),
			'url' 			=> site_url('/'),
			'description'	=> '',
			'image'			=> '',
			'terms'			=> array(),
			'fc_click_link' => 'view',
			'fc_rdate'		=> '', 
			'fc_exdate'		=> '', 
			'allDay'		=> '1', 
			'fc_start'		=> '',
			'fc_start_time'	=> '',
			'fc_end'		=> '',
			'fc_end_time'	=> '', 
			'fc_interval'	=> '',
			'fc_rrule'		=> '',
			'fc_end_interval'=>'',
			'fc_color'		=> '',
			'fc_text_color'	=>'',
			'fc_click_link' =>'',
			'fc_click_target'=>'',
			'local_feed'	=> 1		
		);
	
		$taxonomy = RHC_VENUE;
	
		$args = array(
			'hide_empty' => 0
		);
	
		$parent_term_ids = array();
		if( isset($_REQUEST['terms']) && !empty($_REQUEST['terms']) ){
			$parent_terms = explode(',', str_replace(' ','',$_REQUEST['terms']) );
			if(count($parent_terms)>0){
				foreach( $parent_terms as $slug){
					if( $t = get_term_by('slug', $slug, $taxonomy) ){
						$parent_term_ids[]=$t->term_id;
					}
				}
			}
		}
		
		if(count($parent_term_ids)>0){
			$terms=array();
			foreach($parent_term_ids as $term_id){
				$args['child_of']=$term_id;
				if($tmp = get_terms(array($taxonomy), $args)){
					$terms = array_merge($terms,$tmp);				
				}
			}
		}else{
			$terms =	get_terms(array($taxonomy), $args);
		}
		
		$parents = array();
		if(count($terms)>0){
			foreach($terms as $t){
				if( !isset($parents[$t->parent]) ){
					if($tmp=get_term($t->parent,$t->taxonomy)){
						$parents[$t->parent]=$tmp;
					}
				}
			}
		}
		/*
		foreach($terms as $term){
			$url 		= get_term_link( $term, $taxonomy );
			
			$new = (object)array(
				'term_id'			=> $term->term_id,
				'taxonomy'			=> $taxonomy,
				'taxonomy_label'	=> $directory_label,
				'slug'				=> $term->slug,
				'name'				=> $term->name,
				'url'				=> $url
			);
			
			foreach(array('color', 'background_color', 'gaddress', 'glat', 'glon', 'image', 'address','city','state','zip','country') as $meta){
				$new->$meta = get_term_meta($term->term_id,$meta,true);
			}
						
			$event['terms'][]=apply_filters('rhc_event_term_meta', $new, $term->term_id, $taxonomy);
		}
		$events = array($event);
		*/
		$events = array();
		foreach($terms as $term){
			$url 		= get_term_link( $term, $taxonomy );
			$image		= get_term_meta($term->term_id, 'image', true);
			$content 	= get_term_meta($term->term_id, 'content', true);
			$content	= wpautop( $content, true );
			
			$new_event = $event;
			$new_event['title'] = $term->name;
			$new_event['description'] = $content;
			$new_event['url']	= $url;
			$new_event['image'] = array($image,0,0,false);
			
			$new = (object)array(
				'term_id'			=> $term->term_id,
				'taxonomy'			=> $taxonomy,
				'taxonomy_label'	=> $directory_label,
				'slug'				=> $term->slug,
				'name'				=> $term->name,
				'url'				=> $url,
				'venue_directory'	=> 1,
				'content'			=> $content
			);
			
			foreach(array('color', 'background_color', 'gaddress', 'glat', 'glon', 'image', 'address','city','state','zip','country') as $meta){
				$new->$meta = get_term_meta($term->term_id,$meta,true);
			}
			
			$add_parent_venue = ( empty($new->gaddress) && empty($new->glat) && empty($new->glon) ) ? false : true ;
			if(false===$add_parent_venue){
				continue;
			}
						
			$new_event['terms'][]=apply_filters('rhc_event_term_meta', $new, $term->term_id, $taxonomy);
			//--
			$custom_filter = get_term_meta($term->term_id,'custom_filter',true);
			if(is_array($custom_filter) && count($custom_filter)>0 ){
				foreach($custom_filter as $custom_taxonomy => $cust){
					if( $custom_t = get_taxonomy( $custom_taxonomy ) ){
				
						if(is_array($cust) && count($cust)>0 ){
							foreach($cust as $cust_slug){
								if( $cust_term = get_term_by('slug', $cust_slug, $custom_taxonomy) ){	
									$cust_term->taxonomy_label = $custom_t->labels->singular_name;
									//$new_event['terms'][]=apply_filters('rhc_event_term_meta', $cust_term, $cust_term->term_id, $custom_taxonomy);	
									$new_event['terms'][] = $cust_term ;						
								}
	
							}					
						}					
					}

				}
			}
			
			if($add_parent_venue && $term->parent>0 && isset($parents[$term->parent])){
				$cust_term = $parents[$term->parent];
				$cust_term->taxonomy = 'parent_venue';
				$cust_term->taxonomy_label = $parent_venue_label;
				$new_event['terms'][] = $cust_term;
			}
			/*
			echo "<pre>";
			print_r($term);
			print_r($new_event);
			echo "</pre>";	
			*/
			//--
			$events[]=$new_event;
		}
		
/*

*/
/*
		echo "<pre>";
		print_r($events);
		//print_r($event['terms']);
		echo "</pre>";
	*/				
	
		$this->send_response( $events );								
	}
	
	function handle_rhc_cache($request){
		global $rhc_plugin,$wpdb;
		if('1'==$rhc_plugin->get_option('disable_rhc_cache','',true))return;
		
		$request['_']='cache';
		$this->request_md5 = md5(serialize($request));	

		$minutes = intval($rhc_plugin->get_option('rhc_cache_minutes','10080',true));//default to a week.
		if($minutes==0)return;

		$user_id = ('1'==$rhc_plugin->get_option('rhc_cache_by_user','',true)) ? intval(get_current_user_id()) : 0 ;
		
		$sql = "SELECT `response` FROM `{$wpdb->prefix}rhc_cache` C ";
		$sql.= " WHERE (1)";
		$sql.= " AND( `request_md5`='{$this->request_md5}')";
		$sql.= " AND( `user_id`={$user_id} )";
		$sql.= " AND( DATE_ADD(C.cdate, INTERVAL $minutes MINUTE) > NOW() )";
		$sql = "SELECT COALESCE(($sql),'')";
		$cached_response = $wpdb->get_var($sql,0,0);
		if(!empty($cached_response)){
			die($cached_response);
		}
	}
	
	function send_response($response){
		global $rhc_plugin;
		if('1'==$rhc_plugin->get_option('ajax_catch_warnings','',true)){
			ob_end_clean();
		}
		if(false!==$this->request_md5){
			$encoded_response = json_encode($response);
			//---save
			try {
				global $wpdb,$rhc_plugin;
				$user_id = ('1'==$rhc_plugin->get_option('rhc_cache_by_user','',true)) ? intval(get_current_user_id()) : 0 ;
				$sql = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}rhc_cache` (`request_md5`,`user_id`,`cdate`,`action`,`response`)VALUES(%s,%d,NOW(),%s,%s) ON DUPLICATE KEY UPDATE cdate=NOW(),`response`=%s",
					$this->request_md5,
					$user_id,
					$_REQUEST['rhc_action'],
					$encoded_response,
					$encoded_response
				);
	
				if($wpdb->query($sql)){
				
				}else{
					
				}			
			}catch(Exception $e){
			
			}
			//----
		}else{
			$encoded_response = json_encode($response);
		}
		ob_start();
		echo $encoded_response;
		ob_end_flush();
		die();
	}	
}

/*
Array
(
    [0] => stdClass Object
        (
            [url] => http://localhost.com/wp36/?rhc_json_feed=265
            [color] => #992e83
            [textColor] => #feecfc
            [fc_click_target] => _blank
            [terms] => Array
                (
                )

            [rhc_feed] => 1
        )
)
*/
?>