<?php
/*

	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare 
	
	Released under the GNU General Public License
*/

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();


  
// Generate a path to subscription categories
  function tep_get_subscription_path($current_subscription_category_id = '') {
    global $sucPath_array;

    if (tep_not_null($current_subscription_category_id)) {
      $ecp_size = sizeof($sucPath_array);
      if ($ecp_size == 0) {
        $sucPath_new = $current_subscription_category_id;
      } else {
        $sucPath_new = '';
        $last_subscription_category_query = tep_db_query("select parent_id from " . TABLE_SUBSCRIPTION_CATEGORIES . " where subscription_categories_id = '" . (int)$sucPath_array[($sucp_size-1)] . "'");
        $last_subscription_category = tep_db_fetch_array($last_subscription_category_query);

        $current_subscription_category_query = tep_db_query("select parent_id from " . TABLE_SUBSCRIPTION_CATEGORIES . " where subscription_categories_id = '" . (int)$current_subscription_category_id . "'");
        $current_subscription_category = tep_db_fetch_array($current_subscription_category_query);

        if ($last_subscription_category['parent_id'] == $current_subscription_category['parent_id']) {
          for ($i=0; $i<($sucp_size-1); $i++) {
            $sucPath_new .= '_' . $sucPath_array[$i];
          }
        } else {
          for ($i=0; $i<$sucp_size; $i++) {
            $sucPath_new .= '_' . $sucPath_array[$i];
          }
        }
        $sucPath_new .= '_' . $current_subscription_category_id;

        if (substr($sucPath_new, 0, 1) == '_') {
          $sucPath_new = substr($sucPath_new, 1);
        }
      }
    } else {
      $sucPath_new = implode('_', $sucPath_array);
    }

    return 'sucPath=' . $sucPath_new;
  }
  
  
  function tep_get_static_path($current_static_category_id = '') {
    global $stcPath_array;

    if (tep_not_null($current_static_category_id)) {
      $ecp_size = sizeof($stcPath_array);
      if ($ecp_size == 0) {
        $stcPath_new = $current_static_category_id;
      } else {
        $stcPath_new = '';
        $last_static_category_query = tep_db_query("select parent_id from " . TABLE_MAIN_PAGES . " where page_id = '" . (int)$stcPath_array[($sucp_size-1)] . "'");
        $last_static_category = tep_db_fetch_array($last_static_category_query);

        $current_static_category_query = tep_db_query("select parent_id from " . TABLE_MAIN_PAGES . " where page_id = '" . (int)$current_static_category_id . "'");
        $current_static_category = tep_db_fetch_array($current_static_category_query);

        if ($last_static_category['parent_id'] == $current_static_category['parent_id']) {
          for ($i=0; $i<($sucp_size-1); $i++) {
            $stcPath_new .= '_' . $stcPath_array[$i];
          }
        } else {
          for ($i=0; $i<$sucp_size; $i++) {
            $stcPath_new .= '_' . $stcPath_array[$i];
          }
        }
        $stcPath_new .= '_' . $current_static_category_id;

        if (substr($stcPath_new, 0, 1) == '_') {
          $stcPath_new = substr($stcPath_new, 1);
        }
      }
    } else {
      $stcPath_new = implode('_', $stcPath_array);
    }

    return 'stcPath=' . $stcPath_new;
  }
  
  function tep_get_subscription_subcategories(&$subcategories_array, $parent_id = 0) {
    $subcategories_query = tep_db_query("select subscription_categories_id from " . TABLE_SUBSCRIPTION_CATEGORIES . " where parent_id = '" . (int)$parent_id . "'");
    while ($subcategories = tep_db_fetch_array($subcategories_query)) {
      $subcategories_array[sizeof($subcategories_array)] = $subcategories['subscription_categories_id'];
      if ($subcategories['subscription_categories_id'] != $parent_id) {
        tep_get_subscription_subcategories($subcategories_array, $subcategories['subscription_categories_id']);
      }
    }
  }

  


