<?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 );
	set_time_limit(0);
	require('includes/sms_application_top.php');
	require(DIR_WS_CLASSES . 'currencies.php');
	require(DIR_WS_CLASSES . 'xml_parser.php');
	require(DIR_WS_CLASSES . 'fulfiller.php');
	require(DIR_WS_CLASSES . 'order.php');

?>

<!-- UPDATE CURRENCIES -->
<?php

	define("EMAIL_TEXT_SUBJECT","Currency update failure at %s");
	define("EMAIL_TEXT_RECOVER_SUBJECT","Currency update recovery at %s");
	define("EMAIL_TEXT_RECOVERY_SUBJECT","Currency update recovery at %s");

	$perform_update=true;
	$send_failure_mail_flag=false;
	$send_recovery_mail_flag=false;

	if($perform_update)
	{	
		$status_sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . "  order by update_time desc limit 3";
		$status_query=tep_db_query($status_sql);
		$update_status=0;
		$fail_status=0;
		$icnt=0;
		if(tep_db_num_rows($status_query)>0) {
			while($status_result=tep_db_fetch_array($status_query)) {
				if($status_result['update_status']=='U' && $icnt==0)
					break;
				else if($status_result['update_status']=='U' && $icnt!=0)
					$update_status++;
				else if($status_result['update_status']=='F')
					$fail_status++;	
			$icnt++;		
			}
		}
		$sql="select code from " . TABLE_CURRENCIES . " order by code";
		$sql_query=tep_db_query($sql);
		$update_result=false;
		while($row=tep_db_fetch_array($sql_query))
			$currency_names[]=$row['code'];
			
		$update_result=get_google_currency_rates($currency_names);
		if(!$update_result){ //is false then try for currencysource.com
			error_notification("Update Currency","Failure Currency Update from Google");
			$update_result=get_currencysource_rates();
		}
		
		if($update_result)  //success update
		{
			update_currency_table($update_result);
			insert_status_record('U'); //currecy_update_history
			if($fail_status==3)	{
				send_recovery_mail();
			}
		}
		else	//failure update
		{
			error_notification("Update Currency","Failure Currency Update from currencysource");
			insert_status_record('F'); //currecy_update_history
			if($fail_status==2){
				send_failure_mail();
			}
		}
    }
function get_google_currency_rates($currency_names){
	$result=array();
	for ($icnt=0,$n=count($currency_names);$icnt<$n;$icnt++){
		if (DEFAULT_CURRENCY!=$currency_names[$icnt]){
			$data=@file_get_contents("http://www.google.co.in/search?hl=en&q=" . urlencode(sprintf("1 %s in %s",DEFAULT_CURRENCY,$currency_names[$icnt])));
			//$data=@file_get_contents("currency_update/simple_google_results.txt");
			$data=strip_tags($data);
			$spos=strpos($data," = ");
			if ($spos===false) return false;
			$spos=$spos+3;
			$epos=strpos($data," ",$spos);
			if ($epos===false) return false;
			$data=(float)substr($data,$spos,$epos-$spos);
			if ($data<0.0) return false;
			$result[$currency_names[$icnt]]=$data;
		} else {
			$result[$currency_names[$icnt]]=1.0;
		}
	}
	return $result;
}
	
function get_currencysource_rates()
{
	$er_url=DEFAULT_CURRENCY . ".xml";
	//$rates = @file_get_contents("currency_update/" . $er_url);
	$rates = "http://currencysource.com/RSS/" . DEFAULT_CURRENCY . ".xml";
	$start_pos=strpos($rates,"<item>");
	$end_pos=strrpos($rates,"</item>");
	if($start_pos>=0 && $end_pos>0) //success result
	{
		$rates=substr($rates,$start_pos,$end_pos-$start_pos);
		$rates='<?xml version="1.0"?><items>' . $rates . "</items></item>";
		$parser=new xml_parser_class;
		$parser->store_positions=0;
		$parser->case_folding=0;
		$parser->target_encoding="ISO-8859-1";
		$parser->simplified_xml=0;
		$parser->fail_on_non_simplified_xml=0;
		
		$parser->parse($rates,true);
		$result=&$parser->structure;
		$n=count($result);
		for ($icnt=0;$icnt<$n;$icnt++){
			if (isset($result["0," . $icnt . ",1,0"]))
			{
				$cur_result=$result["0," . $icnt . ",1,0"];
				$cur_arr=split("=",$cur_result);
				if(count($cur_arr)>1)
				{
					$temp_arr=split('\(',$cur_arr[1]);
					$cur_key=trim($temp_arr[0]);
					$cur_value=trim(substr($temp_arr[1],0,-1));
					if ($cur_value<0.0) return false;
					$currency_update[$cur_key]=$cur_value;
				}
			}
		}
		return $currency_update;
	}
	else
		return false;
}

