<?php
/*
  $Id: checkout_process.php,v 1.2 2003/09/24 15:34:25 wilt Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/
// Set flag that this is a parent file
  define( '_FEXEC', 1 );
  require('includes/application_top.php');
  require(DIR_WS_CLASSES . '/currencies.php');
  include(DIR_WS_FUNCTIONS . 'events_sessions.php');
  define('BLOCKED_USER_ERROR','Blocked User');
  define('SUSPENDED_USER_ERROR','User Suspended Temporarily');
  $server_date = getServerDate(true);
  $currency=DEFAULT_CURRENCY;
  $currencies=new currencies;  
  
  
  // if the customer is not logged on, redirect them to the login page
  // modified for wallet payment -start
	//if (tep_session_is_registered("payment_page") && $payment_page=="wallet") tep_redirect(tep_href_link(FILENAME_WALLET_CHECKOUT_PROCESS,tep_get_all_input_params() .'&validID=' . $checkID,'SSL'));	
  // modified for wallet payment -end
	
  $payment_return1=(isset($HTTP_GET_VARS['payment_return1'])?$HTTP_GET_VARS['payment_return1']:'');
  $payment_return2=(isset($HTTP_GET_VARS['payment_return2'])?$HTTP_GET_VARS['payment_return2']:'');	
	
	 if(!tep_session_is_registered('customer_id')){
	 $customer_id=$HTTP_GET_VARS['customers_id'];
	 
	 }
// load selected payment module
	 require(DIR_WS_CLASSES . 'payment.php');
	 $payment_modules = new payment($payment);
	
// load the selected shipping module
	 require(DIR_WS_CLASSES . 'shipping.php');
	 $shipping_modules = new shipping($shipping);
	
	 
	 require(DIR_WS_CLASSES . 'order.php');
	 $order = new order;
	 
	 $type_array=array('B'=>TEXT_SUBSCRIPTION_BASIC,
					'C'=>TEXT_SUBSCRIPTION_CASUAL,
					'S'=>TEXT_SUBSCRIPTION_SEASONAL
					);
	
// load the before_process function from the payment modules
	 $payment_modules->before_process();

	 require(DIR_WS_CLASSES . 'order_total.php');
	 $order_total_modules = new order_total;
	
	 $order_totals = $order_total_modules->process();
	 $total_weight = $cart->show_weight();
	 $product_new_order_ids='0';
	 $event_new_order_ids='0';
	 $subscription_new_order_ids='0';
	 $service_new_order_ids='0';
	
// BOF: WebMakers.com Added: Downloads Controller
	   $sql_data_array = array(
							'customers_id' => $customer_id,
							'customers_name' => $order->customer['firstname'] . ' ' . $order->customer['lastname'],
							'customers_company' => $order->customer['company'],
							'customers_street_address' => $order->customer['street_address'],
							'customers_suburb' => $order->customer['suburb'],
							'customers_city' => $order->customer['city'],
							'customers_postcode' => $order->customer['postcode'], 
							'customers_state' => $order->customer['state'], 
							'customers_country' => $order->customer['country']['title'], 
							'customers_telephone' => $order->customer['telephone'], 
							'customers_email_address' => $order->customer['email_address'],
							'customers_second_telephone'=>$order->customer['second_telephone'],
							'customers_second_email_address'=>$order->customer['second_email_address'],
							'customers_fax'=>$order->customer['fax'],
							'customers_address_format_id' => $order->customer['format_id'], 
							'delivery_name' => $order->delivery['name'],
							'delivery_company' => $order->delivery['company'],
							'delivery_street_address' => $order->delivery['street_address'], 
							'delivery_suburb' => $order->delivery['suburb'], 
							'delivery_city' => $order->delivery['city'], 
							'delivery_postcode' => $order->delivery['postcode'], 
							'delivery_state' => $order->delivery['state'], 
							'delivery_country' => $order->delivery['country']['title'], 
							'delivery_address_format_id' => $order->delivery['format_id'], 
							'billing_name' => $order->billing['name'], 
							'billing_company' => $order->billing['company'],
							'billing_street_address' => $order->billing['street_address'], 
							'billing_suburb' => $order->billing['suburb'], 
							'billing_city' => $order->billing['city'], 
							'billing_postcode' => $order->billing['postcode'], 
							'billing_state' => $order->billing['state'], 
							'billing_country' => $order->billing['country']['title'], 
							'billing_address_format_id' => $order->billing['format_id'], 
							'payment_method' => $order->info['payment_method'],
							'reference_id' => $referenceID,
// BOF: Lango Added for print order mod 
							'payment_info' => $GLOBALS['payment_info'],
// EOF: Lango Added for print order mod 
							'cc_type' => $order->info['cc_type'], 
							'cc_owner' => $order->info['cc_owner'], 
							'cc_number' => $order->info['cc_number'], 
							'cc_expires' => $order->info['cc_expires'], 
							'date_purchased' => getServerDate(true), 
							'last_modified' => getServerDate(true),
							'orders_status' => $order->info['order_status'], 
							'currency' => $order->info['currency'], 
							'currency_value' => $order->info['currency_value'],
							'fulfiller_Status'=>$order->info['order_status'],
							'owd_cost' =>$order->info['owd_cost'],
							'payment_return1'=>$payment_return1,
							'payment_return2'=>$payment_return2,
							'shipping_weight'=>$total_weight);
							
		//print_r ($sql_data_array);
		//exit;					
// EOF: WebMakers.com Added: Downloads Controller
	if(tep_session_is_registered('order_id')){
		tep_db_perform(TABLE_ORDERS, $sql_data_array,"update"," orders_id='" . (int)$order_id . "'");
		$insert_id = $order_id;
		$mode="edit";
	}else{
		$insert_sql_data=array('date_purchased' => $server_date);
		$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
		tep_db_perform(TABLE_ORDERS, $sql_data_array);
		$insert_id = tep_db_insert_id();
		$mode="new";
	}
	//save multiple customers in customers and orders table
	$result_array=array();
	$attendees = $cart->attendees;
	$group_members=$cart->get_attendee_names();	
	tep_db_query("delete from " . TABLE_CUSTOMERS_TO_CUSTOMERS . " where orders_id='" . (int)$insert_id . "'");
    for($icnt=0;$icnt<count($attendees);$icnt++){
		$attendee=$attendees[$icnt];
		//check customer already exists
		$customer_check=tep_db_query("select customers_id from ".TABLE_CUSTOMERS." where customers_email_address='".$attendees[$icnt]["email_address"]."'"); 
		//check customer already exists
		$customer_check_result=tep_db_fetch_array($customer_check);
		if(tep_db_num_rows($customer_check)<=0){ 
			  $makePassword = randomize();
			  $password=tep_encrypt_password($makePassword);
        	 $encription_style=(defined('ENCRYPTION_STYLE'))?ENCRYPTION_STYLE:'O';
				$customer_array = array('customers_firstname'=>$attendees[$icnt]["first_name"],
						 		      'customers_lastname'=>$attendees[$icnt]["last_name"],
								      'customers_email_address'=>$attendees[$icnt]["email_address"],
									  'customers_password' => $password,
									  'encryption_style' => $encription_style);
			  
				tep_db_perform(TABLE_CUSTOMERS, $customer_array);
				$attendees[$icnt]["id"]=tep_db_insert_id();
				$addrees_book_array = array(
			                    'customers_id'=>$attendees[$icnt]["id"],
			                    'entry_firstname'=>$attendees[$icnt]["first_name"],
									  'entry_lastname'=>$attendees[$icnt]["last_name"],
									  'entry_street_address'=>$attendees[$icnt]["street_address"],
									  'entry_city'=>$attendees[$icnt]["city"],
									  'entry_country_id'=>$attendees[$icnt]["country"],
									  'entry_postcode'=>$attendees[$icnt]["postcode"]);
				 
			  $zone_query = tep_db_query("select distinct zone_id from " . TABLE_ZONES . " where zone_country_id = '" . (int)$attendees[$icnt]["country"] . "' and (zone_name like '" . tep_db_input($attendees[$icnt]["state"]) . "%' or zone_code like '%" . tep_db_input($attendees[$icnt]["state"]) . "%')");
			  $zone = tep_db_fetch_array($zone_query);
			  $zone_id = $zone['zone_id'];
			  if ($zone_id > 0) {
		          $addrees_book_array['entry_zone_id'] = $zone_id;
		          $addrees_book_array['entry_state'] = '';
		        } else {
		          $addrees_book_array['entry_zone_id'] = '0';
		          $addrees_book_array['entry_state'] = $attendees[$icnt]["state"];
		      }
			   
			  tep_db_perform(TABLE_ADDRESS_BOOK,$addrees_book_array);
			  $attendees[$icnt]["address_id"] = tep_db_insert_id();
			  tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$attendees[$icnt]["address_id"] . "' where customers_id = '" . (int)$attendees[$icnt]['id'] . "'");
			  
     		  tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_source_id) values ('" . (int)$attendees[$icnt]['id'] . "', '0','" . $server_date . "', '0')");
			  
			  $attendees[$icnt]["country_name"]=tep_get_country_name($attendees[$icnt]["country"]);
			  //store customers_to_customers table
				tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values(".(int)$customer_id.",".(int)$attendees[$icnt]['id'].",".(int)$insert_id.")");
				  //store customers_to_customers table
			  $merge_details=array();
			  $merge_details[TEXT_FN]=$attendees[$icnt]["first_name"];
			  $merge_details[TEXT_LN]=$attendees[$icnt]["last_name"];
			  $merge_details[TEXT_GR] = EMAIL_GREET_NONE;
			  
			  
			 
			  $merge_details[TEXT_SM]=STORE_NAME;
			  $merge_details[TEXT_SN]=STORE_OWNER;
			  $merge_details[TEXT_SE]=STORE_OWNER_EMAIL_ADDRESS;
			  $merge_details[TEXT_LE]=$attendees[$icnt]["email_address"];
			
			  $merge_details[TEXT_LP]=$makePassword;
		
			  $send_details[0]['to_name'] = $attendees[$icnt]["first_name"] . ' ' . $attendees[$icnt]["last_name"];
			  $send_details[0]['to_email'] = $attendees[$icnt]["email_address"];
			  $send_details[0]['from_name']=STORE_OWNER;
			  $send_details[0]['from_email']=STORE_OWNER_EMAIL_ADDRESS;
		
			  tep_send_default_email("CUS",$merge_details,$send_details);
			  
	  	}else{ // customer already exists 
			tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values('".(int)$customer_id."','".(int)$customer_check_result['customers_id']."','".(int)$insert_id."')");
		}
	  }
	  
	  //multiple customers
	 if(tep_session_is_registered("payment_refund"))
	{
		$query=tep_db_query("select * from " . TABLE_ORDERS_TOTAL . " where orders_id='" . (int)$insert_id. "'");
		while($row=tep_db_fetch_array($query))
		{
			switch($row['class'])
			{
				case 'ot_tax':
					$payment_refund_comments.="Previous_tax : " . $row['text'] . " Current_tax : " . $currencies->format($order->info['tax']) . "<br>";
					break;
				case 'ot_shipping':
					$payment_refund_comments.="Previous_shipping : " . $row['text'] . " Current_shipping : " . $currencies->format($order->info['shipping']) . "<br>";
					break;
				case 'ot_subtotal':
					$payment_refund_comments.="Previous_subtotal : " . $row['text'] . " Current_subtotal : " . $currencies->format($order->info['nettotal']) . "<br>";
					break;
				case 'ot_total':
					$payment_refund_comments.="Previous_total : " . $row['text'] . " Current_total : " . $currencies->format($order->info['overall_total']) . "<br>";
					break;
			}
		}
    }
	tep_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id='" . (int)$insert_id. "' ");
	for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
		if($order_totals[$i]['mode']!=1)
		{
		
			$sql_data_array = array(
									'orders_id' => $insert_id,
									'title' => $order_totals[$i]['title'],
									'text' => $order_totals[$i]['text'],
									'value' => $order_totals[$i]['value'],
									'class' => $order_totals[$i]['code'],
									'sort_order' => $order_totals[$i]['sort_order']
									);
			tep_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id='" . (int)$insert_id. "' and class='" . $order_totals[$i]['code']. "'");
			tep_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
		}
	}
	
	
	$customer_notification = (SEND_EMAILS == 'true') ? '1' : '0';
// initialized for the email confirmation
	$products_ordered = '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
	$products_ordered.= '<tr height="30" class="textTableSubHead"><td width="20"><b>' . TEXT_QUANTITY .'</b></td><td colspan="2"><b>'.TEXT_PRODUCTS_NAME.'</b></td><td><b>SKU</b></td><td align="right" width="100"><b>Price</b></td></tr>';
	$subtotal = 0;
	$total_tax = 0;
	$products_type='';
	$events_type='';
	for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
		if($mode=="new")
		{
			if (STOCK_LIMITED == 'true' && $order->products[$i]['element_type']=='P') {
				if (DOWNLOAD_ENABLED == 'true') {
					$stock_query_raw = "SELECT products_quantity,products_image_1,pad.products_attributes_filename
										FROM " . TABLE_PRODUCTS . " p
										LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa
										 ON p.products_id=pa.products_id
										LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
										 ON pa.products_attributes_id=pad.products_attributes_id
										WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'";
	// Will work with only one option for downloadable products
	// otherwise, we have to build the query dynamically with a loop
					$products_attributes = $order->products[$i]['attributes'];
					if (is_array($products_attributes)) {
						$stock_query_raw .= " AND pa.options_id = '" . $products_attributes[0]['option_id'] . "' AND pa.options_values_id = '" . $products_attributes[0]['value_id'] . "'";
					}
					$stock_query = tep_db_query($stock_query_raw);
				} else {
					$stock_query = tep_db_query("select p.products_image_1,p.products_quantity from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where p.products_id = pa.products_id and p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "' and pa.options_id = '" . $products_attributes[0]['option_id'] . "' AND pa.options_values_id = '" . $products_attributes[0]['value_id'] . "'");
					//$stock_query = tep_db_query("select products_image_1,products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
				}
				if (tep_db_num_rows($stock_query) > 0) {
					$stock_values = tep_db_fetch_array($stock_query);
	// do not decrement quantities if products_attributes_filename exists
					if ((DOWNLOAD_ENABLED != 'true') || (!$stock_values['products_attributes_filename'])) {
						$stock_left = $stock_values['products_quantity'] - $order->products[$i]['qty'];
						//$attributes_left=$stock_values['products_attributes_quantity'] - $order->products[$i]['qty'];
					} else {
						$stock_left = $stock_values['products_quantity'];
						//$attributes_left=$stock_valus['products_attributes_quantity'];
					}
					tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $stock_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
				//	tep_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set products_attributes_quantity = '" . $attributes_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "' and options_id = '" . $products_attributes[0]['option_id'] . "' AND options_values_id = '" . $products_attributes[0]['value_id'] . "'");
					if ( ($stock_left < 1) && (STOCK_ALLOW_CHECKOUT == 'false') ) {
						tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
					//	tep_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set products_attributes_quantity = '" . $attributes_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "' and options_id = '" . $products_attributes[0]['option_id'] . "' AND options_values_id = '" . $products_attributes[0]['value_id'] . "'");
					}
				}
			}
		}

		
		if ($order->products[$i]['element_type']=='S'){
			$your_date = $order->products[$i]['subscription_start_date'];
			$subscription_type_sql = "select subscription_date_type from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_get_prid($order->products[$i]['id']);
			$subscription_type_query = tep_db_query($subscription_type_sql);
			$subscription_type_result = tep_db_fetch_array($subscription_type_query);
			if($subscription_type_result['subscription_date_type']=='F')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,subscription_start_date as start_date,subscription_finish_date as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_get_prid($order->products[$i]['id']);
			else if($subscription_type_result['subscription_date_type']=='L')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,date_format(date_add('" . getServerDate(false) . "',INTERVAL 1 DAY),'%Y-%m-%d') as start_date,date_format(date_add('" . getServerDate(false) . "', INTERVAL subscription_period DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_get_prid($order->products[$i]['id']);
			else if($subscription_type_result['subscription_date_type']=='P')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,date_format('" . $your_date . "','%Y-%m-%d') as start_date,date_format(date_add('" . $your_date . "', INTERVAL (subscription_period-1) DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_get_prid($order->products[$i]['id']);
			else
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,subscription_start_date as start_date,subscription_finish_date as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_get_prid($order->products[$i]['id']);
			$subscription_details_query = tep_db_query($subscription_details_sql);
			$subscription_details_result = tep_db_fetch_array($subscription_details_query);
			
		}

// Update products_ordered (for bestsellers list)
		if ($order->products[$i]['element_type']=='P'){
			tep_db_query("update " . TABLE_PRODUCTS . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
			if ($order->products[$i]['discount_id']=='') 
				$discount_id=0;
			else
			    $discount_id=$order->products[$i]['discount_id'];	
			$sql_data_array = array(
							'orders_id' => $insert_id, 
							'products_id' => tep_get_prid($order->products[$i]['id']), 
							'products_model' => $order->products[$i]['model'], 
							'products_name' => $order->products[$i]['name'], 
							'products_price' => $order->products[$i]['price'], 
							'final_price' => $order->products[$i]['final_price'], 
							'products_tax' => $order->products[$i]['tax'], 
							'products_quantity' => $order->products[$i]['qty'],
							'events_type'=>$order->products[$i]['events_type'],
							'products_type'=>$order->products[$i]['element_type'],
							'products_sku'=>$order->products[$i]['sku'],
							'orders_products_status'=>$order->info['order_status'],
							'support_packs_type'=>$order->products[$i]['support_packs_type'], //Support Packs
							'discount_id'=>$discount_id,
							'discount_type'=>$order->products[$i]['discount_type'],
							'discount_text'=>$order->products[$i]['discount_text'],
							'events_id'=>'0'
							);
							
			if($order->products[$i]['order_products_id']>0)
			{
    			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array,'update',"orders_products_id='" . $order->products[$i]['order_products_id']. "'");
	    		$order_products_id = $order->products[$i]['order_products_id'];
				$product_new_order_ids.=$order_products_id .",";
			}
			else{				
    			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
	    		$order_products_id = tep_db_insert_id();
				$product_new_order_ids.=$order_products_id .",";
				//product mode download type------------
				if ($order->products[$i]['product_mode']=="V") { //virtual type
					// $unique_id=md5(date('m/d/y H:i:s'));
					$unique_id=md5(time());
					 $sql_data_array = array('orders_products_download_id'=>$unique_id,
										  'orders_id' => $insert_id, 
										  'orders_products_id' => $order_products_id, 
										  'orders_products_filename' => $order->products[$i]['download_link'], 
										  'download_maxdays' => $order->products[$i]['download_last_date'], 
										  'download_count' => $order->products[$i]['downloads_per_customer']);
					 tep_db_perform(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
				}
			}
			//Support Packs
				if($order->products[$i]['support_packs_type']=='S' && $order->info['order_status']=='2'){
					$pro_id=tep_get_prid($order->products[$i]['id']);
					$packs_query=tep_db_query("select psp.*,sud.subscription_name,su.support_minutes from " . TABLE_PRODUCTS_TO_SUPPORT_PACKS . " psp, " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id and sud.subscription_id=psp.subscription_id and sud.language_id='" . $languages_id ."' and psp.product_id='" . $pro_id . "'");
					while($packs_result=tep_db_fetch_array($packs_query)){
						$sql_data_packs_array=array(
												'products_id' =>$pro_id,
												'subscription_id'=>$packs_result['subscription_id'],
												'subscription_name' =>$packs_result['subscription_name'],
												'orders_id' =>$insert_id,
												'no_users'=>$packs_result['no_users'],
												'support_minutes'=>$packs_result['support_minutes']
												);
						tep_db_perform(TABLE_ORDERS_PRODUCTS_SUPPORT_PACKS,$sql_data_packs_array);
						$support_packs_id=tep_db_insert_id();
						$ln=$packs_result['no_users'];
						for($lcnt=0;$lcnt<$ln;$lcnt++){
							$sql_data_license_array=array(
													'support_packs_id'=>$support_packs_id
													);
							tep_db_perform(TABLE_SUPPORT_PACKS_LICENSE,$sql_data_license_array);
						}
					}							
				}		
			//Support Packs			
		}
		
		if ($order->products[$i]['element_type']=='S'){
			$sql_data_array = array(
							'orders_id' => $insert_id, 
							'products_id' => tep_get_prid($order->products[$i]['id']), 
							'products_model' =>  $type_array[$order->products[$i]['type']], 
							'products_name' => $order->products[$i]['name'], 
							'products_price' => $order->products[$i]['price'], 
							'final_price' => $order->products[$i]['final_price'], 
							'products_tax' => $order->products[$i]['tax'], 
							'products_quantity' => $order->products[$i]['qty'],
							'events_type'=>$order->products[$i]['events_type'],
							'products_type'=>$order->products[$i]['element_type'],
							'orders_products_status'=>$order->info['order_status'],
							'events_id'=>'0'
							);
					
			if($order->products[$i]['order_products_id']>0)
			{
				tep_db_perform(TABLE_ORDERS_PRODUCTS,$sql_data_array,"update","orders_products_id='" .$order->products[$i]['order_products_id']. "'");
				$order_products_id=$order->products[$i]['order_products_id'];
				$subscription_new_order_ids.=$order_products_id .",";
			}
			else{
    			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
    			$order_products_id = tep_db_insert_id();
				$subscription_new_order_ids.=$order_products_id .",";
			}
			$subscription_first_sql_array = array('orders_id'=>$insert_id,
									'products_id' => $subscription_details_result["subscription_id"],
									'type' => $subscription_details_result["type"],
									'deliveries' => $subscription_details_result["deliveries"],
									'deliveries_perday' => $subscription_details_result["deliveries_perday"],
									'deliveries_name' => $subscription_details_result["deliveries_name"],
									'orders_products_id' => $order_products_id
									);
									

			if($subscription_details_result["subscription_date_type"]=='F' || $subscription_details_result["subscription_date_type"]=='L' || $subscription_details_result["subscription_date_type"]=='P'){
				$subscription_second_sql_array = array('start_date' => $subscription_details_result["start_date"],
												'finish_date' => $subscription_details_result["finish_date"]);
			}else{ 
				$subscription_second_sql_array = array('start_date' => '0000-00-00',
													'finish_date' => '0000-00-00');
			}
			$subscription_sql_array = array_merge($subscription_first_sql_array,$subscription_second_sql_array);
			
			if($order->products[$i]['order_products_id']>0)
				tep_db_perform(TABLE_ORDERS_SUBSCRIPTIONS,$subscription_sql_array,'update',"orders_products_id='" . $order->products[$i]['order_products_id']. "'");
			else
				tep_db_perform(TABLE_ORDERS_SUBSCRIPTIONS,$subscription_sql_array);
		}
		if ($order->products[$i]['element_type']=='V'){
			$prid=$order->products[$i]['id'];
			$sql_data_array = array(
							'orders_id' => $insert_id, 
							'products_id' => $prid, 
							'products_model' => $order->products[$i]['model'], 
							'products_name' => $order->products[$i]['name'], 
							'products_price' => $order->products[$i]['price'], 
							'final_price' => $order->products[$i]['final_price'], 
							'products_tax' => $order->products[$i]['tax'], 
							'products_quantity' => $order->products[$i]['qty'],
							'events_type'=>'',
							'products_type'=>$order->products[$i]['element_type'],
							'orders_products_status'=>$order->info['order_status'],
							'events_id'=>'0'
							);
			if($order->products[$i]['order_products_id']>0)
			{
    			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array,"update","orders_products_id='" . $order->products[$i]['order_products_id']. "'");
    			$order_products_id = $order->products[$i]['order_products_id'];
				$service_new_order_ids.=$order_products_id .",";
			}
			else
			{
    			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
    			$order_products_id = tep_db_insert_id();
				$service_new_order_ids.=$order_products_id .",";
			}
			
			// insert date into services
			$sql_data_array = array(
							'orders_id' => $insert_id,
							'products_id'=>$prid,
							'start_date'=>$order->products[$i]['others']['start_date'],
							'end_date'=>$order->products[$i]['others']['end_date'],
							'start_time'=>$order->products[$i]['others']['start_time'],
							'end_time'=>$order->products[$i]['others']['end_time'],
							'resource_id' => (int)$order->products[$i]['others']['resource_id'],
							'resource_name'=>tep_get_resource_name($order->products[$i]['others']['resource_id'],'resource_name',$languages_id),
							'orders_products_id'=>$order_products_id
							); 
							
			if($order->products[$i]['order_products_id']>0)
	    		tep_db_perform(TABLE_ORDERS_SERVICES, $sql_data_array,"update","orders_products_id='" . $order->products[$i]['order_products_id']. "'");
			else
	    		tep_db_perform(TABLE_ORDERS_SERVICES, $sql_data_array);
		} 
// if the product is of type  event
		if ($order->products[$i]['element_type']=='E'){
			
			//get old orders id if we are gettting reminder amount
			$old_orders_id=isset($order->products[$i]['old_orders_id'])?(int)$order->products[$i]['old_orders_id']:0;
			
			$session_query = tep_db_query("select events_id,events_fees,waitfee_vip,events_tax_class_id,session_style from " . TABLE_EVENTS . " e where events_id = '" . (int)$order->products[$i]['id'] . "'");
			$session_result=tep_db_fetch_array($session_query);
			
			$sessions=&$order->products[$i]['sessions'];
			$session_dates=array();
			
			$prev_orders_id=isset($order->products[$i]['old_orders_id'])?(int)$order->products[$i]['old_orders_id']:0;

			if ($prev_orders_id>0) {
				$prev_query=tep_db_query("SELECT op.products_id,op.products_tax,op.events_fees,op.final_price from ". TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_id='" . (int)$prev_orders_id . "' and s.events_id='" . (int)$session_result["events_id"] . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.waitlist_type='P'");
				if ($session_result["session_style"]!="E"){
					while($prev_result=tep_db_fetch_array($prev_query)){
						$prev_tax=$prev_result["products_tax"];
						if (isset($sessions[$prev_result["products_id"]])){
							$sessions[$prev_result["products_id"]]['events_fees']=$prev_result["events_fees"];
							$sessions[$prev_result["products_id"]]['fees']=$prev_result["events_fees"]-$prev_result["final_price"];
						}
					}
				} else {
					$details=tep_get_orders_reminder_details($prev_orders_id,$session_result["events_id"],$session_result["session_style"],true);
					$calculate_amount=0; // actual calculated amount
					$prepared_amount=$details['product_total']-($details['order_total']+$details['confirm_paid']); //final prepared amount to be paid
					$updated_amount=$details['confirm_total']-$details['confirm_paid'];  // remaining waitlist amount
					if ($updated_amount>=$details['order_total']) $updated_amount=0;
					else $updated_amount=$details['order_total']-$updated_amount;

					while($prev_result=tep_db_fetch_array($prev_query)){
						$prev_tax=$prev_result["products_tax"];
						if (isset($sessions[$prev_result["products_id"]])){
							$calculate_amount+=$prev_result['events_fees'];
							$sessions[$prev_result["products_id"]]['events_fees']=$prev_result["events_fees"];
							if ($calculate_amount<=$updated_amount){
								$new_price=0;
							} else if ($prepared_amount>$prev_result['events_fees']) {
								$new_price=$prev_result['events_fees'];
								$prepared_amount-=$prev_result['events_fees'];
							} else {
								$new_price=$prepared_amount;
							}
							$sessions[$prev_result["products_id"]]['fees']=$new_price;
						}
					}
				}
			}
			
			reset($sessions);			
			while(list($id,)=each($sessions)){
			//$order->products[$i]['final_price']=$events_fees;
			//$order->products[$i]['price']=$events_fees;
				if ($sessions[$id]['type']=='U') 
					$etype='R';
				else
					$etype=$sessions[$id]['type'];

				if ($etype!='W')
					$events_type=$etype;

				$sql_data_array=array( 	'orders_id' => $insert_id, 
										'products_id' => $id,
										'products_model' => date('Y-m-d',strtotime($sessions[$id]['date'])), 
										'products_name' => $order->products[$i]['name'], 
										'products_price' => $sessions[$id]['fees'],
										'final_price' => $sessions[$id]['fees'],
										'products_tax' => ($prev_orders_id>0?$prev_tax:$order->products[$i]['tax']),
										'products_quantity' => $order->products[$i]['qty'],
										'events_type'=>$etype,
										'waitlist_type'=>$sessions[$id]['group'],
										'events_fees'=>$sessions[$id]['fees'],
										'waitlist_orders_id'=>$prev_orders_id,
										'products_type'=>'E',
										'orders_products_status'=>$order->info['order_status'],
										'events_id'=>$order->products[$i]['id']
										);
				
				$session_dates[]=$sessions[$id]['date'];
				if(isset($sessions[$id]['order_products_id']) && $sessions[$id]['order_products_id']>0)
				{
					tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array,"update","orders_products_id='" .$sessions[$id]['order_products_id'] ."'");
					$order_products_id = $sessions[$id]['order_products_id'];
					$event_new_order_ids.=$order_products_id .",";
				}
				else
				{
					tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
					$order_products_id = tep_db_insert_id();
					$event_new_order_ids.=$order_products_id .",";
				}

				//change previous entries as new one
				if ($old_orders_id>0 && $sessions[$id]['type']=='U'){
					tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set events_type='C',waitlist_type='' where orders_id='" . (int)$old_orders_id . "' and products_id='" . (int)$id . "'");
				}
			}
		   if ($order->products[$i]['answer_type']!="" && $order->products[$i]['answer_value']!=""){
				//tep_db_query("INSERT into " . TABLE_ORDERS_EVENTS_ANSWERS . "(orders_id,events_id,answer_type,answer_value) values('" . $insert_id . "','" . $order->products[$i]["id"] . "','" . tep_db_input($order->products[$i]["answer_type"]) . "','" . tep_db_input($order->products[$i]["answer_value"]) . "')");
		   }
		   if($mode=="new"){
		   	  tep_send_event_order_email($insert_id);
		   }
		}		
		if ($order->products[$i]['element_type']=='S'){
			if($mode=="new"){
			//tep_send_subscription_order_email($i);
			tep_send_subscription_order_email($insert_id);
			}
		}
				   
       // send email about ordered events to user
	$order_total_modules->update_credit_account($i);//ICW ADDED FOR CREDIT CLASS SYSTEM
//------insert customer choosen option to order--------
		$attributes_exist = '0';
		$products_ordered_attributes = '';
		
		if (isset($order->products[$i]['attributes'])) {
			$attributes_exist = '1';
			$attribute_id="";
			for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
			   if ($order->products[$i]['element_type']=="V"){
				$attributes = tep_db_query("select vopt.services_options_name,vopt.services_options_id, voval.services_options_values_name, voval.services_options_values_id,va.options_values_price, va.price_prefix from " . TABLE_SERVICES_OPTIONS . " vopt, " . TABLE_SERVICES_OPTIONS_VALUES . " voval, " . TABLE_SERVICES_ATTRIBUTES . " va where va.service_id = '" . $order->products[$i]['id'] . "' and va.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and va.options_id = vopt.services_options_id and va.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and va.options_values_id = voval.services_options_values_id and vopt.language_id = '" . (int)$languages_id . "' and voval.language_id = '" . (int)$languages_id . "'");
				$attributes_values = tep_db_fetch_array($attributes);
				$sql_data_array = array(
										'orders_id' => $insert_id, 
										'orders_products_id' => $order_products_id, 
										'products_options' => $attributes_values['services_options_name'],
										'products_options_values' => $attributes_values['services_options_values_name'], 
										'options_values_price' => $attributes_values['options_values_price'], 
										'price_prefix' => $attributes_values['price_prefix'],
										'products_type'=>'V',
										'products_options_id'=>$attributes_values['services_options_id'],
										'products_options_values_id'=>$attributes_values['services_options_values_id']
										);
										
				if($order->products[$i]['order_products_id']>0)
					tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array,"update","orders_products_id='" .$order->products[$i]['order_products_id'] . "'");
				else						
					tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);
				$services_attributes .= "\n\t" . $attributes_values['services_options_name'] . ' ' . $attributes_values['services_options_values_name'];
			 }else {
			 		if (DOWNLOAD_ENABLED == 'true') {
					$attributes_query = "select popt.products_options_id,popt.products_options_name,poval.products_options_values_id, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename 
										from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa 
										left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
										on pa.products_attributes_id=pad.products_attributes_id
										where pa.products_id = '" . $order->products[$i]['id'] . "' 
										and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' 
										and pa.options_id = popt.products_options_id 
										and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' 
										and pa.options_values_id = poval.products_options_values_id 
										and popt.language_id = '" . $languages_id . "' 
										and poval.language_id = '" . $languages_id . "'";
          			$attributes = tep_db_query($attributes_query);
				} else {
				  $attributes = tep_db_query("select popt.products_options_id,popt.products_options_name,poval.products_options_values_id,poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . (int)$order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . (int)$languages_id . "' and poval.language_id = '" . (int)$languages_id . "'");
				}
				$attributes_values = tep_db_fetch_array($attributes);
				

				$sql_data_array = array(
										'orders_id' => $insert_id, 
										'orders_products_id' => $order_products_id, 
										'products_options' => $attributes_values['products_options_name'],
										'products_options_values' => $attributes_values['products_options_values_name'], 
										'options_values_price' => $attributes_values['options_values_price'], 
										'price_prefix' => $attributes_values['price_prefix'],
										'products_options_id'=>$attributes_values['products_options_id'],
										'products_options_values_id'=>$attributes_values['products_options_values_id']);
										
				if($order->products[$i]['order_products_id']>0)
					tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array,"update","orders_products_id='" .$order->products[$i]['order_products_id'] . "'");
				else
					tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);
				
        		$products_ordered_attributes .= "\n\t" . $attributes_values['products_options_name'] . ': ' .$attributes_values['products_options_values_name']." ". $currencies->format(tep_add_tax($attributes_values['options_values_price'],$order->products[$i]['tax']))."<br>";
				if($attribute_id!="")
					$attribute_id.="-";
				$attribute_id.=$order->products[$i]['attributes'][$j]['option_id'] . "{" . $order->products[$i]['attributes'][$j]['value_id'] . "}";
      		
      		}
			if($mode=="new"){
				tep_db_query("update " . TABLE_PRODUCTS_STOCK . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . ",products_quantity=products_quantity - " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "' and attributes_id = '" . tep_get_sorted_attribute_ids($attribute_id) . "'");
				tep_db_query("update " . TABLE_PRODUCTS_STOCK . " set attribute_status=0 where products_quantity<=0 and products_id=" . tep_get_prid($order->products[$i]['id']) . " and attributes_id = '" . tep_get_sorted_attribute_ids($attribute_id) . "'");
			}
    	  }
		}

//------insert customer choosen option eof ----
		$total_weight += ($order->products[$i]['qty'] * $order->products[$i]['weight']);
		$total_tax += tep_calculate_tax($total_products_price, $products_tax) * $order->products[$i]['qty'];
		$total_cost += $total_products_price;
		if ($order->products[$i]['element_type']=='P'){
			
			$products_ordered .= '<tr class="textTableContent" height="56">' . 
									'<td valign="top"  width="40" class="textMain"><br>'. $order->products[$i]['qty'] .' x </td>' .
									'<td width="55" valign="top" class="textMain"><br>'. tep_product_email_image($stock_values["products_image_1"],$order->products[$i]['name'],'style="width:50px;height:50px"').'</td>' . 
									'<td valign="top" class="textMain"><br>'. $order->products[$i]['name'] . ($order->products[$i]['model']!=""?' (' . $order->products[$i]['model'] . ')':'').  '<br>' . $products_ordered_attributes . '</td>' .
									'<td valign="top" class="textMain"><small><br>' . $order->products[$i]['sku'] . '</small></td>' . 
									'<td valign="top" align="right" class="textMain"><br>'.$currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty'],true).'&nbsp;</td>' . 
									'</tr>' .
									'<tr>' . 
									'<td colspan="5" height="1" class="textBorder">' . tep_draw_separator('pixel_trans.gif',10,1) . '</td>' . 
									'</tr>';

		}
		if ($products_type!="M"){
			if ($products_type=='')
				$products_type=$order->products[$i]['element_type'];
			else if ($products_type!=$order->products[$i]['element_type'])
				$products_type="M";
		}
		if ($order->products[$i]['element_type']=='V'){
		if($mode=="new")
			tep_send_service_order_email($insert_id);
		}

	}
	
	if($mode=="edit")
	{
		//==products
		$prd_ids=$product_new_order_ids;
		if($prd_ids!="")
		{
		   if($prd_ids!='0')
			   $prd_ids=substr($prd_ids,0,-1);
		   tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS . " where orders_products_id not in(" . $prd_ids. ") and products_type='P' and orders_id='".$order_id."'");
		   tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_products_id not in(" . $prd_ids. ")  and orders_id='".$order_id."'");
		   tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_DOWNLOADS . " where orders_products_id not in (" . $prd_ids . ") and orders_id='".  $order_id ."'");
		}
		///==events
		$prd_ids=$event_new_order_ids;
		if($prd_ids!="")
		{
		   if($prd_ids!='0')
			   $prd_ids=substr($prd_ids,0,-1);
		   tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS . " where orders_products_id not in(" . $prd_ids. ") and products_type='E' and orders_id='".$order_id."'");
		}
		//===subscriptions
		$prd_ids=$subscription_new_order_ids;
		if($prd_ids!="")
		{
		   if($prd_ids!='0')
		   	$prd_ids=substr($prd_ids,0,-1);
		   tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS . " where orders_products_id not in(" . $prd_ids. ") and products_type='S' and orders_id='".$order_id."'");
		   tep_db_query("delete from " .TABLE_ORDERS_SUBSCRIPTIONS . " where orders_products_id not in(" . $prd_ids. ")  and orders_id='".$order_id."'");
		}
		//===services
		$prd_ids=$service_new_order_ids;
		if($prd_ids!="")
		{
		   if($prd_ids!='0')
		   	$prd_ids=substr($prd_ids,0,-1);
		   tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS . " where orders_products_id not in(" . $prd_ids. ") and products_type='V' and orders_id='".$order_id."'");
		   tep_db_query("delete from " .TABLE_ORDERS_SERVICES . " where orders_products_id not in(" . $prd_ids. ")  and orders_id='".$order_id."'");
		   tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_products_id not in (" . $prd_ids .") and orders_id='" . $order_id . "'");
		}
		
	}
	$products_ordered.="</table>";
	$status=$order->info['order_status'];

	$refund_flag=isset($HTTP_GET_VARS['refund_flag'])?$HTTP_GET_VARS['refund_flag']:'';
	if($refund_flag==1){
	$orders_status_query=tep_db_query("select orders_status_id from ".TABLE_ORDERS_STATUS." where orders_status_name like '%Processed%'");
		if(tep_db_num_rows($orders_status_query)>0){
		$orders_status_array=tep_db_fetch_array($orders_status_query);
		$status=$orders_status_array['orders_status_id'];
		}
	}
	
	
		//manual adjust payment
		$manual_price=$HTTP_SESSION_VARS['modify_price_prefix'];
		$manual_sign=$HTTP_SESSION_VARS['sign'];
		$manual_purpose=$HTTP_SESSION_VARS['purpose'];
		$manual_option=$HTTP_SESSION_VARS['manual_option'];
		if($manual_sign=='-')
		$rest_mp = substr($manual_price, 1);
		else
		$rest_mp =$manual_price;
		
		$manual_text='('.$manual_sign.')'.$currencies->format($rest_mp);
		$mpa_text=$manual_purpose; //Manual Price Adjust:
		$manual_data_array = array(
									'orders_id' => $insert_id,
									'title' => $mpa_text,
									'text' =>  $manual_text,
									'value' =>  $manual_price,
									'class' => 'ot_adjust',
									'sort_order' => '8'
									);
									
									
				if($manual_option=='Y' ){							
				tep_db_perform(TABLE_ORDERS_TOTAL, $manual_data_array);	
				$manual_comment='<div><b>'.'Manual Price Adjustment:</b>' . $mpa_text . $manual_text.'</div>';
				}						
									
$comments=$payment_modules->get_comments();

$order->info['id']=$insert_id;
$sql_data_array = array('orders_id' => $insert_id,
						'orders_status_id' => (int)$status,
						'date_added' => getServerDate(true),
						'customer_notified' => $customer_notification,
						'comments' => $order->info['comments'] . $comments . $manual_comment ,
						'user_added'=>"Admin");

tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

tep_db_query("update ".TABLE_ORDERS." set orders_status='$status' where orders_id='$order_id' ");

$order_total_modules->apply_credit();//ICW ADDED FOR CREDIT CLASS SYSTEM

// intimate the fulfiller
require(DIR_WS_CLASSES . 'fulfiller.php');
require(DIR_WS_CLASSES . 'xml_parser.php');

$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');

$fulfiller->process();

// end intimate fullfiller
// lets start with the email confirmation


$comment=$order->info['comments'] . $comments;
if ($products_type=='M' || $products_type=='P'){
	$merge_details=array();
	$send_details=array();
	// order details
	$merge_details[ORDR_NO]=$insert_id;
	$merge_details[ORDR_OL]='<a href="'.tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $insert_id, 'SSL', false).'" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">'."Order Invoice Link".'</a>';
	$merge_details[ORDR_OP]=strftime(DATE_FORMAT_LONG);
	$merge_details[ORDR_OM]=(($comment)?'Order Comments: ' . $comment:'');
	$merge_details[ORDR_PO]=$products_ordered;
	//===get if any download links===============
	$downloads_query=tep_db_query("select opd.*,op.products_name from " . TABLE_ORDERS_PRODUCTS_DOWNLOAD . " opd," . TABLE_ORDERS_PRODUCTS . " op where opd.orders_products_id=op.orders_products_id and opd.orders_id='" . $insert_id . "'");
	$download_content="<table>";
	if(tep_db_num_rows($downloads_query)>0)
		$download_content.='<tr class="textTableContent"><td class="textMain" colspan=10>' .TEXT_DOWNLOAD_LINK . '</td></tr>';
    while ($downloads = tep_db_fetch_array($downloads_query)) {
// MySQL 3.22 does not have INTERVAL
      list($dt_year, $dt_month, $dt_day) = explode('-', date('Y-m-d',strtotime(getServerDate())));
      $download_timestamp = mktime(23, 59, 59, $dt_month, $dt_day + $downloads['download_maxdays'], $dt_year);
      $download_expiry = date('Y-m-d H:i:s', $download_timestamp);
      $download_content.=' <tr class="textTableContent">';
      if ( ($downloads['download_count'] > 0) && (file_exists(DIR_FS_DOWNLOAD . $downloads['orders_products_filename'])) && ( ($downloads['download_maxdays'] == 0) || ($download_timestamp > time())) ) {
        $download_content.= '            <td class="textMain" align="center"><a href="'.tep_href_link(FILENAME_DOWNLOAD, 'id=' . $downloads['orders_products_download_id'], 'SSL', false).'" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . $downloads['products_name'] .  '</a></td>' . "\n";
      } else {
        $download_content.= '            <td class="textMain">' . $downloads['products_name'] . '</td>' . "\n";
      }
      $download_content.= '            <td class="textMain" nowrap><b>' . TABLE_HEADING_DOWNLOAD_DATE . '</b>&nbsp;' . tep_date_long($download_expiry) . '</td>' . "\n" .
           '            <td class="textMain" align="right"><b>' . $downloads['download_count'] . '</b>' .  TABLE_HEADING_DOWNLOAD_COUNT . '</td>' . "\n" .
           '          </tr>' . "\n";
    }
	$download_content.="</table>";
	$merge_details[TEXT_DL]=$download_content;
//============================================
	$order_totals_str="<table border='0' cellpadding='2' cellspacing='0' width='100%'>";
	
	for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
		if ($order_totals[$i]['code']=='ot_total'){
			$class="textTotal";
		} else if ($i%2==0){
			$class="textTableTotalE";
		} else {
			$class="textTableTotalO";
		}
		if($order_totals[$i]['code']=='ot_tax'){
			$order_totals_str.= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . TEXT_TAX . '</td><td class="' . $class . '" align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
		}else if($order_totals[$i]['code']=='ot_shipping'){
			$order_totals_str.= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . TEXT_SHIPPING . '</td><td class="' . $class . '" align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
		}else if($order_totals[$i]['code']=='ot_total'){
			$order_totals_str.= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . TEXT_TOTAL . '</td><td class="' . $class . '" align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
		}else if($order_totals[$i]['code']=='ot_subtotal'){
			$order_totals_str.= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . TEXT_SUBTOTAL . '</td><td class="' . $class . '" align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
		} else {
			$order_totals_str.= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . $order_totals[$i]['title'] . '</td><td class="' . $class . '" align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
		}
	}
	$order_totals_str.="</table>";
	$merge_details[ORDR_OT]=$order_totals_str;
	//customer details
	$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[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'];
	
	//Billing details
	$merge_details[BILL_NA]=$order->billing['firstname'] . ' ' . $order->billing['lastname'];;
	$merge_details[BILL_CM]=$order->billing['company'];
	$merge_details[BILL_CT]=$order->billing['street_address'];
	$merge_details[BILL_CS]=$order->billing['suburb'];
	$merge_details[BILL_CC]=$order->billing['city'];
	$merge_details[BILL_CP]=$order->billing['postcode'];
	$merge_details[BILL_CE]=$order->billing['state'];
	$merge_details[BILL_CU]=$order->billing['country']['title'];

	//delivery details
	$merge_details[DELI_NA]=$order->delivery['firstname'] . ' ' . $order->delivery['lastname'];
	$merge_details[DELI_CM]=$order->delivery['company'];
	$merge_details[DELI_CT]=$order->delivery['street_address'];
	$merge_details[DELI_CS]=$order->delivery['suburb'];
	$merge_details[DELI_CC]=$order->delivery['city'];
	$merge_details[DELI_CP]=$order->delivery['postcode'];
	$merge_details[DELI_CE]=$order->delivery['state'];
	$merge_details[DELI_CU]=$order->delivery['country']['title'];
	
	if (is_object($$payment)) {
		$payment_class = $$payment;
		$merge_details[ORDR_PM]= $payment_class->title;
			if($payment_class->code=='ausbank')
				$merge_details[ORDR_DD]=sprintf(TEXT_DIRECT_DEPOSIT,$referenceID);
			else 
				$merge_details[ORDR_DD]='';	
		if ($payment_class->email_footer) { 
	  		$merge_details[ORDR_PF] .= $payment_class->email_footer;
		}  
	}

	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_CATALOG:HTTP_SERVER . DIR_WS_CATALOG);
	$merge_details['Store_Link']='<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>';
	$merge_details['Telephone']=$order->customer['telephone'];
	$merge_details['Order_Link']='<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $insert_id, 'SSL', false) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . 'Click Here' . '</a>';
	//$merge_details['Store_Logo']='<img src="' . tep_href_link(DIR_WS_IMAGES . COMPANY_LOGO) . '" title="' . STORE_NAME . '">';
	$merge_details['Store_Logo'] = '<img src="' . $url_home . 'admin/images/freeway.png" title="' . STORE_NAME . '">';
	
	$send_details[0]['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
	$send_details[0]['to_email']=$order->customer['email_address'];
	$send_details[0]['from_name']=STORE_OWNER;
	$send_details[0]['from_email']=STORE_OWNER_EMAIL_ADDRESS;


  // send emails to other people    
	if (SEND_EXTRA_ORDER_EMAILS_TO != '') {
		$send_details[1]['to_name']=SEND_EXTRA_ORDER_EMAILS_TO;
		$send_details[1]['to_email']=SEND_EXTRA_ORDER_EMAILS_TO;
		$send_details[1]['from_name']=STORE_OWNER;
		$send_details[1]['from_email']=STORE_OWNER_EMAIL_ADDRESS;
	}
	if ($GLOBALS[$payment]->code!="paypalipn"){
	if($mode=='new')
		tep_send_default_email("PRD",$merge_details,$send_details);
		tep_send_support_pack_default_email("SPP",$insert_id);	 //Support Packs
	}
}

	// modified for wallet payment -start
	if ($GLOBALS[$payment]->code=="wallet"){
		$sql_wallet_array=array( 'drawn_date' => getServerDate(true),
								'customers_id' => $customer_id,
								'orders_id'=>$insert_id,
								'amount'=>$order->info['total']
		);
		
		tep_db_perform(TABLE_WALLET_HISTORY, $sql_wallet_array);
		$balance=tep_get_wallet_balance($customer_id);
		$minimum_balance=tep_get_wallet_min_balance($customer_id);
		if ($balance<$minimum_balance){
			// send wallet balance email
			$merge_details=array(	TEXT_FN=>$order->customer['firstname'],
									TEXT_LN=>$order->customer['lastname'],
									TEXT_DF=>'',
									TEXT_EM=>$order->customer['email_address'],
									TEXT_TN=>$order->customer['telephone_number'],
									TEXT_FX=>$order->customer['fax'],
									TEXT_SA=>$order->billing['street_address'],
									TEXT_SU=>$order->billing['suburb'],
									TEXT_PC=>$order->billing['postcode'],
									TEXT_CT=>$order->billing['city'],
									TEXT_ST=>$order->billing["state"],
									TEXT_CY=>$order->billing["country"]["title"],
									TEXT_RE=>'',
									TEXT_IV=>'',
									TEXT_UN=>'',
									TEXT_PT=>'',
									TEXT_WAD=>'',
									TEXT_WCB=>$currencies->format($balance)
								);
		   $send_details=array(array('to_name'=>$order->customer['firstname'] . ' ' . $order->customer['lastname'],
											 'to_email'=>$order->customer['email_address'],
											 'from_name'=>STORE_OWNER,
											 'from_email'=>STORE_OWNER_EMAIL_ADDRESS));
			tep_send_default_email("WBW",$merge_details,$send_details);

			// store in the message history
			$sql_array=array(
								"send_date"=>getServerDate(true),
								"customers_id"=>$customer_id,
								"message_mode"=>"E",
								"message_type"=>"WBW"
							);
							
			tep_db_perform(TABLE_WALLET_MESSAGES_HISTORY,$sql_array);
		}
	}
	// modified for wallet payment -end
	
	



//paypal ipn changes
if ($GLOBALS[$payment]->code=="paypalipn"){
	  if (ereg($order->info['currency'],MODULE_PAYMENT_PAYPALIPN_ALLOWED_CURRENCIES)) {
		$paypal_ipn_currency = $order->info['currency'];
	  } else {
		$paypal_ipn_currency = MODULE_PAYMENT_PAYPALIPN_DEFAULT_CURRENCY;
	  };
	
	  $paypal_ipn_order_amount = $order->info['total'];
	
	  if (MODULE_PAYMENT_PAYPALIPN_ADD_SHIPPING_TO_AMOUNT=='True') {
		$paypal_ipn_shipping_amount = 0.00;
	  } else {
		$paypal_ipn_order_amount -= $order->info['shipping_cost'];
		$paypal_ipn_shipping_amount = number_format($order->info['shipping_cost'] * $currencies->get_value($paypal_ipn_currency), 2);
	  }; 
	
	  if (MODULE_PAYMENT_PAYPALIPN_ADD_TAX_TO_AMOUNT=='True') {
		$paypal_ipn_tax_amount = 0.00;
	  } else {
		$paypal_ipn_order_amount -= $order->info['tax'];
		$paypal_ipn_tax_amount = number_format($order->info['tax'] * $currencies->get_value($paypal_ipn_currency), 2);
	  };
	  
	  $paypal_ipn_order_amount = tep_get_rounded_amount($paypal_ipn_order_amount * $currencies->get_value($paypal_ipn_currency));
		$cart->reset(true);
		tep_session_unregister('shipping');
		tep_session_unregister('payment');
		tep_session_unregister('comments');
		tep_session_unregister('order_timestamp');
		tep_session_unregister('show_billing');
		$order_total_modules->clear_posts();
		tep_session_unregister('cartID');
	  	tep_redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_ext-enter&redirect_cmd=_xclick&business=".MODULE_PAYMENT_PAYPALIPN_ID."&item_name=".urlencode(STORE_NAME)."&item_number=".$insert_id."&currency_code=".$paypal_ipn_currency."&amount=".$paypal_ipn_order_amount."&shipping=".$paypal_ipn_shipping_amount.($paypal_ipn_tax_amount>0?"&tax=".$paypal_ipn_tax_amount:'') ."&first_name=".urlencode($order->customer['firstname'])."&last_name=".urlencode($order->customer['lastname'])."&address1=".urlencode($order->customer['street_address'])."&city=".urlencode($order->customer['city'])."&state=".urlencode($order->customer['state'])."&zip=".urlencode($order->customer['postcode'])."&email=".$order->customer['email_address']."&bn=oscommres&return=".tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $insert_id, 'SSL')."&cancel_return=".tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL')."&notify_url=".MODULE_PAYMENT_PAYPALIPN_NOTIFY_URL);
}
  // Include OSC-AFFILIATE 
//require(DIR_WS_INCLUDES . 'affiliate_checkout_process.php');

// load the after_process function from the payment modules
$payment_modules->after_process();

$cart->reset(true);
$HTTP_SESSION_VARS['error_count']=0;
// unregister session variables used during checkout
tep_session_unregister('sendto');
tep_session_unregister('billto');
tep_session_unregister('shipping');
tep_session_unregister('payment');
tep_session_unregister('comments');
tep_session_unregister('order_timestamp');
tep_session_unregister('receiptNo');
tep_session_unregister('transactionNr');
tep_session_unregister('coupon');
tep_session_unregister('coupon_exist');
tep_session_unregister('gv_redeem_code');
tep_session_unregister('cart');	
tep_session_unregister('order_id');
tep_session_unregister("payment_refund");
tep_session_unregister('modify_price_prefix');
tep_session_unregister('sign');
tep_session_unregister('purpose');
tep_session_unregister('manual_option');

$order_total_modules->clear_posts();//ICW ADDED FOR CREDIT CLASS SYSTEM

// BOF: Lango added for print order mod
// echo "redirect_page||" . tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $insert_id . '&payment=' . $payment, 'SSL');

   tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $insert_id . '&payment=' . $payment, 'SSL'));
//tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $insert_id, 'SSL'));
// EOF: Lango added for print order mod
require(DIR_WS_INCLUDES . 'application_bottom.php'); 
   function randomize() {
            $salt = "abchefghjkmnpqrstuvwxyz0123456789";
            srand((double)microtime()*1000000); 
            $i = 0;
    	    while ($i <= 7) {
    		$num = rand() % 33;
    		$tmp = substr($salt, $num, 1);
    		$pass = $pass . $tmp;
    		$i++;
  	    }
  	    return $pass;
          }

?>