////
// Parse and secure the sucPath parameter values
  function tep_parse_subscription_category_path($sucPath) {
// make sure the category IDs are integers
    $sucPath_array = array_map('tep_string_to_int', explode('_', $sucPath));

// make sure no duplicate category IDs exist which could lock the server in a loop
    $tmp_array = array();
    $n = sizeof($sucPath_array);
    for ($i=0; $i<$n; $i++) {
      if (!in_array($sucPath_array[$i], $tmp_array)) {
        $tmp_array[] = $sucPath_array[$i];
      }
    }

    return $tmp_array;
  }
  
  ////
// Parse and secure the sucPath parameter values
  function tep_parse_static_category_path($stcPath) {
// make sure the category IDs are integers
    $stcPath_array = array_map('tep_string_to_int', explode('_', $stcPath));

// make sure no duplicate category IDs exist which could lock the server in a loop
    $tmp_array = array();
    $n = sizeof($stcPath_array);
    for ($i=0; $i<$n; $i++) {
      if (!in_array($stcPath_array[$i], $tmp_array)) {
        $tmp_array[] = $stcPath_array[$i];
      }
    }

    return $tmp_array;
  }
  
  
  function tep_get_subscription_name($subscription_id, $language_id = 0) {
    global $languages_id;

    if ($language_id == 0) $language_id = $languages_id;
    $subscription_query = tep_db_query("select subscription_name from " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " where subscription_id = '" . (int)$subscription_id . "' and language_id = '" . (int)$language_id . "'");
    $subscription = tep_db_fetch_array($subscription_query);

    return $subscription['subscription_name'];
  }
  
