<?php
/*
	osCommerce, Open Source E-Commerce Solutions 
	http://www.oscommerce.com 
	
	Copyright (c) 2003 osCommerce 
	
	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare
	
	Released under the GNU General Public License
*/

// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	

  include('includes/application_top.php');

// if the customer is not logged on, redirect them to the login page
	if (!tep_session_is_registered('customer_id')) {
	$navigation->set_snapshot(array('mode' => 'SSL', 'page' => FILENAME_SHOPPING_CART));
	tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
  	}

// avoid hack attempts during the checkout procedure by checking the internal cartID
	if (isset($cart->cartID) && tep_session_is_registered('cartID')) {
		if ($cart->cartID != $cartID) {
			tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
		}
	}

	//include(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CHECKOUT_PROCESS);

	require(DIR_WS_CLASSES . 'order.php');
	$order = new order;

	require(DIR_WS_CLASSES . 'order_total.php');
	$order_total_modules = new order_total;
	
	$order_totals = $order_total_modules->process();
    $pay_info="free checkout event";
    if($order->products[0]['element_type']=='V') $pay_info="free checkout service";
// 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['firstname'] . ' ' . $order->delivery['lastname'], 
							'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['firstname'] . ' ' . $order->billing['lastname'], 
							'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' => 'free',
// BOF: Lango Added for print order mod 
							'payment_info' => $pay_info,
// EOF: Lango Added for print order mod 
							'cc_type' => '', 
							'cc_owner' => '', 
							'cc_number' => '', 
							'cc_expires' => '', 
							'date_purchased' => 'now()', 
							'last_modified' => 'now()',
							'orders_status' => 2, 
							'currency' => $order->info['currency'], 
							'currency_value' => $order->info['currency_value']
							);
// EOF: WebMakers.com Added: Downloads Controller
	tep_db_perform(TABLE_ORDERS, $sql_data_array);
	$insert_id = tep_db_insert_id();
	
	//Multiple Customers
  if($order->products[$icnt]['element_type']=='E'){
	$attendees = $cart->attendees;
	$group_members=$cart->get_attendee_names();
//	break;
    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'] . "'");
			  $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 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."')"); // customer already exists		
	 } 	
	 for ($icnt=0;$icnt<sizeof($order->products);$icnt++){
			if($order->products[$icnt]['element_type']=='E'){
		  		tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_TO_CUSTOMERS."(group_customer_id,customer_id,orders_id) values('".$customer_id."','".(int)$customer_id."','".$insert_id."')");
				break;
			}
		}
	}
	 for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
    	$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_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
	}

	$customer_notification = (SEND_EMAILS == 'true') ? '1' : '0';

// initialized for the email confirmation
	$products_ordered = '';
	$subtotal = 0;
	$total_tax = 0;
	$products_type='';
	$events_type='';
	for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
// 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();
			
			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;
					
				if($sessions[$id]['events_fees']=='')$sessions[$id]['events_fees']=0;
				$sql_data_array=array( 	'orders_id' => $insert_id, 
										'products_id' => $id,
										'products_model' => $sessions[$id]['date'], 
										'products_name' => $order->products[$i]['name'], 
										'products_price' => 0,
										'final_price' => 0,
										'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]['events_fees'],
										'waitlist_orders_id'=>0,
										'products_type'=>'E');
				
				$session_dates[]=$sessions[$id]['date'];
				tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
				$order_products_id = tep_db_insert_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"]) . "')");
		   tep_send_event_order_email($i);
		}else if ($order->products[$i]['element_type']=='V'){
			 	$sql_data_array=array( 	'orders_id' =>(int) $insert_id, 
								'products_id' => (int)$order->products[$i]["id"],
								'products_name' => $order->products[$i]['name'], 
								'products_price' => 0,
								'final_price' => 0,
								'products_tax' => ($prev_orders_id>0?$prev_tax:$order->products[$i]['tax']),
								'products_quantity' => 1,
								'events_fees'=>0,
								'waitlist_orders_id'=>0,
								'products_type'=>'V');
															
				tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
				$order_products_id = tep_db_insert_id();				
				$service_data_array = array(
							'orders_id' => (int)$insert_id,
							'products_id'=>(int)$order->products[$i]["id"],
							'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'=>(int)$order_products_id
							);
    		tep_db_perform(TABLE_ORDERS_SERVICES, $service_data_array);
			tep_send_service_order_email($i);
		}		
//------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 ($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";
		}
	}
$status=2;
if($customer_notification=='')$customer_notification = 0;
$sql_data_array = array(
						'orders_id' => $insert_id,
						'orders_status_id' => $status,
						'date_added' => 'now()',
						'customer_notified' => $customer_notification,
						'comments' => $order->info['comments'],
						'user_added'=>"web"
						);
tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

$cart->reset(true);

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

// BOF: Lango added for print order mod
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;
          }
?>