function insert_status_record($update_status)
{
	global $send_failure_mail_flag,$send_recovery_mail_flag;
	$update_time=date("Y-m-d h:i:s");
	/*$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . " where currency_name='" . DEFAULT_CURRENCY . "' order by update_time desc limit 3";
	$sql_query=tep_db_query($sql);
	if(tep_db_num_rows($sql_query)>0)
	{
		$row=tep_db_fetch_array($sql_query);
		if($row['update_status']=='U' && $update_status=='U')  //successive success updates no change
		{
			$step_val=0;
		}
		elseif($row['update_status']=='U' && $update_status=='F') //first failure
		{
			$step_val=1;
		}
		elseif($row['update_status']=='F' && $update_status=='U') //prev failure and now success
		{
			$send_recovery_mail_flag=true;
			$step_val=0;
		}
		elseif($row['update_status']=='F' && $row['counter_track']==2 && $update_status=='F') //two failures 
		{
			$send_failure_mail_flag=true;
			$step_val=$row['counter_track']+1;
		}
		elseif($row['update_status']=='F' && $update_status=='F') //count the successive failures 
		{
			$step_val=$row['counter_track']+1;
		}
	}
	else
	{
		if($update_status=='U')
			$step_val=0;
		else
			$step_val=1;
	} */
	$sql="insert into " . TABLE_CURRENCY_UPDATE_HISTORY . " (update_time,update_status) values('" . $update_time . "','" . $update_status  . "')";
	tep_db_query($sql);
}
	
function update_currency_table($cur_update)
{
	while(list($key,$value)=each($cur_update))
	{
		$sql="update " . TABLE_CURRENCIES . " set value='$value',last_updated=now() where code='$key'";
		tep_db_query($sql);
	}
}

function send_failure_mail()
{
	$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . " where update_status='F' order by update_time desc limit 3";
	$sql_query=tep_db_query($sql);
	$max_cnt=0;
	$min_cnt=2;
	while($row=tep_db_fetch_array($sql_query))
	{
		if($max_cnt==0)
			$max_time=$row['update_time'];
		elseif($min_cnt==0)
			$min_time=$row['update_time'];
		$max_cnt++;
		$min_cnt--;
	}

	$subject=sprintf(EMAIL_TEXT_SUBJECT, STORE_NAME);
	$email ="This is an automated email. Please do not reply. " . "\n\n" .
			"The automatic currency update at " . STORE_NAME . " failed after three attempts between " . $min_time . " to " . $max_time . ".It is strongly recommended that you try a manual update. " . "\n\n" . "with thanks, " . "\n\n" . "osCommRes system	";
	$sql="select a.admin_firstname,a.admin_lastname,a.admin_email_address from " . TABLE_ADMIN . " a," . TABLE_ADMIN_GROUPS . " ag where ag.admin_groups_id=a.admin_groups_id and ag.admin_groups_name='" . TEXT_ADMINISTRATOR_ENTRY . "'";
	$sql_query=tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_query))
		tep_mail($row['admin_lastname'] . ' ' . $row['admin_firstname'] , $row['admin_email_address'], $subject, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	return true;
}
function send_recovery_mail()
{
	$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . "  order by update_time desc";
	$sql_query=tep_db_query($sql);
	$cunt=0;
	while($row=tep_db_fetch_array($sql_query))
	{
		if($row['update_status']=='U' && $cunt==0)
			$update_time=$row['update_time'];
		elseif($row['update_status']=='U' && $cunt!=0)
			break;
		elseif($row['update_status']=='F' && $cunt==0)
		{
			$max_date=$row['update_time'];
			$cunt++;
		}
		$min_date=$row['update_time'];
	}

	$subject=sprintf(EMAIL_TEXT_RECOVER_SUBJECT, STORE_NAME);
	$email ="This is an automated email. Please do not reply. " . "\n\n" .
			"The automatic currency update at " .STORE_NAME  . " has recovered as at " . $update_time . ". It was in a failed state between " . $min_date . " to " .  $max_date . ". It is strongly recommended that you check your systems to avoid further outages." . "\n\n" . "with thanks, " . "\n\n" . "osCommRes system	"; 
	$sql="select a.admin_firstname,a.admin_lastname,a.admin_email_address from " . TABLE_ADMIN . " a," . TABLE_ADMIN_GROUPS . " ag where ag.admin_groups_id=a.admin_groups_id and ag.admin_groups_name='" . TEXT_ADMINISTRATOR_ENTRY . "'";
	$sql_query=tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_query))
        tep_mail($row['admin_lastname'] . ' ' . $row['admin_firstname'] , $row['admin_email_address'], $subject, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	return true;
}
?>