// send subscription order email
function tep_send_subscription_order_email($i){
	//global $currencies,$order,$customer_id,$insert_id,$order_timestamp;
	global $currencies,$order,$customer_id,$insert_id,$referenceID;
	if ((int)EMAIL_ACTIVATE!=1) return;

	// get subscription details	
	$subscription_query=tep_db_query("SELECT su.subscription_id,su.subscription_period,su.subscription_renewal_end,su.subscription_costs,su.subscription_tax_class_id,su.subscription_type,os.start_date,os.finish_date from " . 
							   TABLE_SUBSCRIPTIONS . " su, " .TABLE_ORDERS_SUBSCRIPTIONS  . " os  where su.subscription_id='" . (int)$order->products[$i]['id'] . "' and os.products_id = su.subscription_id ");

	if (tep_db_num_rows($subscription_query)<=0) return;    
	$subscription_result=tep_db_fetch_array($subscription_query);
	
	// get mail template details
	$details_r=array();
	$details_r['type']='RCF';
	$details_r['table']=TABLE_SUBSCRIPTION_MESSAGES;
	$details_r['subscription_id']=$subscription_result['subscription_id'];
	tep_get_template($details_r);

	if ($details_r['html_text']=="") return;

	// get the renewal end date of this reservation
	$renewal_date=date('Y-m-d',tep_dateadd(strtotime(getServerDate()),"day",$subscription_result["subscription_period"]-$subscription_result["subscription_renewal_end"]));
	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_HTTPS_CATALOG:HTTP_SERVER . DIR_WS_HTTP_CATALOG);
	
	// get some customer information 
	$order_query=tep_db_query("SELECT customers_fax,customers_dob from " . TABLE_CUSTOMERS . " where customers_id='" . (int)$customer_id . "'");
	$order_result=tep_db_fetch_array($order_query);
 
 	//for direct deposit module
	if($GLOBALS['payment']=='ausbank')
		//$direct_deposit=sprintf(TEXT_DIRECT_DEPOSIT,substr(strtolower($order->customer['firstname']),0,3) , substr(strtolower($order->customer['lastname']),0,3) , $order_timestamp);
		$direct_deposit=sprintf(TEXT_DIRECT_DEPOSIT,$referenceID);
	else 
		$direct_deposit='';	
	//subscription type
   	if($subscription_result['subscription_type']=='C'){
			$subscription_type=TEXT_CASUAL;
	}else if($subscription_result['subscription_type']=='S'){
			$subscription_type=TEXT_SEASON;
	}else if($subscription_result['subscription_type']=='D'){
		$subscription_type=TEXT_DEGITAL;
	}else if($subscription_result['subscription_type']=='T'){
		$subscription_type=TEXT_TANGIBILE;
	}	
	//subscription type
  	$replace_array=array(	TEXT_FN=>$order->customer['firstname'],
							TEXT_LN=>$order->customer['lastname'],
							TEXT_DF=>format_date($order_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $order->customer['email_address'] . '"><u>' . $order->customer['email_address'] .'</u></a>',
							TEXT_TN=>$order->customer['telephone'],
							TEXT_FX=>$order_result['customers_fax'],
							TEXT_SA=>$order->customer['street_address'],
							TEXT_SU=>$order->customer['suburb'],
							TEXT_PC=>$order->customer['postcode'],
							TEXT_CT=>$order->customer['city'],
							TEXT_ST=>$order->customer['state'],
							TEXT_CY=>$order->customer['country']['title'],
							
							TEXT_SUB_NA=>$order->products[$i]['name'],
							TEXT_SUB_CO=>$currencies->format(tep_add_tax($subscription_result['subscription_costs'],tep_get_tax_rate($subscription_result['subscription_tax_class_id']))),
							TEXT_SUB_PE=>$subscription_result["subscription_period"],
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_SUBSCRIPTION_INVITE_FRIEND,'R=1&path=ACC&suID=' . $subscription_result['subscription_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_SUBSCRIPTION_UNSUBSCRIBE,'R=1&cID=' . $customer_id,'NONSSL',false) . '">' . TEST_MAIL_SUB_UN . '</a>',
							TEXT_SUB_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $insert_id,'NONSSL',false) . '">' . TEST_MAIL_SUB_IL . '</a>',
							TEXT_RE=>format_date($renewal_date),
							TEXT_SL=>'<a href="' . tep_href_link(FILENAME_DEFAULT) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . STORE_OWNER . '</a>',
							TEXT_SP=>'<img src="' . $url_home . DIR_WS_TEMPLATES . TEMPLATE_NAME . '/images/' .COMPANY_LOGO . '" title="' . STORE_NAME . '">',
							TEXT_ON=>$insert_id,
							TEXT_OC=>$order->info['comments'],
							TEXT_OD=>date(EVENTS_DATE_FORMAT),
							TEXT_BT=>$order->billing['firstname'] . ' ' . $order->billing['lastname'],
							TEXT_BA=>$order->billing['street_address'],
							TEXT_PY=>$order->info['payment_method'],
							TEXT_DD=>$direct_deposit,
							TEXT_TX=>$currencies->format(tep_calculate_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']),
							TEXT_SB=>$currencies->format($order->products[$i]['final_price']*$order->products[$i]['qty']),
							TEXT_TL=>$currencies->format(tep_add_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']),
							TEXT_SUB_TY=>$subscription_type,
							TEXT_SUB_SD=>$subscription_result['start_date'],
							TEXT_SUB_FD=>$subscription_result['finish_date']
							);
	$sql_array=array(	'orders_id'=>$insert_id,
						'subscription_id'=>$subscription_result['subscription_id'],
						'customers_id'=>$customer_id,
						'message_type'=>'RCF',
						'message_mode'=>'E',
						'email_address'=>$order->customer['email_address'],
						'send_date'=>'now()'
					);
				
	tep_replace_template($details_r,$replace_array);
	tep_strip_html($details_r);
	// form the address array to send
	$details_r['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
	$details_r['to_email']=$order->customer['email_address'];
	$details_r['from_name']=STORE_OWNER;
	$details_r['from_email']=STORE_OWNER_EMAIL_ADDRESS;
	tep_send_email($details_r);
			if (SEND_EXTRA_ORDER_EMAILS_TO != ''){
			$details_r['to_email']=SEND_EXTRA_ORDER_EMAILS_TO;
			tep_send_email($details_r);
			}
	tep_db_perform(TABLE_SUBSCRIPTION_MESSAGES_HISTORY,$sql_array);
}

// send invite email to selected friends email address
function tep_send_subscription_invite_email(&$send_details){

	global $currencies,$languages_id;

	if (!is_array($send_details)) return;

	// fetch the subscription details
	$subscription_query=tep_db_query("select su.subscription_id,sud.subscription_name,su.subscription_period,su.subscription_costs,su.subscription_tax_class_id from " . 
								TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION .  " sud " .
								"where su.subscription_id='" . $send_details['subscription_id'] . "' and su.subscription_id=sud.subscription_id and sud.language_id='" . $languages_id . "'");

	if (tep_db_num_rows($subscription_query)<=0) return;

	$subscription_result=tep_db_fetch_array($subscription_query);

	$tax_rate=tep_get_tax_rate($subscription_result['subscription_tax_class_id']);

	// fetch the customer details
	$customer_query=tep_db_query("select customers_firstname,customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " where customers_id='" . $send_details['customers_id'] . "'");
	if (tep_db_num_rows($customer_query)<=0) return;
	$customer_result=tep_db_fetch_array($customer_query);

	$details=array();
	$details['type']=$send_details['mail_type'];
	$details['table']=TABLE_SUBSCRIPTION_MESSAGES;
	$details['subscription_id']=$send_details['subscription_id'];
	
	tep_get_template($details);
	
	$replace_array=array( 	TEXT_SUB_NA=>$subscription_result['subscription_name'],
							TEXT_SUB_CO=>$currencies->format(tep_add_tax($subscription_result['subscription_costs'],$tax_rate)),
							TEXT_SUB_PE=>$subscription_result["subscription_period"],
						//	TEXT_SUB_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
							TEXT_CF=>$customer_result['customers_firstname'],
							TEXT_CL=>$customer_result['customers_lastname'],
							TEXT_IC=>$send_details['comments'],
							TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
							);
	//replace template
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);
	$email_array=&$send_details["address"];
	$name_array=&$send_details["name"];

	// send email
	$message = new email(array('X-Mailer: osCommres'));
	for ($icnt=0;$icnt<sizeof($email_array);$icnt++){
		$mes_content=$details['html_text'];
		$mes_text=eregi_replace("%%" . TEXT_FE . "%%",$name_array[$icnt] . "",$mes_content);
		
		$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 ($mes_text!='' && $email_array[$icnt]!=''){

			if ($mail_data_result['message_format'] != 'T') {
				$message->add_html($mes_text, $text);
			} else {
				$message->add_text($text);
			}
			$message->build_message();

			$message->send($name_array[$icnt], $email_array[$icnt], $customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'], $customer_result['customers_email_address'], $details['subject']);
		}
	}
}

// replace the invite email content
function tep_replace_subscription_invite_mail_content($send_details){
global $currencies,$languages_id;
	if (!is_array($send_details)) return;

	// fetch the subscription details
	$subscription_query=tep_db_query("select su.subscription_id,sud.subscription_name,su.subscription_period,su.subscription_costs,su.subscription_tax_class_id from " . 
								TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION .  " sud " .
								"where su.subscription_id='" . $send_details['subscription_id'] . "' and su.subscription_id=sud.subscription_id and sud.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($subscription_query)<=0) return;
	
	$subscription_result=tep_db_fetch_array($subscription_query);
	
	$tax_rate=tep_get_tax_rate($subscription_result['subscription_tax_class_id']);
	
	// fetch the customer detail
	$customer_query=tep_db_query("select customers_firstname,customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " where customers_id='" . $send_details['cID'] . "'");
	if (tep_db_num_rows($customer_query)<=0) return;
	$customer_result=tep_db_fetch_array($customer_query);

	
	// prepare the merge array
	$replace_array=array( 	TEXT_SUB_NA=>$subscription_result['subscription_name'],
							TEXT_SUB_CO=>$currencies->format(tep_add_tax($subscription_result['subscription_costs'],$tax_rate)),
							TEXT_SUB_PE=>$subscription_result["susbcription_period"],
						//	TEXT_SUB_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
							TEXT_CF=>$customer_result['customers_firstname'],
							TEXT_CL=>$customer_result['customers_lastname'],
							TEXT_IC=>$send_details['comments'],
							TEXT_FE=>TEST_MAIL_FE,
							TEXT_IC=>TEST_MAIL_IC,
							TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
							);

	$mes_content=$send_details['text'];

	// replace the merge details
	while (list($key, $value) = each($replace_array))
		$mes_content=eregi_replace("%%" . $key  . "%%",$value . "",$mes_content);

	return $mes_content;	
}

// subscription tree structure

 function tep_get_subscription_output_tree($parent_id = '0',&$content,$default,$subscription_category_id=0) {
    global $languages_id,$selected_name,$login_id,$login_groups_type;

	// iterate with nested category
	
	$subscription_where = "";
	if($subscription_category_id>0)$subscription_where = " suc.subscription_categories_id='" . $subscription_category_id . "' ";
	$subscription_category_query = tep_db_query("select suc.subscription_categories_id, sucd.subscription_categories_name, suc.parent_id from " . TABLE_SUBSCRIPTION_CATEGORIES . " suc, " . TABLE_SUBSCRIPTION_CATEGORIES_DESCRIPTION . " sucd where suc.subscription_categories_id = sucd.subscription_categories_id and sucd.language_id = '" . (int)$languages_id . "' and suc.parent_id = '" . (int)$parent_id . "' " . $subscription_where . " order by suc.sort_order, sucd.subscription_categories_name");
	while ($subscription_category = tep_db_fetch_array($subscription_category_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_subscription_category_space($subscription_category['subscription_categories_id']) . tep_output_string($subscription_category['subscription_categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of subscription of particular category
		$subscription_query=tep_db_query("select sud.subscription_name,sud.subscription_id from " . TABLE_SUBSCRIPTIONS . ' su, ' . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud, " . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sucd where sucd.subscription_categories_id='" . $subscription_category['subscription_categories_id'] . "' and sud.language_id = " . (int)$languages_id . " " . SUBSCRIPTION_CONDITION_STATUS. " and su.subscription_id=sucd.subscription_id and su.subscription_id=sud.subscription_id order by sud.subscription_name");
		while ($subscription=tep_db_fetch_array($subscription_query))
		{ 
			$content .= '<option style="color:#000000" value="' . tep_output_string($subscription['subscription_id']) . '"';
			if ($default == $subscription['subscription_id']){ 
				$selected_name=$subscription['subscription_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . tep_output_string($subscription['subscription_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}    
		tep_get_subscription_output_tree($subscription_category['subscription_categories_id'], $content,$default);
		$content.='</optgroup>';
	}

}
	function write_subscription_category_space($category_id){
	    global $languages_id,$selected_name,$login_id,$login_groups_type;
		$sql = "select parent_id,sc.subscription_categories_id,subscription_categories_name from " . TABLE_SUBSCRIPTION_CATEGORIES . " sc," . TABLE_SUBSCRIPTION_CATEGORIES_DESCRIPTION . " scd where sc.subscription_categories_id=scd.subscription_categories_id and scd.language_id = '" . (int)$languages_id . "' and sc.subscription_categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_subscription_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_subscription_select_menu($name, $values, $default = '', $parameters = '', $required = false,$initial_category_id=0,$need_all=true,$initial_parent_id=0) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_SELECT . '</option>';
		
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		tep_get_subscription_output_tree($initial_parent_id,$content,$default,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
	// subscription tree
	function tep_get_subscription_array_single($first=''){
		global $languages_id;
		$subscription_array=array();
		$subscription_query=tep_db_query("SELECT su.subscription_id,sud.subscription_name from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id and language_id='" . $languages_id . "' " . SUBSCRIPTION_CONDITION_STATUS . " order by sud.subscription_name");
		
		while($subscription_result=tep_db_fetch_array($subscription_query)){
			$subscription_array[]=array('id'=>$subscription_result['subscription_id'],'text'=>$subscription_result['subscription_name']);
		}
		return $subscription_array;
	} 
//subscription discount start
function subscription_discount($subscription_id,$date,$fees)
{
  $discount_amount=0;
  
  $discount_query=tep_db_query("SELECT discount_value,discount_type from " . TABLE_SUBSCRIPTION_DISCOUNTS . " where subscription_id='" . $subscription_id . "' and '" . $date . "'>=discount_start_date and '" . $date . "'<=discount_end_date order by discount_start_date");
  if (tep_db_num_rows($discount_query)){
    $discount_result=tep_db_fetch_array($discount_query);
	// P=>Percentage A=>Amount
    if ($discount_result['discount_type']=='P'){
       $discount_amount=$fees*$discount_result['discount_value']/100;
    } else {
       $discount_amount=$discount_result['discount_value'];
    }
  }
  return $discount_amount;   
}

//end
?>
