<!--#!/usr/bin/php -q-->

<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd 
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	
	require('includes/sms_application_top.php');
	require(DIR_WS_CLASSES . 'currencies.php');

	$currencies=new currencies();

	$mail_status=array('E'=>'N','S'=>'N');
	
	$curdate=date('Y-m-d');
	//$curdate='2007-08-21';

	$current_time=date("H:i");
	$server_date = getServerDate(true);
	
	$time_split=(defined('EVENTS_EMAIL_TIMINGS')?split(",",EVENTS_EMAIL_TIMINGS):array());
	$offset=(int)EVENTS_SERVER_DATE_OFFSET;
	
	if (sizeof($time_split)>1 && $offset>=-23 && $offset<=23){
		$start_time="";
		$end_time="";
		//if ($time_split[0]>0) $start_time=date("H:i",tep_timeadd(strtotime($time_split[0]),'hr',$offset));
		//if ($time_split[1]>0) $end_time=date("H:i",tep_timeadd(strtotime($time_split[1]),'hr',$offset));
		if ($time_split[0]>0) $start_time=date("H:i",mktime(date('H')+abs($offset+$time_split[0])));
		if ($time_split[1]>0) $end_time=date("H:i",mktime(date('H')+abs($offset+$time_split[1])));
		$flag=0;
		if ($time_split[0]<=0 || $current_time>=$start_time) $flag++;
		if ($time_split[1]<=0 || $current_time<=$end_time) $flag++;
		if ($flag==2) $mail_status['E']='Y';
	}		
	$time_split=(defined('EVENTS_SMS_TIMINGS')?split(",",EVENTS_SMS_TIMINGS):array());
	$offset=(int)EVENTS_SERVER_DATE_OFFSET;
	if (sizeof($time_split)>1 && $offset>=-23 && $offset<=23){
		$start_time="";
		$end_time="";

		//if ($time_split[0]>0) $start_time=date("H:i",tep_timeadd(strtotime($time_split[0]),'hr',$offset));
		//if ($time_split[1]>0) $end_time=date("H:i",tep_timeadd(strtotime($time_split[1]),'hr',$offset));
		if ($time_split[0]>0) $start_time=date("H:i",mktime(date('H')+abs($offset+$time_split[0])));
		if ($time_split[1]>0) $end_time=date("H:i",mktime(date('H')+abs($offset+$time_split[1])));

		$flag=0;
		if ($time_split[0]<=0 || $current_time>=$start_time) $flag++;
		if ($time_split[1]<=0 || $current_time<=$end_time) $flag++;
		if ($flag==2) $mail_status['S']='Y';
	}
	if ((int)SMS_ACTIVATE!=1) $mail_status['S']='N';
	if ((int)EMAIL_ACTIVATE!=1) $mail_status['E']='N';
	
	if ($mail_status['E']!='Y' && $mail_status['S']!='Y'){
		error_notification("EMAIL & SMS Activation is False or Email Timings are Mismatched on Current Time");
		return;
	}


	$replace_array=array();
	$details=array();

	$templates_e=array();
	$templates_s=array();
	//get the email templates
	$email_query=tep_db_query("SELECT events_id,message_type,message_text,message_subject,message_send from " . TABLE_EVENTS_MESSAGES . " where message_type in('RNR','FDB') group by events_id,message_type");
	while($email_array=tep_db_fetch_array($email_query)){
		$temp=&new mesContent();
		$temp->content=$email_array["message_text"];
		$temp->subject=$email_array["message_subject"];
		$temp->sendtime=$email_array["message_send"];
		$temp->format=$email_array["message_format"];
		$templates_e[$email_array["events_id"]][$email_array["message_type"]]=$temp;
	}
	//get the sms templates
	$sms_query=tep_db_query("SELECT events_id,message_type,message_text,message_subject,message_send from " . TABLE_EVENTS_SMS_MESSAGES . " where message_type in('RNR','FDB','RSR') group by events_id,message_type");
	while($sms_array=tep_db_fetch_array($sms_query)){
		$temp=new mesContent();
		$temp->content=$sms_array["message_text"];
		$temp->subject=$sms_array["message_subject"];
		$temp->sendtime=$sms_array["message_send"];
		$temp->format='T';
		$templates_s[$sms_array["events_id"]][$sms_array["message_type"]]=$temp;
	}

	// check reservation start reminders
	$cur_type="RSR";
	if ($mail_status['S']=='Y') {
		$first_sql = "SELECT o.customers_id,s.events_id,min(s.start_date) as start_date,date_sub(min(s.start_date),interval es.message_send+0 day) as res_start_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o," . TABLE_EVENTS_SESSIONS . " s," . TABLE_EVENTS_SMS_MESSAGES . " es where o.orders_id=op.orders_id and op.products_id=s.sessions_id and es.events_id=s.events_id and es.message_type='RSR' and op.products_type='E' and op.events_type='R' group by o.customers_id,s.events_id having res_start_date='" . $curdate ."'";
		$first_query=tep_db_query($first_sql);

		while($first_result=tep_db_fetch_array($first_query)){
			if (isset($templates_s[$first_result["events_id"]][$cur_type])){
				$cur_template=$templates_s[$first_result["events_id"]][$cur_type];
				tep_send_automate_start_email($first_result["events_id"],$first_result["customers_id"],$first_result["res_start_date"]);
			}
		}
	}
	
	if ($mail_status['S']=='Y'){
		$third_sql = "SELECT o.customers_id,s.events_id,max(s.start_date) as end_date,case es.message_send when 'FLS' then max(s.start_date) when 'OBS' then date_add(max(s.start_date),interval -7 day) when 'TBS' then date_add(max(s.start_date),interval -14 day) when 'DFS' then date_add(max(s.start_date),interval 1 day) when 'OLS' then date_add(max(s.start_date),interval 7 day) when 'TLS' then date_add(max(s.start_date),interval 14 day) END as feed_start_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS_SMS_MESSAGES . 
									" es where o.orders_id=op.orders_id and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and s.events_id=es.events_id and es.message_type='FDB' and es.message_send in ('FLS','OBS','TBS','DFS','OLS','TLS') group by o.customers_id,s.events_id having feed_start_date='" . $curdate . "'";
		$third_query=tep_db_query($third_sql);
		while($third_result=tep_db_fetch_array($third_query)){
			if (isset($templates_s[$third_result["events_id"]][$cur_type])){
				$cur_template=$templates_s[$third_result["events_id"]][$cur_type];
				tep_send_automate_feedback_email($third_result["events_id"],$third_result["customers_id"],'S');
			}
		}
		$event_query=tep_db_query("SELECT s.events_id,es.message_send from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS_SMS_MESSAGES . " es where op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and s.events_id=es.events_id and es.message_type='FDB' and es.message_send in('SLS','DLS') group by s.events_id");
		while($event_result=tep_db_fetch_array($event_query)){
			if (isset($templates_s[$event_result["events_id"]][$cur_type])){
				$user_result_query=tep_db_query("SELECT o.customers_id,s.start_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
										" where s.events_id='" . $event_result['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id and op.products_id=s.sessions_id order by o.customers_id,s.start_date desc");
	
				$prev_customer=0;
				$session_position=($event_result["message_send"]=='SLS'?2:3);
				$cur_row=1;
				
				while($user_result=tep_db_fetch_array($user_result_query)){
					if ($prev_customer!=$user_result['customers_id']){
						$prev_customer=$user_result['customers_id'];
						$cur_row=1;
					}
					if ($cur_row==$session_position){
						if ($user_result['start_date']==$curdate) {
							$cur_template=$templates_s[$event_result["events_id"]][$cur_type];
							tep_send_automate_feedback_email($event_result["events_id"],$user_result["customers_id"],'S');
						}
					}
					$cur_row++;
				}
			}
		}		
	}$cur_type="FDB";
	if ($mail_status['E']=='Y'){
		$second_sql = "SELECT o.customers_id,s.events_id,max(s.start_date) as end_date,case em.message_send when 'FLS' then max(s.start_date) when 'OBS' then date_add(max(s.start_date),interval -7 day) when 'TBS' then date_add(max(s.start_date),interval -14 day) when 'DFS' 
									then date_add(max(s.start_date),interval 1 day) when 'OLS' then date_add(max(s.start_date),interval 7 day) when 'TLS' then date_add(max(s.start_date),interval 14 day) END as feed_start_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS_MESSAGES . " em where o.orders_id=op.orders_id and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and s.events_id=em.events_id and em.message_type='FDB' 
									and em.message_send in ('FLS','OBS','TBS','DFS','OLS','TLS') group by o.customers_id,s.events_id having feed_start_date='" . $curdate . "'";
		$second_query=tep_db_query($second_sql);

		while($second_result=tep_db_fetch_array($second_query)){
			if (isset($templates_e[$second_result["events_id"]][$cur_type])){
				$cur_template=$templates_e[$second_result["events_id"]][$cur_type];
				tep_send_automate_feedback_email($second_result["events_id"],$second_result["customers_id"],'E');
			}
		}
		$event_query=tep_db_query("SELECT s.events_id,em.message_send from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS_MESSAGES . " em where op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and s.events_id=em.events_id and em.message_type='FDB' and em.message_send in('SLS','DLS') group by s.events_id");
		while($event_result=tep_db_fetch_array($event_query)){
			if (isset($templates_e[$event_result["events_id"]][$cur_type])){
				$user_result_query=tep_db_query("SELECT o.customers_id,s.start_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
										" where s.events_id='" . $event_result['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id and op.products_id=s.sessions_id order by o.customers_id,s.start_date desc");
	
				$prev_customer=0;
				$session_position=($event_result["message_send"]=='SLS'?2:3);
				$cur_row=1;
				
				while($user_result=tep_db_fetch_array($user_result_query)){
					if ($prev_customer!=$user_result['customers_id']){
						$prev_customer=$user_result['customers_id'];
						$cur_row=1;
					}
					if ($cur_row==$session_position){
						if ($user_result['start_date']==$curdate) {
							$cur_template=$templates_e[$event_result["events_id"]][$cur_type];
							tep_send_automate_feedback_email($event_result["events_id"],$user_result["customers_id"],'E');
						}
					}
					$cur_row++;
				}
			}
		}
	}
	$cur_type="RNR";

	if ($mail_status['E']=='Y' || $mail_status['S']=='Y'){
		$fourth_sql = "SELECT o.customers_id,s.events_id,max(s.start_date) as end_date,case e.events_renewal_start when 'FLS' then max(s.start_date) when 'OBS' then date_add(max(s.start_date),interval -7 day) when 'TBS' then date_add(max(s.start_date),interval -14 day) when 'DFS' then date_add(max(s.start_date),interval 1 day) when 'OLS' 
									then date_add(max(s.start_date),interval 7 day) when 'TLS' then date_add(max(s.start_date),interval 14 day) END as renewal_start_date,case e.events_renewal_start when 'FLS' then date_add(max(s.start_date),interval e.events_renewal_end day) when 'OBS' then 
									date_add(max(s.start_date),interval -7+e.events_renewal_end day) when 'TBS' then date_add(max(s.start_date),interval -14+e.events_renewal_end day) when 'DFS' then date_add(max(s.start_date),interval 1+e.events_renewal_end day) when 'OLS' then date_add(max(s.start_date),interval 7+e.events_renewal_end day) when 'TLS' then 
									date_add(max(s.start_date),interval 14+e.events_renewal_end day) END as renewal_end_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e where o.orders_id=op.orders_id and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and 
									s.events_id=e.events_id and e.events_renewal_start in ('FLS','OBS','TBS','DFS','OLS','TLS') group by o.customers_id,s.events_id having renewal_start_date<='" . $curdate . "' and renewal_end_date>='" . $curdate . "'";
		$fourth_query=tep_db_query($fourth_sql);
		while($fourth_result=tep_db_fetch_array($fourth_query)){
			tep_send_automate_remind_email($fourth_result["events_id"],$fourth_result["customers_id"],$fourth_result["renewal_end_date"]);
		}
		$event_query=tep_db_query("SELECT s.events_id,e.events_renewal_start,e.events_renewal_end from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e where op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and s.events_id=e.events_id and e.events_renewal_start in('SLS','DLS') group by s.events_id");
		while($event_result=tep_db_fetch_array($event_query)){
			$user_result_query=tep_db_query("SELECT o.customers_id,s.start_date,date_add(s.start_date,interval " . $event_result["events_renewal_end"] . " day) as end_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
									" where s.events_id='" . $event_result['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id and op.products_id=s.sessions_id order by o.customers_id,s.start_date desc");

			$prev_customer=0;
			$session_position=($event_result["events_renewal_start"]=='SLS'?2:3);
			$cur_row=1;
			
			while($user_result=tep_db_fetch_array($user_result_query)){
				if ($prev_customer!=$user_result['customers_id']){
					$prev_customer=$user_result['customers_id'];
					$cur_row=1;
				}
				if ($cur_row==$session_position){
					if ($user_result['start_date']<=$curdate && $user_result['end_date']>=$curdate) {
						tep_send_automate_remind_email($event_result["events_id"],$user_result["customers_id"],$user_result["end_date"]);
					}
				}
				$cur_row++;
			}
		}		
	}
require('includes/application_bottom.php');

function tep_send_automate_start_email($events_id,$customers_id,$res_start_date)
{
	global $currencies,$curdate,$languages_id,$templates_s,$cur_template,$server_date;
	if ((int)$events_id<=0 || (int)$customers_id<=0){
		error_notification("Automate Start => Event Id :" . $events_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}
	$mes_text=$cur_template->content;
	if ($mes_text==""){
		error_notification("Automate Start => Template Content Text is Empty");
		return;
	}

	// check if previously sent
	$query=tep_db_query("SELECT count(*) as total from " . TABLE_EVENTS_MESSAGES_HISTORY . " where events_id='" . $events_id . "' and customers_id='" . $customers_id . "' and message_type='RSR' group by message_mode order by message_mode");
	$result=tep_db_fetch_array($query);
	
	if ($result['total']>0){
		error_notification("Automate Start => Record(s) of Event Id:" . $events_id . " and Customer Id:" . $customers_id . " found on Message History");
		return false;
	}
	
	// fetch customer details
	$customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_email_address,c.customers_second_email_address," . 
									"a.entry_street_address,a.entry_suburb,a.entry_postcode,a.entry_city,a.entry_state,a.entry_country_id,a.entry_zone_id from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK . " a where c.customers_id='" . $customers_id . "' and c.customers_default_address_id=a.address_book_id");
	
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Automate Start => Customer (Customer Id:" . $customers_id . ") Not Found");
		return;
	}

	$customer_result=tep_db_fetch_array($customer_query);

	$state=$customer_result["entry_state"];
	if ($state==""){
		$state=tep_get_zone_name($customer_result["entry_country_id"],$customer_result["entry_zone_id"],DEFAULT_ZONE);
	}
	$country=tep_get_country_name($customer_result["entry_country_id"]);
	if ($customer_result["customers_fax"]==""){
		error_notification("Automate Start => Customer Fax (Customer Id:" . $customers_id . ") is Empty");
		return;
	}

	//fetch event details	
	$event_query=tep_db_query(	"SELECT e.events_id,e.events_instructor,e.events_renewal_start,e.events_renewal_end,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time," .
								"e.events_location,e.events_tax_class_id,e.events_fees,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id='" . $events_id . "' and e.events_id=ed.events_id and ed.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Automate Start => Event (Event Id:" . $events_id . ") Not Found");
		return;
	}
	$event_result=tep_db_fetch_array($event_query);
	$events_location=tep_get_locations_name($event_result['events_location']);
		
	// prepare replace array
	$replace_array=array(	TEXT_FN=>$customer_result['customers_firstname'],
							TEXT_LN=>$customer_result['customers_lastname'],
							TEXT_DF=>format_date($customer_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$customer_result['customers_telephone'],
							TEXT_FX=>$customer_result['customers_fax'],
							TEXT_SA=>$customer_result['entry_street_address'],
							TEXT_SU=>$customer_result['entry_suburb'],
							TEXT_PC=>$customer_result['entry_postcode'],
							TEXT_CT=>$customer_result['entry_city'],
							TEXT_ST=>$state,
							TEXT_CY=>$country,
							TEXT_RE=>'',
							TEXT_EN=>$event_result['events_name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],tep_get_tax_rate($event_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_SD=>format_date($res_start_date),
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $events_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>'
						);

	$sql_array=array(	'orders_id'=>0,
						'events_id'=>$events_id,
						'customers_id'=>$customer_result["customers_id"],
						'message_type'=>'RSR',
						'message_mode'=>'S',
						'email_address'=>$customer_result["customers_email_address"],
						'send_date'=>$server_date
					);

	reset($replace_array);
	while (list($key, $value) = each($replace_array))
		$mes_text=eregi_replace("%%" . $key  . "%%",$value,$mes_text);
	
	$text = strip_tags($mes_text,'<br><BR>');
	$text = str_replace('<br>',chr(13) .chr(10),$text);
	$text = str_replace('<BR>',chr(13) .chr(10),$text);

	if (send_sms($customer_result['customers_fax'],$customer_result["customers_firstname"] . ' ' . $customer_result["customers_lastname"],$text,$country,true)){
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);	
	}
}
function tep_send_automate_feedback_email($events_id,$customers_id,$type){
	global $currencies,$languages_id,$cur_template,$server_date;
	
	if ((int)$events_id<=0 || (int)$customers_id<=0){
		error_notification("Automate Feedback => Event Id :" . $events_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}

	if ($cur_template->content==""){
		error_notification("Automate Feedback => Template Content Text is Empty");
		return;
	}
	
	$query=tep_db_query("SELECT message_mode from " . TABLE_EVENTS_MESSAGES_HISTORY . " where events_id='" . $events_id . "' and customers_id='" . $customers_id . "' and message_type='FDB' and message_mode='" . $type . "'");
	if (tep_db_num_rows($query)>0){
		error_notification("Automate Feedback => Record(s) of Event Id:" . $events_id . " and Customer Id:" . $customers_id . " found on Message History");
		return;
	}

	$customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_email_address,c.customers_second_email_address," . 
									"a.entry_street_address,a.entry_suburb,a.entry_postcode,a.entry_city,a.entry_state,a.entry_country_id,a.entry_zone_id from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK . " a where c.customers_id='" . $customers_id . "' and c.customers_default_address_id=a.address_book_id");
	
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Automate Feedback => Customer (Customer Id:" . $customers_id . ") Not Found");
		return;
	}
	$customer_result=tep_db_fetch_array($customer_query);

	$state=$customer_result["entry_state"];
	if ($state==""){
		$state=tep_get_zone_name($customer_result["entry_country_id"],$customer_result["entry_zone_id"],DEFAULT_ZONE);
	}
	$country=tep_get_country_name($customer_result["entry_country_id"]);
		
	
	$event_query=tep_db_query(	"SELECT e.events_id,e.events_instructor,e.events_renewal_end,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time," .
								"e.events_location,e.events_tax_class_id,e.events_fees,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id='" . $events_id . "' and e.events_id=ed.events_id and ed.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Automate Feedback => Event (Event Id:" . $events_id . ") Not Found");
		return;
	}
	$event_result=tep_db_fetch_array($event_query);
	$events_location=tep_get_locations_name($event_result['events_location']);
		
	$replace_array=array(	TEXT_FN=>$customer_result['customers_firstname'],
							TEXT_LN=>$customer_result['customers_lastname'],
							TEXT_DF=>format_date($customer_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$customer_result['customers_telephone'],
							TEXT_FX=>$customer_result['customers_fax'],
							TEXT_SA=>$customer_result['entry_street_address'],
							TEXT_SU=>$customer_result['entry_suburb'],
							TEXT_PC=>$customer_result['entry_postcode'],
							TEXT_CT=>$customer_result['entry_city'],
							TEXT_ST=>$state,
							TEXT_CY=>$country,
							TEXT_RE=>format_date($renewal_end),
							TEXT_EN=>$event_result['events_name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],tep_get_tax_rate($event_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $events_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
						);
	$sql_array=array(	'orders_id'=>0,
						'events_id'=>$events_id,
						'customers_id'=>$customer_result["customers_id"],
						'message_type'=>'FDB',
						'message_mode'=>$type,
						'email_address'=>$customer_result["customers_email_address"],
						'send_date'=>$server_date
					);


	if ($type=='E'){
		$details=array();
		$details['type']='FDB';
		$details['events_id']=$events_id;
	
		$details['format']=$cur_template->format;
		$details['html_text']=$cur_template->content;
		$details['subject']=$cur_template->subject;

		//replace content
		tep_replace_template($details,$replace_array);
		tep_strip_html($details);
	
		// get the address to send
		$details['to_name']=$customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'];
		$details['to_email']=$customer_result['customers_email_address'];
		$details['from_name']=STORE_OWNER;
		$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;

		if (tep_send_email($details)){
			tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
		}
	} else if ($customer_result['customers_fax']!="") {
		$mes_text=$cur_template->content;
		reset($replace_array);
		while (list($key, $value) = each($replace_array))
			$mes_text=eregi_replace("%%" . $key  . "%%",$value,$mes_text);
	
		$text = strip_tags($mes_text,'<br>');
		$text = str_replace('<br>',chr(13) .chr(10),$text);
		$text = str_replace('<BR>',chr(13) .chr(10),$text);

		if (send_sms($customer_result['customers_fax'],$customer_result["customers_firstname"] . ' ' . $customer_result["customers_lastname"],$text,$country,true)){
			$sql_array["message_mode"]="S";		
			tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);	
		}
	}
}

function tep_send_automate_remind_email($events_id,$customers_id,$renewal_date){
	global $currencies,$languages_id,$mail_status,$templates_s,$templates_e,$server_date;
	
	if ((int)$events_id<=0 || (int)$customers_id<=0){
		error_notification("Automate Remind => Event Id :" . $events_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}

	$mail_count=array('E'=>0,'S'=>0);
	$query=tep_db_query("SELECT count(*),message_mode from " . TABLE_EVENTS_MESSAGES_HISTORY . " where events_id='" . $events_id . "' and customers_id='" . $customers_id . "' and message_type='RNR' group by message_mode order by message_mode");
	while($result=tep_db_fetch_array($query)){
		$mail_count[$result["message_mode"]]=1;
	}

	$send_email=$send_sms=false;
	if (isset($templates_e[$events_id]['RNR']) && $mail_status['E']=='Y' && $mail_count['E']<=0){
		$email_template=$templates_e[$events_id]['RNR'];
		$send_email=true;
	}
	if (isset($templates_s[$events_id]['RNR']) && $mail_status['S']=='Y' && $mail_count['S']<=0){
		$sms_template=$templates_s[$events_id]['RNR'];
		$send_sms=true;
	}
	if (!$send_email && !$send_sms){
		error_notification("Automate Remind => Record(s) of Event Id:" . $events_id . " and Customer Id:" . $customers_id . " found on Message History");
		return;
	}
	$customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_email_address,c.customers_second_email_address," . 
									"a.entry_street_address,a.entry_suburb,a.entry_postcode,a.entry_city,a.entry_state,a.entry_country_id,a.entry_zone_id from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK . " a where c.customers_id='" . $customers_id . "' and c.customers_default_address_id=a.address_book_id");

	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Automate Remind => Customer (Customer Id:" . $customers_id . ") Not Found");
		return;
	}
	$customer_result=tep_db_fetch_array($customer_query);
	
	$state=$customer_result["entry_state"];
	if ($state==""){
		$state=tep_get_zone_name($customer_result["entry_country_id"],$customer_result["entry_zone_id"],DEFAULT_ZONE);
	}
	$country=tep_get_country_name($customer_result["entry_country_id"]);
	
	$event_query=tep_db_query(	"SELECT e.events_id,e.events_instructor,e.events_renewal_end,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time," .
								"e.events_location,e.events_tax_class_id,e.events_fees,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id='" . $events_id . "' and e.events_id=ed.events_id and ed.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Automate Remind => Event (Event Id:" . $events_id . ") Not Found");
		return;
	}
	$event_result=tep_db_fetch_array($event_query);
	$events_location=tep_get_locations_name($event_result['events_location']);	
	
	$replace_array=array(	TEXT_FN=>$customer_result['customers_firstname'],
							TEXT_LN=>$customer_result['customers_lastname'],
							TEXT_DF=>format_date($customer_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$customer_result['customers_telephone'],
							TEXT_FX=>$customer_result['customers_fax'],
							TEXT_SA=>$customer_result['entry_street_address'],
							TEXT_SU=>$customer_result['entry_suburb'],
							TEXT_PC=>$customer_result['entry_postcode'],
							TEXT_CT=>$customer_result['entry_city'],
							TEXT_ST=>$state,
							TEXT_CY=>$country,
							TEXT_RE=>format_date($renewal_date),
							TEXT_EN=>$event_result['events_name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],tep_get_tax_rate($event_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $events_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
						);

	$sql_array=array(	'orders_id'=>0,
						'events_id'=>$events_id,
						'customers_id'=>$customer_result["customers_id"],
						'message_type'=>'RNR',
						'message_mode'=>'E',
						'email_address'=>$customer_result["customers_email_address"],
						'send_date'=>$server_date
					);


	if ($send_email){
		$details=array();
		$details['type']='RNR';
		$details['events_id']=$events_id;
		$details['format']=$email_template->format;
		$details['html_text']=$email_template->content;
		$details['subject']=$email_template->subject;

		//replace content
		tep_replace_template($details,$replace_array);
		tep_strip_html($details);
	
		// get the address to send
		$details['to_name']=$customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'];
		$details['to_email']=$customer_result['customers_email_address'];
		$details['from_name']=STORE_OWNER;
		$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
		
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
		tep_send_email($details);
	} 
	if ($customer_result['customers_fax']!="" && $send_sms){
		$mes_text=$sms_template->content;
		if ($mes_text==""){
			error_notification("Automate Remind => Template Content Text is Empty");
			return;
		}
		reset($replace_array);
		while (list($key, $value) = each($replace_array))
			$mes_text=eregi_replace("%%" . $key  . "%%",$value,$mes_text);
		
		$text = strip_tags($mes_text,'<br>');
		$text = str_replace('<br>',chr(13) .chr(10),$text);
		$text = str_replace('<BR>',chr(13) .chr(10),$text);

		$sql_array["message_mode"]="S";
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);

		send_sms($customer_result['customers_fax'],$customer_result["customers_firstname"] . ' ' . $customer_result["customers_lastname"],$text,$country,true);
	}
}
function error_notification($error){
	global $HTTP_SERVER_VARS;
	$error_array = array(
						'cron_jobs_error_action' => basename($HTTP_SERVER_VARS['PHP_SELF']),
						'cron_jobs_error_text' => $error,
						'cron_jobs_error_date' => 'now()'
						);
	tep_db_perform(TABLE_CRON_JOBS_ERROR,$error_array);
}

class mesContent{
	var $content;
	var $subject;
	var $sendtime;
	var $format;
}
?>