<!-- WALLET CHECK SCRIPT -->
<?php

	$mail_status=array('E'=>'N','S'=>'N');

	$now=getServerDate(true);
	$curdate=getServerDate();

	//$curdate='2006-04-23';
	//$now='2006-04-22 00:00:00';
	
	$currencies=new currencies();
	$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",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';
	}
	if ((int)EMAIL_ACTIVATE!=1) $mail_status['E']='N';

	// find if the template for the wallet balance reminder email is present
	$template_query=tep_db_query("SELECT * from " . TABLE_EMAIL_MESSAGES . " where message_type='WBW'");
	if (tep_db_num_rows($template_query)<=0) {
		$mail_status["E"]="N";
	}
	
	// if mail sending is enabled and if we are in the time scheduling 

		
		//check for wallet Balance
		// first get the wallet upoad total
		$balance=array();
		$sql="SELECT customers_id,sum(amount) as total from " . TABLE_WALLET_UPLOADS . " where payment_status>1 group by customers_id order by customers_id";
		$upload_query=tep_db_query($sql);
		while($upload_result=tep_db_fetch_array($upload_query)){
			$balance[$upload_result["customers_id"]]["upload_total"]=$upload_result["total"];
		}
		
		// get the wallet drawn total
		$sql="SELECT customers_id,sum(amount) as total from " . TABLE_WALLET_HISTORY . " group by customers_id order by customers_id";
		$drawn_query=tep_db_query($sql);
		while($drawn_result=tep_db_fetch_array($drawn_query)){
			$balance[$drawn_result["customers_id"]]["drawn_total"]=$drawn_result["total"];
		}
		$mail_status['E']='Y';
	if ($mail_status['E']=='Y'){
		// get the customers to be the messages are sent
		$sql="SELECT customers_id,if(date_format(date_add(max(send_date), interval 3 day),'%Y-%m-%d')='" .$curdate ."','Y','N') as mail_send from " . TABLE_WALLET_MESSAGES_HISTORY . " where message_type='WBW' group by customers_id";
		$mail_query=tep_db_query($sql);
		while($mail_result=tep_db_fetch_array($mail_query)){
			$balance[$mail_result["customers_id"]]["mail_send"]=$mail_result["mail_send"];
		}
		// find the customers who had balance < defined balance amount
		if (count($balance)>0){
			reset($balance);
			while(list($customers_id,$value)=each($balance)){
				if (!isset($value["upload_total"])) $value["upload_total"]=0;
				if (!isset($value["drawn_total"])) $value["drawn_total"]=0;
				$current_balance=$value["upload_total"]-$value["drawn_total"];

				// get minimum balance
				$minimum_balance=tep_get_wallet_min_balance($customers_id);
				if ($current_balance<$minimum_balance && (!isset($value["mail_send"]) || $value["mail_send"]=="Y")) {
					tep_send_wallet_balance_reminder($customers_id,$current_balance);
				}
			} // while balance
		} // count balance
	} // if mailstatus
	
	
	// making payment for the expired subscription
	// first get the expired subscriptions for the current date
	// if subscription wallet payment is on, draw amount after subscription ends
	// if subscription periodic payment is on, draw amount after/before periodic days from subscription ends
	$expired_sql="SELECT o.customers_id,su.wallet_payment,su.periodic_payment,o.orders_id,su.subscription_id,date_add(max(o.date_purchased), interval su.subscription_period day) as subscription_end_date, " . 
						" if (su.periodic_type='A',date_add(max(o.date_purchased), interval su.subscription_period+su.periodic_days day),date_add(max(o.date_purchased), interval su.subscription_period-su.periodic_days day)) as subscription_payment_date from " .
						TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " .
						TABLE_SUBSCRIPTIONS . " su where op.orders_id=o.orders_id and op.products_id=su.subscription_id and op.products_type='S' and (su.wallet_payment='Y' || su.periodic_payment='Y') " .
						" group by o.customers_id,su.subscription_id having (su.wallet_payment='Y' and '" . $curdate . "'>=date_format(subscription_end_date,'%Y-%m-%d')) or (su.periodic_payment='Y' and '" . $curdate . "'>=date_format(subscription_payment_date,'%Y-%m-%d')) order by su.subscription_id";

	$expired_query=tep_db_query($expired_sql);


	$total_class=array(	'ot_subtotal'=>array('title'=>"Sub-Total:",'sort_order'=>1),
						'ot_tax'=>array('title'=>'Tax:','sort_order'=>2),
						'ot_total'=>array('title'=>'Total:','sort_order'=>4));

	$prev_id=0;
	// create new orders for the entries 
	while($expired_result=tep_db_fetch_array($expired_query)){
		// get the subscription price
		$temp_drawn_amount=0;
		$customers_id=$expired_result["customers_id"];
		if ($prev_id!=$expired_result["subscription_id"]){
			$subscription_sql = "SELECT su.subscription_id,su.subscription_costs,sud.subscription_name,su.subscription_tax_class_id from " . TABLE_SUBSCRIPTIONS . " su, " .
												TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id and sud.language_id='" .  $languages_id . "' and su.subscription_id='" . (int)$expired_result["subscription_id"] . "'";
			$subscription_query=tep_db_query($subscription_sql);
			$subscription_result=tep_db_fetch_array($subscription_query);
			$prev_id=$subscription_result["subscription_id"];
			
			$subscription_result["tax_rate"]=tep_get_tax_rate($subscription_result["subscription_tax_class_id"]);
			$subscription_result["ot_tax"]=tep_calculate_tax($subscription_result["subscription_costs"],$subscription_result["tax_rate"]);
			$subscription_result["ot_total"]=$subscription_result["subscription_costs"]+$subscription_result["ot_tax"];
			$subscription_result["ot_subtotal"]=$subscription_result["ot_total"];
		}
		
		if (tep_db_num_rows($subscription_query)<=0) continue;
		if (!isset($balance[$customers_id])) continue;
		
		// check for amount present in wallet
		$temp_drawn_amount=$balance[$customers_id]["drawn_total"]+$subscription_result["ot_total"];
		$upload_amount=$balance[$customers_id]["upload_total"];

		if ($temp_drawn_amount>$upload_amount) continue;
		
		
		// update to order
		$order_sql = "SELECT * from " . TABLE_ORDERS . " where orders_id='" . $expired_result["orders_id"] . "'";
		$order_query=tep_db_query($order_sql);
		$order_result=tep_db_fetch_array($order_query);
		$order_result["payment_method"]="Wallet Payment";
		$order_result["cc_type"]="";
		$order_result["cc_owner"]="";
		$order_result["cc_number"]="";
		$order_result["last_modified"]="";
		$order_result["date_purchased"]=$now;
		$order_result["orders_date_finished"]="";
		$order_result["payment_info"]="Wallet Payment";
		$order_result["cc_cvv_number"]="";
		unset($order_result["orders_id"]);
		tep_db_perform(TABLE_ORDERS,$order_result);
		$insert_id=tep_db_insert_id();
		// update to order products
		$sql_array=array(	"orders_id"=>$insert_id,
							"products_id"=>$subscription_result["subscription_id"],
							"products_model"=>"",
							"products_name"=>$subscription_result["subscription_name"],
							"products_price"=>$subscription_result["subscription_costs"],
							"final_price"=>$subscription_result["subscription_costs"],
							"products_quantity"=>1,
							"products_tax"=>$subscription_result["tax_rate"],
							"products_type"=>"S",
							"events_type"=>"",
							"waitlist_type"=>"",
							"events_fees"=>0,
							"waitlist_orders_id"=>0
							);
		tep_db_perform(TABLE_ORDERS_PRODUCTS,$sql_array);
  
  		// update the order total
		reset($total_class);
		while(list($key,)=each($total_class)){
			$val_amount=$subscription_result[$key];
			$sql_data_array = array('orders_id' => $insert_id,
									'title' => $total_class[$key]['title'],
									'text' => $currencies->format($val_amount),
									'value' => $val_amount, 
									'class' => $key, 
									'sort_order' => $total_class[$key]['sort_order']);
			tep_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
		}
		$balance[$customers_id]["drawn_total"]=$temp_drawn_amount;
		// update the order status history
		$sql_array=array(	"orders_id"=>$insert_id,
							"orders_status_id"=>2,
							"date_added"=>$now,
							"customer_notified"=>'1',
							"comments"=>"Created Order Using Automatic Wallet Payment",
							"user_added"=>"Auto Wallet"
		);
		tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$sql_array);
		//update the wallet_history about usage of amount
		$sql_array=array(	"orders_id"=>$insert_id,
							"drawn_date"=>$now,
							"customers_id"=>$customers_id,
							"amount"=>$subscription_result["ot_total"]
						);
		tep_db_perform(TABLE_WALLET_HISTORY,$sql_array);
		tep_send_subscription_order_email($insert_id);
	}
	
	function tep_send_wallet_balance_reminder($customers_id,$balance){
		global $currencies,$curdate,$now;

		$customer_sql="SELECT c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_email_address,c.customers_telephone,
						c.customers_fax,a.entry_street_address,a.entry_city,a.entry_suburb,a.entry_postcode,a.entry_state,a.entry_country_id,a.entry_zone_id
						from " . TABLE_CUSTOMERS . " c," . TABLE_ADDRESS_BOOK . " a where a.address_book_id=c.customers_default_address_id and c.customers_id='" . (int)$customers_id . "'";


		$customer_query=tep_db_query($customer_sql);
		
		if (tep_db_num_rows($customer_query)<=0){
			error_notification("Wallet Check script","Wallet Balance =>Customer (Customer Id:" . $customers_id . ") Not Found");
			return;
		}
		$customer_result=tep_db_fetch_array($customer_query);

								
		$merge_details=array(	TEXT_FN=>$customer_result['customers_firstname'],
								TEXT_LN=>$customer_result['customers_lastname'],
								TEXT_DF=>format_date($customer_result['customers_dob']),
								TEXT_EM=>$customer_result['customers_email_address'],
								TEXT_TN=>$customer_result['entry_telephone_number'],
								TEXT_FX=>$customer_result['entry_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=>tep_get_zone_name($customer_result["entry_country_id"],$customer_result["entry_zone_id"],$customer_result['entry_state']),
								TEXT_CY=>tep_get_country_name($customer_result['entry_country_id']),
								TEXT_RE=>'',
								TEXT_IV=>'',
								TEXT_UN=>'',
								TEXT_PT=>'',
								TEXT_WAD=>'',
								TEXT_WCB=>$currencies->format($balance)
							);
		
       $send_details=array(
	   						array('to_name'=>$customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'],
	                                     'to_email'=>$customer_result['customers_email_address'],
										 'from_name'=>STORE_OWNER,
										 'from_email'=>STORE_OWNER_EMAIL_ADDRESS
							)
						);
		// store in the message history
		$sql_array=array(
							"send_date"=>$now,
							"customers_id"=>$customers_id,
							"message_mode"=>"E",
							"message_type"=>"WBW"
						);
						
		tep_db_perform(TABLE_WALLET_MESSAGES_HISTORY,$sql_array);
		tep_send_default_email("WBW",$merge_details,$send_details);
	}
?>

<!-- UPDATE PRODUCT STATUS -->
<?php

$currencies=new currencies();
$parser=new xml_parser_class;
$parser->store_positions=0;
$parser->case_folding=0;
$parser->target_encoding="ISO-8859-1";
$parser->simplified_xml=0;
$parser->fail_on_non_simplified_xml=0;

$fulfiller= new fulfiller('oneworld');

$error="";
$result=$fulfiller->process_out_of_stock();
if ($result["error"]==""){
	if (count($result["content"])<=0) $error="Error: No products found to update";
} else {
	$error=$result["error"];
}
if($error=="")
{
	while(list($key,$value)=each ($result["content"]))
	{
		if ($key=="") continue;
		if($value<=0) //out of stock
		{
			$sql="update " . TABLE_PRODUCTS . " set products_status=0 where products_sku='" . tep_db_input($key) . "'";
			tep_db_query($sql);
			$sql="update " . TABLE_PRODUCTS_STOCK . " set attribute_status=0 where sku='" . tep_db_input($key) . "'";
			tep_db_query($sql);
		}
		else
		{
			$sql="update " . TABLE_PRODUCTS . " set products_status=1 where products_sku='" . tep_db_input($key) . "'";
			tep_db_query($sql);
			$sql="update " . TABLE_PRODUCTS_STOCK . " set attribute_status=1 where sku='" . tep_db_input($key) . "'";
			tep_db_query($sql);
		}
	}
}
else{
	error_notification("Update Product Status",$error);
}
?>

<!-- SEND MESSAGE ORDER STATUS -->
<?php

	$currencies=new currencies();
	$parser=new xml_parser_class;
	$parser->store_positions=0;
	$parser->case_folding=0;
	$parser->target_encoding="ISO-8859-1";
	$parser->simplified_xml=0;
	$parser->fail_on_non_simplified_xml=0;
	
//	$fulfiller= new fulfiller('oneworld');

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

	//get the subscription templates
	$email_sql = "SELECT * from " . TABLE_EMAIL_MESSAGES . " where message_type in('PST')";
	$email_query=tep_db_query($email_sql);
	while($email_array=tep_db_fetch_array($email_query)){
		$template=&new mesContent();
		$template->content=$email_array["message_text"];
		$template->subject=$email_array["message_subject"];
		$template->sendtime=$email_array["message_send"];
		$template->format=$email_array["message_format"];
	}

	// check order statuschange
	$sql="select orders_id,fulfiller_status from " . TABLE_ORDERS . " where orders_status!=3 and fulfiller_status!='SHIPPED'";
	$select_query=tep_db_query($sql);
	$success='';
	while($row=tep_db_fetch_array($select_query)){
		$result_status=$fulfiller->process_status($row['orders_id']);
		if ($result_status["error"]!='' || $result_status["status"]==""){
			if ($result_status["error"]==""){
				error_notification("Send Message Order Status","Fulfiller Interface error. Mail sending failed");
				break;
			}
		}
	    if ($result_status["status"]!=$row['fulfiller_status']){
			$order = new order($row['orders_id']);
			$sql="update " . TABLE_ORDERS . " set fulfiller_status='" . $result_status["status"] ."' where orders_id='" . $row['orders_id'] . "'";
			tep_db_query($sql);
			tep_send_status_change_email($order,$row['orders_id']);
		}
	}
	if ($result_status["status"]){
	} else {
		error_notification("Send Message Order Status","Mail Sending Error");
	}

function get_status_id($s_id)
{
	$id=$s_id;
	return constant($id);
}
function tep_send_status_change_email(&$order,$ord_id){
	global $currencies,$languages_id,$template;
	

	$merge_details[CUST_CF]=$order->customer['firstname'];
	$merge_details[CUST_CL]=$order->customer['lastname'];
	$merge_details[CUST_CM]=$order->customer['company'];
	$merge_details[TEXT_SN]=STORE_OWNER;
	$merge_details[TEXT_SM]=STORE_NAME;
	$merge_details[TEXT_SE]=STORE_EMAIL;
	$merge_details[TEXT_AL]=STORE_EMAIL;
	$merge_details[CUST_CT]=$order->customer['street_address'];
	$merge_details[CUST_CS]=$order->customer['suburb'];
	$merge_details[CUST_CC]=$order->customer['city'];
	$merge_details[CUST_CP]=$order->customer['postcode'];
	$merge_details[CUST_CE]=$order->customer['state'];
	$merge_details[CUST_CU]=$order->customer['country']['title'];
	$merge_details[CUST_CO]=$order->customer['telephone'];
	$merge_details[CUST_CA]=$order->customer['email_address'];
	

	/*$merge_details[TEXT_PN]=
	$merge_details[TEXT_PP]=
	$merge_details[TEXT_P_Q]=
	$merge_details[TEXT_P_STATUS]=*/
	$merge_details[ORDR_NO]=$insert_id;
	$merge_details[ORDR_OL]=tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $insert_id, 'SSL', false);
	$merge_details[ORDR_OP]=strftime(DATE_FORMAT_LONG);
	$merge_details[ORDR_OM]=$order->info['comments'] . $comments;
	$merge_details[ORDR_PO]=$products_ordered;
	
	$merge_details[ORDR_NO]=$ord_id;
	$merge_details[ORDR_OP]=$order->info['date_purchased'];
	$merge_details[ORDR_OL]=tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $ord_id, 'SSL', false);
	$merge_details[ORDR_PO]="";
	$merge_details[ORDR_OM]=$order->info['comments'];
	$merge_details[ORDR_OT]=$order->info['total'];
	$merge_details[ORDR_PM]=$order->info['payment_method'];

		$details=array();
		$details['format']=$template->format;
		$details['html_text']=$template->content;
		$details['text']=$template->content;
		$details['subject']=$template->subject;

		//replace content
		tep_replace_template($details,$merge_details);
		tep_strip_html($details);
		// get the address to send
		$details['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
		$details['to_email']=$order->customer['email_address'];
		$details['from_name']=STORE_OWNER;
		$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
		
		tep_send_email($details);	
}
?>

