<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
  include('includes/application_top.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  require(DIR_WS_CLASSES . 'payment.php');
  require(DIR_WS_CLASSES . 'order.php');
  require(DIR_WS_CLASSES . 'ot_coupon.php');
  $server_date = getServerDate(true);
	$cart=new shoppingcart();

	$detail_only=(isset($HTTP_POST_VARS["detail_only"])?$HTTP_POST_VARS["detail_only"]:0);
	$order_timestamp=(isset($HTTP_SESSION_VARS['order_timestamp'])?$HTTP_SESSION_VARS['order_timestamp']:0);
	$payment_modules = new payment($payment); 
	$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']:'';
	$order_comments=$payment_modules->get_comments();
	// to update details only
	$coupon_class=new ot_coupon;
	if ($detail_only==1){
		$inputID=(isset($HTTP_GET_VARS['validID'])?(int)$HTTP_GET_VARS['validID']:0);

		//check if it is a newly created orderf
		$order_query=tep_db_query("SELECT count(*) as total from " . TABLE_ORDERS_PRODUCTS . " where orders_id='" . (int)$oID . "'");
		$order=tep_db_fetch_array($order_query);
		if ((int)$order['total']==0)
			$mode='new';
		else
			$mode='edit';
	
	
		//check return id with stored id to avoid hack attempts
		if ($checkID!=$inputID)
			tep_redirect(tep_href_link(FILENAME_ORDERS));

		$currencies=new currencies();
		$oID=(int)$edit_order;
		$order=new order($oID,true);
		$edit_cart=new editOrderCart($oID);
		$update_string=$edit_cart->store_final_contents(true);

		if ($update_string!=""){
			$order_status_query=tep_db_query("SELECT orders_status from " . TABLE_ORDERS . " where orders_id='" . (int)$oID . "'");
			$order_status_result=tep_db_fetch_array($order_status_query);
			$status=$order_status_result["orders_status"]; 
			$add_comments="<b>Order Updated</b><br>";
			
			$add_comments.=$order_comments.'<br>'.$update_string;
			$user_name=tep_admin_name($login_id);
			
			tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " 
			(orders_id, orders_status_id, date_added, customer_notified, comments,user_added) 
			values ('" . $oID . "', '" . $status . "','" . $server_date . "', '" . $customer_notify . "', '" . tep_db_input($add_comments)  . "','" . tep_db_input($user_name) . "')");
		}
		// unregister session variables used during checkout
		tep_session_unregister('payment');
		tep_session_unregister('edit_order');
		tep_session_unregister('checkID');
		$coupon_class->apply_credit();//ICW ADDED FOR CREDIT CLASS SYSTEM
		//$messageStack->add(ORDER_EDIT_SUCCESS,'success');
		
		tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS_SUCCESS, 'oID=' . $oID . '&mode=' . $mode));
	}
	if ((!tep_not_null(MODULE_PAYMENT_INSTALLED)) && (!tep_session_is_registered('payment')) ) {
		tep_redirect(tep_href_link(FILENAME_ORDERS));
	}

	$inputID=(isset($HTTP_GET_VARS['validID'])?(int)$HTTP_GET_VARS['validID']:0);

	//check if it is a newly created order
	$order_query=tep_db_query("SELECT count(*) as total from " . TABLE_ORDERS_PRODUCTS . " where orders_id='" . (int)$oID . "'");
	$order=tep_db_fetch_array($order_query);
	if ((int)$order['total']==0)
		$mode='new';
	else
		$mode='edit';

	//check return id with stored id to avoid hack attempts
	if ($checkID!=$inputID)
		tep_redirect(tep_href_link(FILENAME_ORDERS));
 
	$currencies=new currencies();
	$oID=(int)$edit_order;

	$order=new order($oID,true);
	$payment_modules->before_process();  
	$edit_cart=new editOrderCart($oID);
	$update_string=$edit_cart->store_final_contents();

	$order=new order($oID);  
	$ip_address= $_SERVER['REMOTE_ADDR'];
	

	$UpdateOrders = "update " . TABLE_ORDERS . " set ";
		

	$update_info_cc_type=(isset($GLOBALS['cc_type']) ? tep_db_input(stripslashes($GLOBALS['cc_type'])) : '');
	$update_info_cc_owner=(isset($GLOBALS['cc_owner']) ? tep_db_input(stripslashes($GLOBALS['cc_owner'])) : '');
	$update_info_cc_number=(isset($GLOBALS['cc_number']) ? tep_db_input(stripslashes($GLOBALS['cc_number'])) : '');
	$update_info_cc_cvv='';
	$update_info_cc_expires=(isset($GLOBALS['cc_expires']) ? tep_db_input(stripslashes($GLOBALS['cc_expires'])) : '');
	$update_info_payment=(isset($GLOBALS['payment_info']) ? tep_db_input(stripslashes($GLOBALS['payment_info'])) : '');
	$UpdateOrders .="payment_method = '" . tep_db_input(stripslashes($GLOBALS[$payment]->title)) . "',
					 cc_type = '" . tep_db_input(stripslashes($update_info_cc_type)) . "',
					 cc_owner = '" . tep_db_input(stripslashes($update_info_cc_owner)) . "',
					 cc_cvv_number='" . tep_db_input(stripslashes($update_info_cc_cvv)) . "',";
	
	$UpdateOrders .= "cc_number = '" . tep_db_input(stripslashes($update_info_cc_number)) . "',";
	$UpdateOrders .= "payment_info = '" . tep_db_input(stripslashes($GLOBALS[$payment]->email_footer)) . "',";
	$UpdateOrders .="reference_id= '" . $referenceID . "',";
	
	$UpdateOrders .= "cc_expires = '" . tep_db_input(stripslashes($update_info_cc_expires)) . "',";
	
	$UpdateOrders .= "payment_return1 = '" . tep_db_input(stripslashes($payment_return1)) . "',ip_address='". $ip_address ."',payment_return2='".tep_db_input(stripslashes($payment_return2))."'";
	
	$customer_query=tep_db_query("select customers_id from ".TABLE_ORDERS ." where orders_id='".(int)$oID."'");
	$customer_result=tep_db_fetch_array($customer_query);
	
	//save multiple customers in customers and orders table
	$result_array=array();
	$attendees = $edit_cart->attendees;
	$group_members=$edit_cart->get_attendee_names();
	tep_db_query("delete from " . TABLE_CUSTOMERS_TO_CUSTOMERS . " where orders_id='" . (int)$oID . "'");
    for($icnt=0;$icnt<count($attendees);$icnt++){
		// customer not exists
		if($attendees[$icnt]["customer_id"]==-1){
			$attendee=$attendees[$icnt];
			  $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 );
								 // print_r($customer_array);
		  
	
			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'] . "'");
		  $attendees[$icnt]["country_name"]=tep_get_country_name($attendees[$icnt]["country"]);
		  tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values('".$customer_result['customers_id']."','".(int)$attendees[$icnt]['id']."','".$oID."')");
		  
		  $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
			$customer_check=tep_db_query("select customers_id from ".TABLE_CUSTOMERS." where customers_email_address='".$attendees[$icnt]["email_address"]."'"); 
			$customer_check_result=tep_db_fetch_array($customer_check);
	  		tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values('".$customer_result['customers_id']."','".(int)$customer_check_result['customers_id']."','".$oID."')");
		}
	  }
	/*  	for ($icnt=0;$icnt<sizeof($order->products);$icnt++){
			if($order->products[$icnt]['products_type']=='E'){
		  		tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values('".$customer_result['customers_id']."','".(int)$customer_result['customers_id']."','".$oID."')");
				break;
			}
		}		*/
	  //multiple customers

	$products_type='';
	$events_type='';

	for ($icnt=0;$icnt<sizeof($order->products);$icnt++){
		if ($products_type!="M"){
			if ($products_type=='')
				$products_type=$order->products[$icnt]['products_type'];
			elseif ($products_type!=$order->products[$icnt]['products_type'])
				$products_type="M";
		}
		if ($events_type!='W' && $products_type=='E')
			$events_type=$order->products[$icnt]['events_type'];
	}
	$status=$GLOBALS[$payment]->order_status;
		if($status == '')
			$status = DEFAULT_ORDERS_STATUS_ID;	
	switch($GLOBALS[$payment]->title)
	{
		case 'Credit Card':
		case 'Cash':
		case 'Internal Only':
			if ($products_type=='P' || $products_type=='S' || $products_type=="M" || $products_type=='V')
				$status=2;
			else if ($products_type=='E'){
				if ($events_type=='R')
					$status=3;
				else
					$status=2;
			}
			break;
		case 'Cheque/Money Order':
			$status=1;
	}
	if ((int)$status>0){
		$UpdateOrders .= ",orders_status = '" . tep_db_prepare_input($status) . "'";
		$comments="Automatic Updation";
	}
	if ($UpdateOrders!=''){
		$UpdateOrders .= ",last_modified ='" . $server_date . "' ";
		$UpdateOrders .= " where orders_id = '" . tep_db_prepare_input($oID) . "';";
		tep_db_query($UpdateOrders);
	}
	
	$check_status_query = tep_db_query("select * from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id = '" . (int)$oID . "'");
	$customer_notify=0;
	if (tep_db_num_rows($check_status_query)>0){
		if ($update_string!='')
			$add_comments="<b>Order Updated</b><br>" . $update_string;
			//order updated
			if($update_string!=""){
				$details['to_name']=$order->customer['name'];
				$details['to_email']=$order->customer['email_address'];
				$details['from_name']=STORE_OWNER;
				$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
				$details["html_text"]=sprintf(TEXT_ORDERS_UPDATED,$oID)."<br>".TEXT_DATE.format_date($order->info['date_purchased'])."<br>".$update_string;
	 			tep_send_email($details,true); // send email
	 			$add_comments.=$order_comments.'<br>'.$update_string;
			}
			//order updated
	}else {
		if ($products_type=='M' || $products_type=='E')
			tep_send_event_order_email($oID);
		if ($products_type=='M' || $products_type=='S')
			tep_send_subscription_order_email($oID);
		if ($products_type=='V')
			tep_send_service_order_email($oID);
		if ($products_type=='M' || $products_type=='P'){
			$products_ordered="";
			$order=new order($oID);  
			$merge_details=array();
			$send_details=array(); 
			$merge_details[ORDR_OL]=tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL', false);
			$merge_details[ORDR_OP]=strftime(DATE_FORMAT_LONG);
			$merge_details[ORDR_NO]=sprintf('%s',$oID);
			// customer query start
         $customer_query=tep_db_query("SELECT customers_firstname,customers_lastname from " . TABLE_CUSTOMERS . " where customers_id='" . (int) $order->customer['id'] . "'");
			$customer_result=tep_db_fetch_array($customer_query);
			// customer query end
			// add ausbank info start
			
	/*		$email_comments =	(($GLOBALS[$payment]->code=='ausbank') ? MODULE_AUSBANK_PAYMENT_INFO:'');
		   if($email_comments!=''){
            $email_comments.= TEXT_REFERENCEID . '&nbsp;:&nbsp;' . $referenceID;
         } */
	//		$comments =	(($GLOBALS[$payment]->code=='ausbank') ? MODULE_AUSBANK_INFO:'');
	//	   if($comments!=''){
           // $comments.= TEXT_REFERENCEID . ':' . substr(strtolower($customer_result['customers_firstname']),0,3) . substr(strtolower($customer_result['customers_lastname']),0,3) . $order_timestamp . '</b>';
	//	   $comments.=TEXT_REFERENCEID . ' &nbsp;&nbsp; '.$referenceID;
    //     }
	
			$comment=$order_comments;
			$merge_details[ORDR_OM] = (($comment)?'Order Comments: ' . $comment:'');
			/*	if($ltable==""){
				$ltable='<table cellpadding="2" cellspacing="0" border="0" width="60%">'.
					'<tr bgcolor="#C9C9C9" style="font-family: Verdana, Arial, sans-serif; font-size: 10px; color: #000000; font-weight: bold;"><td width="5"></td><td>Products Name</td>'.'<td align="right">Price</td><td width="10"></td><td>Attributes</td></tr>';
			} */
			// ausbank info end
			$merge_details[ORDR_PO]=$products_ordered;
			
			$order_totals_str="<table border='0' cellpadding='2' cellspacing='0' width='100%'>";
			$order_totals=$order->totals;
			for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
				if ($i==$n-1){
					$class="textTotal";
				} else if ($i%2==0){
					$class="textTableTotalE";
				} else {
					$class="textTableTotalO";
				}
				$order_totals_str .= '<tr class="textMain" height="21"><td class="' . $class . '" align="right">' . strip_tags($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]=$customer_result['customers_firstname'];
			$merge_details[CUST_CL]=$customer_result['customers_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'];
			$merge_details[CUST_CO]=$order->customer['telephone'];
			$merge_details[CUST_CA]=$order->customer['email_address'];
		
			//Billing details
			$merge_details[BILL_NA]=$order->billing['name'];
			$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'];
	
			//delivery details
			$merge_details[DELI_NA]=$order->delivery['name'];
			$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'];

		  	$merge_details['Store_Link']='<a href="' . tep_catalog_href_link(FILENAME_DEFAULT) . '">' . 
										'<span style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' .
										STORE_OWNER . '</span></a>';
			$merge_details['Telephone']=$order->customer['telephone'];
			$merge_details['Order_Link']='<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL', false) . '">' . 
											'<span style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . 'Click Here' . '</span></a>';
			$merge_details['Store_Logo']='<img src="' . tep_href_link(DIR_WS_IMAGES . 'freeway.png') . '" title="' . STORE_NAME . '">';
			//print_r($merge_details);
			if (is_object($$payment)) {
				$payment_class = $$payment;
				$merge_details[ORDR_PM]= $payment_class->title;
						//for direct deposit module
						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;
				}  
			}


			$send_details[0]['to_name']=$order->customer['name'];
			$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_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;
			}
			tep_send_default_email("PRD",$merge_details,$send_details);
			
	  }
         $customer_notify=1;
    }

	$user_name=tep_admin_name($login_id);
	tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " 
	(orders_id, orders_status_id, date_added, customer_notified, comments,user_added) 
	values ('" . $oID . "', '" . $status . "','" . $server_date . "', '" . $customer_notify . "', '" . tep_db_input($order_comments . '<br>' .$add_comments)  . "','" . tep_db_input($user_name) . "')");
	$coupon_class->apply_credit();//ICW ADDED FOR CREDIT CLASS SYSTEM
	// unregister session variables used during checkout
	tep_session_unregister('coupon_exist');
	tep_session_unregister('coupon_exist_equal_amount');
	tep_session_unregister('payment');
	tep_session_unregister('edit_order');
	tep_session_unregister('checkID');
	tep_session_unregister('order_timestamp');
	//error count 
		tep_set_session_value('error_count',0);
	//error count
	
	//$messageStack->add(ORDER_EDIT_SUCCESS,'success');
	tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS_SUCCESS, 'oID=' . $oID . '&mode=' . $mode));

	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;
          }
	
	
?>
