<!--#!/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=getServerDate();
	//$curdate = "2007-07-24";
	$server_date = getServerDate(true);
		
	$current_time=date("H:i");
	$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'; 
	}
	$mail_status['S']='Y';
	$mail_status['E']='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 service_id,message_type,message_text,message_subject,message_send from " . TABLE_SERVICES_MESSAGES . " where message_type  in ('RN1','RN2','RN3','RN4','RN5','RS1','RS2','RE1','RE2') group by service_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["service_id"]][$email_array["message_type"]]=$temp;
	}
	
	//get the sms templates
	$sms_query=tep_db_query("SELECT service_id,message_type,message_text,message_subject,message_send from " . TABLE_SERVICES_SMS_MESSAGES . " where message_type in('RN1','RN2','RN3','RN4','RN5','RS1','RS2','RE1','RE2') group by service_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["service_id"]][$sms_array["message_type"]]=$temp;
	}
 
	// check reservation start reminders
	$cur_type="RN1";
	
	if ($mail_status['S']=='N') {
		$first_sql = "SELECT o.customers_id,s.service_id,o.date_purchased as start_date,date_format(date_sub(o.date_purchased,interval es.message_send+0 day),'%Y-%m-%d') as res_start_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o," . TABLE_SERVICES . " s," .  TABLE_ORDERS_SERVICES . " os, "  . TABLE_SERVICES_SMS_MESSAGES . " es where os.orders_id=op.orders_id and os.orders_products_id=op.orders_products_id and os.products_id=op.products_id and o.orders_id=op.orders_id and op.products_id=s.service_id and es.service_id=s.service_id and es.message_type ='RN1' and op.products_type='V' and op.events_type='P'  group by o.customers_id,s.service_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["service_id"]][$cur_type])){
				$cur_template=$templates_s[$first_result["service_id"]][$cur_type];
				tep_send_automate_start_email($first_result["service_id"],$first_result["customers_id"],$first_result["res_start_date"]);
			}
		}
	}
	if ($mail_status['E']=='Y' || $mail_status['S']=='Y'){
		$fourth_sql = "SELECT sm.message_type,if(s.booking_type='D',sm.message_send,sm.message_send1) as message_send,o.customers_id,s.service_id,s.service_renewal_end,date_add((if(POSITION('-' IN (if(s.booking_type='D',sm.message_send,sm.message_send1)))='1',os.end_date,os.start_date)), interval( if( s.booking_type = 'D', message_send, message_send1 ) )
											DAY ) as renewal_start,date_add(date_add((if(POSITION('-' IN (if(s.booking_type='D',sm.message_send,sm.message_send1)))='1',os.end_date,os.start_date)), interval( if( s.booking_type = 'D', message_send, message_send1 ) )
											DAY ),interval s.service_renewal_end day) as renewal_end from orders_products op, orders o,orders_services os, services s, services_messages sm where op.orders_id=o.orders_id and o.orders_status>1 and op.orders_id=os.orders_id and op.orders_products_id=os.orders_products_id and op.products_id=os.products_id and op.products_id=s.service_id and op.products_id=sm.service_id and o.orders_id=os.orders_id and os.products_id=s.service_id and os.products_id=s.service_id and os.products_id=sm.service_id and s.service_id=sm.service_id and sm.message_type in('RN1','RN2','RN3','RN4','RN5','RS1','RS2','RE1','RE2') group by sm.message_type,s.service_id order by s.service_id,sm.message_type";
		$fourth_query=tep_db_query($fourth_sql);
		while($fourth_result=tep_db_fetch_array($fourth_query)){
		   if($fourth_result['renewal_start']>=$curdate && $fourth_result['renewal_end']>=$curdate){
					tep_send_automate_remind_email($fourth_result["service_id"],$fourth_result["customers_id"],$fourth_result["renewal_end_date"],$fourth_result['message_type']);
			}
		}	 	
	}

require('includes/application_bottom.php');