<!-- SEND MESSAGES EVENT SCRIPT -->
<?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",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",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("Send Messages Event Script","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_sql = "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";
	$email_query=tep_db_query($email_sql);
	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_sql = "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";
	$sms_query=tep_db_query($sms_sql);
	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_event_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_event_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_sql = "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";
				$user_result_query=tep_db_query($user_result_sql);
	
				$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_event_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_event_feedback_email($second_result["events_id"],$second_result["customers_id"],'E');
			}
		}
		$event_sql = "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";
		$event_query=tep_db_query($event_sql);
		while($event_result=tep_db_fetch_array($event_query)){
			if (isset($templates_e[$event_result["events_id"]][$cur_type])){
				$user_result_sql = "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";
				$user_result_query=tep_db_query($user_result_sql);
	
				$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_event_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_event_remind_email($fourth_result["events_id"],$fourth_result["customers_id"],$fourth_result["renewal_end_date"]);
		}
		$event_sql = "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";
		$event_query=tep_db_query($event_sql);
		while($event_result=tep_db_fetch_array($event_query)){
			$user_result_sql = "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";
			$user_result_query=tep_db_query($user_result_sql);

			$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_event_remind_email($event_result["events_id"],$user_result["customers_id"],$user_result["end_date"]);
					}
				}
				$cur_row++;
			}
		}		
	}

