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

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


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

	$templates_sub=array();
	//get the subscription templates
	$email_query=tep_db_query("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')");
	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);
		}
	}
	
	
require('includes/application_bottom.php');

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("Automate Remind => Subscription Id :" . $subscription_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_SUBSCRIPTION_MESSAGES_HISTORY . " where subscription_id='" . $subscription_id . "' and customers_id='" . $customers_id . "' and orders_id='" . $detail["orders_id"] . "' and message_type='" . $message_type. "' 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_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("Automate Remind => Record(s) of Subscription Id:" . $subscription_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"]);
	
	$subscription_query=tep_db_query("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='" . $subscription_id . "' and su.subscription_id=sud.subscription_id and sud.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($subscription_query)<=0){
		error_notification("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);
	} 
}
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;
}
?>