<?php
/*

  

  Freeway eCommerce from ZacWare
  http://www.openfreeway.org

  Copyright 2007 ZacWare Pty. Ltd

  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=$FREQUEST->getvalue('payment_return1');
  $payment_return2=$FREQUEST->getvalue('payment_return2');	
	
	 if(!$FSESSION->is_registered('customer_id')){
	 $customer_id=$FREQUEST->getvalue('customers_id');
	 
	 }
// load selected payment module
	 require(DIR_WS_CLASSES . 'payment.php');
	 $payment_modules = new payment($FSESSION->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' => $FSESSION->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' => $FSESSION->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'], 
							//CARTZONE FIX
							'date_purchased' => date('Y-m-d H:i:s',getServerDate(false)), 
							'last_modified' => date('Y-m-d H:i:s',getServerDate(false)),
							'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($FSESSION->is_registered('order_id')){
		tep_db_perform(TABLE_ORDERS, $sql_data_array,"update"," orders_id='" . (int)$FSESSION->order_id . "'");
		$insert_id = $FSESSION->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='". tep_db_input($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','" . tep_db_input($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_SL]=='<a href="' . tep_catalog_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['Store_Link']='<a href="' . tep_catalog_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[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($FSESSION->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' => (int)$order_totals[$i]['sort_order']
									);
                                  
			tep_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id='" . (int)$insert_id. "' and class='" . tep_db_input($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></td><td align="right" width="100"><b>' .TEXT_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_db_input(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 = '" . tep_db_input($products_attributes[0]['option_id']) . "' AND pa.options_values_id = '" . tep_db_input($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_db_input(tep_get_prid($order->products[$i]['id'])) . "' and pa.options_id = '" . tep_db_input($products_attributes[0]['option_id']) . "' AND pa.options_values_id = '" . tep_db_input($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_db_input(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_db_input(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_db_input(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_db_input(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('" . tep_db_input(getServerDate(false)) . "',INTERVAL 1 DAY),'%Y-%m-%d') as start_date,date_format(date_add('" . tep_db_input(getServerDate(false)) . "', INTERVAL subscription_period DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_db_input(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('" . tep_db_input($your_date) . "','%Y-%m-%d') as start_date,date_format(date_add('" . tep_db_input($your_date) . "', INTERVAL (subscription_period-1) DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . tep_db_input(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_db_input(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);
			
		// }

								// prepare for heading
		###################################################################
		$id=$order->products[$i]['id'];
		require_once(DIR_WS_INCLUDES . 'functions/categories_lookup.php');
		########################################################### cartzone added 16-03-12
		
		if($order->products[$i]['support_packs_type']!='P'){
			$heading_name=$cat_parent_name.' '.$cat_name;
				if ($plan_id==9){
				$heading_venue=$venue_name;
				$heading_date=$date_name;
				$heading_time=$time_name;
				}else{
				$heading_venue=$parent_venue_name;
				$heading_date=$parent_date_name;
				$heading_time=$parent_time_name;	
				}
			}else{
				if ($plan_id==3){//SHOW
				$heading_name=$cat_name;
				$heading_venue=$venue_name;
				$heading_date=$date_name;
				$heading_time=$time_name;
				}
				elseif ($plan_id==2){//SHOW/PLAN
				$heading_name=$cat_parent_name;
				$heading_venue=$parent_venue_name;
				$heading_date=$parent_date_name;
				$heading_time=$parent_time_name;
				}
				elseif ($plan_id==1){//SHOW/DAYS				
				$heading_name=$cat_parent_parent_name.' '.$cat_parent_name;
				$heading_venue=$parent_parent_venue_name;
				$heading_date=$parent_parent_date_name;
				$heading_time=$parent_parent_time_name;
				}
				elseif ($plan_id==0){//CINE	
				$heading_name=$cat_parent_parent_name;		
				//$heading_name=$cat_parent_parent_name.' '.$cat_parent_name.' '.$cat_name;
				$heading_venue=$parent_parent_venue_name;
				$heading_date=$cat_parent_parent_name;
				$heading_time=$parent_time_name;
				}
				else {
				$heading_name=$product_info['products_name'];
				}
			}
		########################################################### v6
// 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_db_input(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',
							'categories_name'=> $heading_name,
							//'categories_heading_title'=> $heading_name,
							//'categories_description'=> $categories_description,
							'concert_venue'=> $heading_venue,
							'concert_date'=> $heading_date,
							'concert_time'=> $heading_time
							);
							
			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);
				}
			}
			
				
		
		// 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',$FSESSION->languages_id),
							// 'orders_products_id'=>$order_products_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 = '" . tep_db_input($order->products[$i]['id']) . "' and va.options_id = '" . tep_db_input($order->products[$i]['attributes'][$j]['option_id']) . "' and va.options_id = vopt.services_options_id and va.options_values_id = '" . tep_db_input($order->products[$i]['attributes'][$j]['value_id']) . "' and va.options_values_id = voval.services_options_values_id and vopt.language_id = '" . (int)$FSESSION->languages_id . "' and voval.language_id = '" . (int)$FSESSION->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 = '" . tep_db_input($order->products[$i]['id']) . "' 
										and pa.options_id = '" . tep_db_input($order->products[$i]['attributes'][$j]['option_id']) . "' 
										and pa.options_id = popt.products_options_id 
										and pa.options_values_id = '" . tep_db_input($order->products[$i]['attributes'][$j]['value_id']) . "' 
										and pa.options_values_id = poval.products_options_values_id 
										and popt.language_id = '" . (int)$FSESSION->languages_id . "' 
										and poval.language_id = '" . (int)$FSESSION->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)$FSESSION->languages_id . "' and poval.language_id = '" . (int)$FSESSION->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_db_input(tep_get_prid($order->products[$i]['id'])) . "' and attributes_id = '" . tep_db_input(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;
		$flag_product=false;
		if ($order->products[$i]['element_type']=='P'){
			$flag_product=true;
			$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('ticket_icon.gif',$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'] . ')':'').  ' ' . $cat_name . '' . '<br>' . $products_ordered_attributes . (isset($order->products[$i]['discount_whole_text'])?'<br>' . $order->products[$i]['discount_whole_text']:'') . '</td>' .
									//cartzone hide SKU '<td valign="top" class="textMain"><small><br>' . $order->products[$i]['sku'] . '</small></td>' .
									'<td valign="top" class="textMain"><small><br>' . $heading_name .'<br>' . $heading_venue .' ' . $heading_date .' ' . $heading_time .'</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($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(" . tep_db_input($prd_ids) . ") and products_type='P' and orders_id='". (int)$FSESSION->order_id."'");
		   //tep_db_query("delete from " .TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_products_id not in(" . tep_db_input($prd_ids) . ")  and orders_id='". (int)$FSESSION->order_id."'");
		   tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_DOWNLOADS . " where orders_products_id not in (" . tep_db_input($prd_ids) . ") and orders_id='". (int)$FSESSION->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(" . tep_db_input($prd_ids) . ") and products_type='E' and orders_id='". (int)$FSESSION->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(" . tep_db_input($prd_ids) . ") and products_type='S' and orders_id='". (int)$FSESSION->order_id ."'");
		   // tep_db_query("delete from " .TABLE_ORDERS_SUBSCRIPTIONS . " where orders_products_id not in(" . tep_db_input($prd_ids) . ")  and orders_id='". (int)$FSESSION->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(" . tep_db_input($prd_ids) . ") and products_type='V' and orders_id='". (int)$FSESSION->order_id ."'");
		   // tep_db_query("delete from " .TABLE_ORDERS_SERVICES . " where orders_products_id not in(" . tep_db_input($prd_ids) . ")  and orders_id='". (int)$FSESSION->order_id ."'");
		   // tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_products_id not in (" . tep_db_input($prd_ids) .") and orders_id='" . (int)$FSESSION->order_id . "'");
		// }
		
	}
	
	
	$products_ordered.="</table>";
	
	
	$status=$order->info['order_status'];

	$refund_flag=$FREQUEST->getvalue('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=$FSESSION->get('modify_price_prefix');
		$manual_sign=$FSESSION->get('sign');
		$manual_purpose=$FSESSION->get('purpose');
		$manual_option=$FSESSION->get('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' => date('Y-m-d H:i:s',getServerDate(false)),
						//'date_added' => getServerDate(true),
						'customer_notified' => $customer_notification,
						'comments' => $order->info['comments'] . $comments . $manual_comment ,
						'user_added'=>tep_admin_name($FSESSION->login_id));

//$sql_data_array = array(
					//	'orders_id' => $insert_id,
//						'orders_status_id' => $status,
//						'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
//						'customer_notified' => $customer_notification,
//						'comments' => $order->info['comments'] . $FSESSION->get(''),
//						'user_added'=>"web"
//						);

tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

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

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


$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_OL]='<a href="' . tep_catalog_href_link(FILENAME_CATALOG_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;">'.TICKET_LINK_TEXT.' ' . CLICK_HERE . '</a>';
	
	$merge_details['Date_Purchased']=strftime(DATE_FORMAT_LONG);
	//$server_date = date('Y-m-d',getServerDate(true));
	//$merge_details['Date_Purchased']='' . $server_date . '';
	//list($dt_year, $dt_month, $dt_day) = explode('-', date('Y-m-d',strtotime(getServerDate())));
	//$merge_details[TEXT_OP]=date('l d F, Y',$server_date);
	//'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
	//$merge_details[ORDR_PO]=$date_purchased;
	$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='" . tep_db_input($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'];
	
//Bank Transfer
	define("ORDR_BDM","Bank_Deposit_Message");//Bank Deposit Message as place holder %%Bank_Deposit_Message%%
	if($payment_modules->selected_module =='bank_transfer'){
	$merge_details[ORDR_BDM]=MODULE_BANK_TRANSFER_INFO;
	} else {
	$merge_details[ORDR_BDM]="";} 
	
	if (is_object($$payment)) {
		$payment_class = $$payment;
		$merge_details[ORDR_PM]= $payment_class->title;
				$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_catalog_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;">'.TICKET_LINK_TEXT.' ' . CLICK_HERE . '</a>';
	$merge_details['Detailed_PDF_Format_Link']='<a href="' . tep_catalog_href_link(FILENAME_PDF_MAIL, 'file=pdf&order_id=' . $insert_id, 'SSL', false) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . TEST_MAIL_PDF . '</a>';
	$merge_details['Store_Logo'] = '<img src="' . $url_home . 'templates/' . DEFAULT_TEMPLATE . '/images/' .COMPANY_LOGO.'" title="' . STORE_NAME . '">';
	//$merge_details['Store_Logo']='<img src="' . tep_href_link(HTTP_HOME_URL . DIR_WS_IMAGES . '/' .COMPANY_LOGO) . '" 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' && $flag_product==true){
		//#### start email attachment new code - apes checkout_process
	    {
		
				//extra code to create pdf and attach
		
        $filename="";
			
			
		if(EMAIL_PDF_DELIVERED_ONLY=='true' && E_TICKETS == 'true' && $status == E_TICKET_STATUS ){ 
		try
		  {
		      require_once('includes/functions/products_ticket.php');
			  $filename= (DIR_FS_CATALOG.create_checkout_pdf($insert_id));
			  }
			  
		 //catch exception
           catch(Exception $e)
              {
                exit( 'Message: ' .$e->getMessage());
             }	
	       }

			//set ticket printed
					tep_db_query("update  " . TABLE_ORDERS . "  set ticket_printed='Y' where orders_id in(" . $insert_id . ")");
					//exit( $filename);
		tep_send_default_email("PRD",$merge_details,$send_details,$filename);

		//tep_send_default_email("PRD",$merge_details,$send_details);
		}
		//######end 
		}
	}
}

	// 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);
		$FSESSION->remove('shipping');
		$FSESSION->remove('payment');
		$FSESSION->remove('comments');
		$FSESSION->remove('order_timestamp');
		$FSESSION->remove('show_billing');
		$order_total_modules->clear_posts();
		$FSESSION->remove('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=osconcert&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);
}


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

$cart->reset(true);
$FSESSION->set('error_count',0);

// unregister session variables used during checkout
$FSESSION->remove('sendto');
$FSESSION->remove('billto');
$FSESSION->remove('shipping');
$FSESSION->remove('payment');
$FSESSION->remove('comments');
$FSESSION->remove('order_timestamp');
$FSESSION->remove('receiptNo');
$FSESSION->remove('transactionNr');
$FSESSION->remove('coupon');
$FSESSION->remove('coupon_exist');
$FSESSION->remove('gv_redeem_code');
$FSESSION->remove('cart');	
$FSESSION->remove('order_id');
$FSESSION->remove("payment_refund");
$FSESSION->remove('modify_price_prefix');
$FSESSION->remove('sign');
$FSESSION->remove('purpose');
$FSESSION->remove('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;
          }

?>