function tep_send_automate_event_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("Send Messages Event Script","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("Send Messages Event Script","Automate Start => Template Content Text is Empty");
		return;
	}

	// check if previously sent
	$sql = "SELECT count(*) as total from " . TABLE_EVENTS_MESSAGES_HISTORY . " where events_id='" . (int)$events_id . "' and customers_id='" . (int)$customers_id . "' and message_type='RSR' group by message_mode order by message_mode";
	$query=tep_db_query($sql);
	$result=tep_db_fetch_array($query);
	
	if ($result['total']>0){
		error_notification("Send Messages Event Script","Automate Start => Record(s) of Event Id:" . (int)$events_id . " and Customer Id:" . (int)$customers_id . " found on Message History");
		return false;
	}
	
	// fetch customer details
	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);
	
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Event Script","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("Send Messages Event Script","Automate Start => Customer Fax (Customer Id:" . $customers_id . ") is Empty");
		return;
	}

	//fetch event details	
	$event_sql = "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='" . (int)$events_id . "' and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "'";
	$event_query=tep_db_query($event_sql);
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Send Messages Event Script","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_event_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("Send Messages Event Script","Automate Feedback => Event Id :" . $events_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}

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

	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);
	
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Event Script","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_sql = "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='" . (int)$events_id . "' and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "'";
	$event_query=tep_db_query($event_sql);
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Send Messages Event Script","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_event_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("Send Messages Event Script","Automate Remind => Event Id :" . $events_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}

	$mail_count=array('E'=>0,'S'=>0);
	$sql = "SELECT count(*),message_mode from " . TABLE_EVENTS_MESSAGES_HISTORY . " where events_id='" . (int)$events_id . "' and customers_id='" . (int)$customers_id . "' and message_type='RNR' group by message_mode order by message_mode";
	$query=tep_db_query($sql);
	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("Send Messages Event Script","Automate Remind => Record(s) of Event Id:" . $events_id . " and Customer Id:" . $customers_id . " found on Message History");
		return;
	}
	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);

	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Event Script","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_sql = "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='" . (int)$events_id . "' and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "'";
	$event_query=tep_db_query($event_sql);
	
	if (tep_db_num_rows($event_query)<=0){
		error_notification("Send Messages Event Script","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("Send Messages Event Script","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);
	}
}
class mesContent{
	var $content;
	var $subject;
	var $sendtime;
	var $format;
}
?>