function tep_send_automate_start_email($service_id,$customers_id,$res_start_date)
{
	global $currencies,$curdate,$languages_id,$templates_s,$cur_template,$server_date;
	
	if ((int)$service_id<=0 || (int)$customers_id<=0){
		error_notification("Automate Start => Service Id :" . $service_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_SERVICES_MESSAGES_HISTORY . " where service_id='" . $service_id . "' and customers_id='" . $customers_id . "' and message_type='RN1' 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 Service Id:" . $service_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 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"]);
	if ($customer_result["customers_fax"]==""){
		error_notification("Automate Start => Customer Fax (Customer Id:" . $customers_id . ") is Empty");
		return;
	}
	
	//fetch event details	
	$service_query=tep_db_query(	"SELECT s.service_id,s.service_renewal_start,s.service_renewal_end,os.start_time,os.end_time,os.start_date,os.end_date," .
								"s.service_location,s.service_tax_class_id,s.service_costs,sd.service_name from " . TABLE_SERVICES . " s, " . TABLE_SERVICES_DESCRIPTION . " sd , " . TABLE_ORDERS_SERVICES . " os  where os.products_id=s.service_id and sd.service_id=os.products_id and s.service_id='" . $service_id . "' and s.service_id=sd.service_id and sd.language_id='" . $languages_id . "'");
	
	
	if (tep_db_num_rows($service_query)<=0){
		error_notification("Automate Start => Service (Service Id:" . $service_id . ") Not Found");
		return;
	}
	$service_result=tep_db_fetch_array($service_query);
	
	$service_location=tep_get_service_location_name($service_result['service_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_SER_SN=>$service_result['service_name'],
							TEXT_SER_SC=>$currencies->format(tep_add_tax($service_result['service_costs'],tep_get_tax_rate($service_result['service_tax_class_id']))),
							TEXT_SER_SL=>$service_location, 
							TEXT_SER_ST=>date('h:i A',strtotime($service_result['start_time'])),
							TEXT_SER_ET=>date('h:i A',strtotime($service_result['end_time'])),
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_INVITE_FRIEND,'R=1&path=ACC&eID=' . $service_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_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_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>'
						);
	$sql_array=array('orders_id'=>0,
						'service_id'=>$service_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_SERVICES_MESSAGES_HISTORY,$sql_array); 	
		}
	}

function tep_send_automate_remind_email($service_id,$customers_id,$renewal_date,$value='RN1'){
	global $currencies,$languages_id,$mail_status,$templates_s,$templates_e,$server_date;
	
	if ((int)$service_id<=0 || (int)$customers_id<=0){
		error_notification("Automate Remind => Service Id :" . $service_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_SERVICES_MESSAGES_HISTORY . " where service_id='" . $service_id . "' and customers_id='" . $customers_id . "' and message_type in ('RN1','RN2','RN3','RN4','RN5','RS1','RS2','RE1','RE2') 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[$service_id][$value]) && $mail_status['E']=='Y' && $mail_count['E']<=0){
			$email_template=$templates_e[$service_id][$value];
			$send_email=true;
		}
		if (isset($templates_s[$service_id][$value]) && $mail_status['S']=='Y' && $mail_count['S']<=0){
			$sms_template=$templates_s[$service_id][$value];
			$send_sms=true;
		}
	
	if (!$send_email && !$send_sms){
		error_notification("Automate Remind => Record(s) of Service Id:" . $service_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"]);
	
	$service_query=tep_db_query("SELECT s.service_id,date_add(date_add((if(POSITION('-' IN (if(s.booking_type='D',sm.message_send,sm.message_send1)))='1',os.end_date,os.start_date)), interval( if( s.booking_type = 'D', message_send, message_send1 ) )
								DAY ),interval s.service_renewal_end day)as renewal_end," .
								"s.service_location,s.service_tax_class_id,s.service_costs,sd.service_name from " . TABLE_SERVICES . " s, " . TABLE_SERVICES_DESCRIPTION . " sd, " . TABLE_SERVICES_MESSAGES . " sm, "  . TABLE_ORDERS_SERVICES . " os where os.products_id=s.service_id and sm.service_id=os.products_id and sm.service_id=s.service_id and s.service_id='" . $service_id . "' and s.service_id=sd.service_id and sd.language_id='" . $languages_id . "'");
	if (tep_db_num_rows($service_query)<=0){
		error_notification("Automate Remind => Service (Service Id:" . $service_id . ") Not Found");
		return;
	}
	$service_result=tep_db_fetch_array($service_query);
	$service_location=tep_get_service_location_name($service_result['service_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($service_result['renewal_end']),
							TEXT_SER_SN=>$service_result['service_name'],
							TEXT_SER_SC=>$currencies->format(tep_add_tax($service_result['service_costs'],tep_get_tax_rate($service_result['service_tax_class_id']))),
							TEXT_SER_SL=>$service_location, 
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_INVITE_FRIEND,'R=1&path=ACC&eID=' . $service_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_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_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $service_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>'
						);

	$sql_array=array('orders_id'=>0,
						'service_id'=>$service_id,
						'customers_id'=>$customer_result["customers_id"],
						'message_type'=>$value,
						'message_mode'=>'V',
						'email_address'=>$customer_result["customers_email_address"],
						'send_date'=>$server_date
					);

	if ($send_email){
		$details=array();
		$details['type']=$value;
		$details['service_id']=$service_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_SERVICES_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_SERVICES_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;
}
?>