<!-- SEND MESSAGES SUBSCRIPTION SCRIPT -->
<?php

	$currencies=new currencies();
	$server_date = getServerDate(true);
	
	$mail_status=array('E'=>'N','S'=>'N');
	
	//$curdate=date('Y-m-d');
	$curdate=getServerDate();
	//$curdate='2007-08-25';

	$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",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",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("Send Messages Subscription Script","EMAIL & SMS Activation is False or Email Timings are Mismatched on Current Time");
		return;
	}


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

	$templates_sub=array();
	//get the subscription templates
	$email_sql = "SELECT subscription_id,message_type,message_text,message_subject,message_send,message_send1 from " . TABLE_SUBSCRIPTION_MESSAGES . " where message_type in('RN1','RN2','RN3','RN4','RN5')";
	$email_query=tep_db_query($email_sql);
	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_sub[$email_array["subscription_id"]][$email_array["message_type"]]=$temp;
	}

	// check subscription Renewal Reminders
	if ($mail_status['E']=='Y'){
	
		$sql="SELECT o.customers_id,o.orders_id,op.products_id,if(sue.message_send='B',date_add(max(o.date_purchased),interval if(op.products_price>0,su.subscription_period,su.subscription_free_days) day),date_add(max(o.date_purchased),interval if(op.products_price>0,su.subscription_period,su.subscription_free_days) day)) as renewal_end_date,sue.message_type,  " . 
				"date_format(if(sue.message_send='B',date_add(max(o.date_purchased),interval if(op.products_price>0,su.subscription_period,su.subscription_free_days)-sue.message_send1 day),date_add(max(o.date_purchased),interval if(op.products_price>0,su.subscription_period,su.subscription_free_days)+sue.message_send1 day)),'%Y-%m-%d') as renewal_mail_date from " .
				TABLE_ORDERS_PRODUCTS ." op, " . TABLE_ORDERS . " o," . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTION_MESSAGES . " sue " . 
				" where op.orders_id=o.orders_id and op.products_id=su.subscription_id and su.subscription_id=sue.subscription_id and message_type in('RN1','RN2','RN3','RN4','RN5') and op.products_type='S' " .
				" group by o.customers_id,su.subscription_id,sue.message_type having renewal_mail_date='" . $curdate . "'";
		$fifth_query=tep_db_query($sql);
		while($fifth_result=tep_db_fetch_array($fifth_query)){
			tep_send_automate_subs_remind_email($fifth_result);
		}
	}
	
function tep_send_automate_subs_remind_email(&$detail){
	global $currencies,$languages_id,$mail_status,$templates_sub,$server_date;
	
	$subscription_id=(int)$detail["products_id"];
	$customers_id=(int) $detail["customers_id"];
	$message_type=$detail["message_type"];
	if ((int)$subscription_id<=0 || (int)$customers_id<=0){
		error_notification("Send Messages Subscription Script","Automate Remind => Subscription Id :" . $subscription_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}
	$mail_count=array('E'=>0,'S'=>0);
	$sql = "SELECT count(*),message_mode from " . TABLE_SUBSCRIPTION_MESSAGES_HISTORY . " where subscription_id='" . (int)$subscription_id . "' and customers_id='" . (int)$customers_id . "' and orders_id='" . (int)$detail["orders_id"] . "' and message_type='" . $message_type. "' group by message_mode order by message_mode";
	$query=tep_db_query($sql);
	while($result=tep_db_fetch_array($query)){
		$mail_count[$result["message_mode"]]=1;
	}
	$send_email=$send_sms=false;
	if (isset($templates_sub[$subscription_id][$message_type]) && $mail_status['E']=='Y' && $mail_count['E']<=0){
		$email_template=$templates_sub[$subscription_id][$message_type];
		$send_email=true;
	}
	if (!$send_email){
		error_notification("Send Messages Subscription Script","Automate Remind => Record(s) of Subscription Id:" . $subscription_id . " and Customer Id:" . $customers_id . " found on Message History");
		return;
	}

	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);

	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Subscription Script","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"]);
	
	$subscription_sql = "SELECT su.subscription_id,su.subscription_period,su.subscription_costs,su.subscription_tax_class_id,sud.subscription_name from " .
									TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id='" . (int)$subscription_id . "' and su.subscription_id=sud.subscription_id and sud.language_id='" . (int)$languages_id . "'";
	$subscription_query=tep_db_query($subscription_sql);
	
	if (tep_db_num_rows($subscription_query)<=0){
		error_notification("Send Messages Subscription Script","Automate Remind => Subscription (Subscription Id:" . $subscription_id . ") Not Found");
		return;
	}
	$subscription_result=tep_db_fetch_array($subscription_query);

	$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($detail["renewal_end_date"]),
							TEXT_SUB_NA=>$subscription_result['subscription_name'],
							TEXT_SUB_CO=>$currencies->format(tep_add_tax($subscription_result['subscription_costs'],tep_get_tax_rate($subscription_result['subscription_tax_class_id']))),
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_SUBSCRIPTION_INVITE_FRIEND,'R=1&path=ACC&suID=' . $subscription_result['subscription_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_IV . '</a>',
							TEXT_SUB_PE=>$subscription_result["subscription_period"],
							TEXT_SUB_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_SUBSCRIPTION_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_UN . '</a>'
						);

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


	if ($send_email){

		$details=array();
		$details['subscription_id']=$subscription_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_SUBSCRIPTION_MESSAGES_HISTORY,$sql_array);
		tep_send_email($details);
	} 
}
?>

<!-- SEND MESSAGES SERVICES SCRIPT -->
<?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",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",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("Send Messages Services Script","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_sql = "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";
	$email_query=tep_db_query($email_sql);
	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_sql = "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";
	$sms_query=tep_db_query($sms_sql);
	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_service_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 op.orders_products_status>1 and op.orders_products_status<5 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_service_remind_email($fourth_result["service_id"],$fourth_result["customers_id"],$fourth_result["renewal_end_date"],$fourth_result['message_type']);
			}
		}	 	
	}

function tep_send_automate_service_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("Send Messages Services Script","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("Send Messages Services Script","Automate Start => Template Content Text is Empty");
		return;	
	}

	// check if previously sent
	$sql = "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";
	$query=tep_db_query($sql);
	$result=tep_db_fetch_array($query);
	
	if ($result['total']>0){
		error_notification("Send Messages Services Script","Automate Start => Record(s) of Service Id:" . $service_id . " and Customer Id:" . $customers_id . " found on Message History");
		return false;
	}
	
	// fetch customer details
	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Services Script","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("Send Messages Services Script","Automate Start => Customer Fax (Customer Id:" . $customers_id . ") is Empty");
		return;
	}
	
	//fetch event details
	$service_sql = "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='" . (int)$service_id . "' and s.service_id=sd.service_id and sd.language_id='" . (int)$languages_id . "'";
	$service_query=tep_db_query($service_sql);
	
	
	if (tep_db_num_rows($service_query)<=0){
		error_notification("Send Messages Services Script","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_service_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("Send Messages Services Script","Automate Remind => Service Id :" . $service_id . " or Customer Id :" . $customers_id . " is Not valid");
		return;
	}
	
	$mail_count=array('E'=>0,'S'=>0);
	$sql = "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";
	$query=tep_db_query($sql);
	 
	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("Send Messages Services Script","Automate Remind => Record(s) of Service Id:" . $service_id . " and Customer Id:" . $customers_id . " found on Message History");
		return;
	}
	$customer_sql = "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='" . (int)$customers_id . "' and c.customers_default_address_id=a.address_book_id";
	$customer_query=tep_db_query($customer_sql);
	
	if (tep_db_num_rows($customer_query)<=0){
		error_notification("Send Messages Services Script","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_sql = "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='" . (int)$service_id . "' and s.service_id=sd.service_id and sd.language_id='" . (int)$languages_id . "'";
	$service_query=tep_db_query($service_sql);
	if (tep_db_num_rows($service_query)<=0){
		error_notification("Send Messages Services Script","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("Send Messages Services Script","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);
	}
}
?>


<!-- Error Notification -->
<?php 
function error_notification($action,$error){
	$error_array = array(
						'cron_jobs_error_action' => $action,
						'cron_jobs_error_text' => $error,
						'cron_jobs_error_date' => 'now()'
						);
	tep_db_perform(TABLE_CRON_JOBS_ERROR,$error_array);
}
?>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
