<?php
/*
	osCommerce, Open Source E-Commerce Solutions 
	http://www.oscommerce.com 
	
	Copyright (c) 2003 osCommerce 
	
	Freeway eCommerce 
	http://www.openfreeway.org
	Copyright (c) 2007 ZacWare
	
	osConcert, Online Seat Booking 
	https://www.osconcert.com
	
	Copyright (c) 2020 osConcert
	Released under the GNU General Public License
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
 include('includes/application_top.php');
 
//attempted access by non BoxOffice
if(!$_SESSION['customer_country_id']==999 ){exit('..');} 
//clear the session for bor
	   if ($FSESSION->is_registered('bor_new_order')) {
	   	   $FSESSION->remove('bor_new_order');
	   }
//check for POST values of some sort
if ($_POST['confirm_list'] == '' && $_POST['restock_list'] == ''){
      $messageStack->add_session('header', TEXT_NO_TICKETS, 'error');
      tep_redirect(tep_href_link('bor_listings.php'));
	  
	  }
	  
$FSESSION->remove('box_office_reservation');
//check for orders_id
 if ($_POST['orders_id'] == '' ){
      $messageStack->add_session('header', TEXT_NO_ORDERS, 'error');
      tep_redirect(tep_href_link('bor_listings.php'));
	  
	  }else{
	  $order_id = $_POST['orders_id'];
	  }
//retrieve the original order
	require(DIR_WS_CLASSES . 'order.php');
	$order_old = new order($_POST['orders_id']);
// compare the size of the different arrays	
$confirm_list = array();
$restock_list = array();
foreach($_POST['confirm_list'] as $selected){
 $confirm_list_array[] = $selected;
}
foreach($_POST['restock_list'] as $selected){
 $restock_list_array[] = $selected;
}	
// check there is the correct number of products in the order
//PHP8	
if(!is_array($confirm_list_array)){
	$confirm_list_array=array();
}
if(!is_array($restock_list_array)){
	$restock_list_array=array();
}

if ( sizeof($confirm_list_array) + sizeof($restock_list_array) != sizeof($order_old->products)){
      $messageStack->add_session('header', TEXT_DISPARITY, 'error');
      tep_redirect(tep_href_link('bor_listings.php'));
}	
//check the order status is suitable
if ($order_old->info['status_id'] != MODULE_PAYMENT_BOR_ORDER_STATUS_ID){
      $messageStack->add_session('header', TEXT_NOT_PERMIT, 'error');
      tep_redirect(tep_href_link('bor_listings.php'));
};
$order = new order();
$this_operator = $order->customer['firstname'] . ' ' . $order->customer['lastname'];
$old_operator = $order_old->customer['firstname'] . ' ' . $order_old->customer['lastname'];
// three steps now (1) all confirm (2) all restock or (3) mix and match
// first change the order owner
######### change order owner #####################
		   $sql_data_array = array(
							'customers_id' => $FSESSION->get('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'], 
							'orders_status' => MODULE_PAYMENT_BOR_ORDER_MANUAL_STATUS_ID,
							);
	
  tep_db_perform(TABLE_ORDERS, $sql_data_array, "update", "orders_id='".$order_id."'");
#########################  ALL RESTOK #######################
if ( sizeof($confirm_list_array) == 0 && sizeof($restock_list_array) > 0){
// simple cancellation here no need to change order owner?
 canx_order($_POST['orders_id'],TEXT_MANUAL_RESTOCK,$this_operator);
 exit();
}
#########################  ALL CONFIRM ######################
elseif ( sizeof($confirm_list_array) > 0 && sizeof($restock_list_array) == 0){
  
######### note order comments ####################
        
        $sql_data_array = array('orders_id' => $order_id,
        'orders_status_id' => MODULE_PAYMENT_BOR_ORDER_MANUAL_STATUS_ID,
        'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
        'customer_notified' => 0,
        'comments' => TEXT_ORDER_CONFIRMED.$old_operator);
        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
		
		//update the product status
					tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status = '".MODULE_PAYMENT_BOR_ORDER_MANUAL_STATUS_ID."'                      where orders_id = '" . (int)$order_id ."'");
		
		
		tep_redirect(tep_href_link('bor_checkout_success.php?order_id='.$order_id.'&type=comp'));
}
######################### MIX + MATCH #######################
//change the order owner to current Box Office user
else { 
	$comments = 'RESTOCKED: ';
//now change the quantities etc on the tickets NOT required 
foreach ($restock_list_array as $key => $value){
        $order_query = tep_db_query("select products_id, products_name, final_price, products_quantity, events_type from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order_id. "' AND orders_products_id = '".$value."'");
        while ($order2 = tep_db_fetch_array($order_query)) {
            tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = products_quantity + " . $order2['products_quantity'] . ", products_ordered = products_ordered - " . $order2['products_quantity'] . ", products_status='1' where products_id = '" . (int)$order2['products_id'] . "'");
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status = '".MODULE_PAYMENT_BOR_ORDER_CANX_STATUS_ID."' , products_name = 'REFUNDED:".$order2['products_name']."', products_quantity = products_quantity - " . $order2['products_quantity'] . " where products_id = '" . (int)$order2['products_id'] . "' AND orders_products_id = '".$value."'");
			
			$comments .= $order2['products_name'] .' ';
			
					//adjust the original order totals
					//get the values		
					    $order_new=new order($order_id);
						$total_array=$order_new->totals;
						
					//we now have the original order_total table values as an array
					//work through these and adjust only for ot_total and ot_subtotal
					for ($k=0, $kn=count($total_array); $k<$kn; $k++) {
						if( $total_array[$k]['class'] =='ot_subtotal'){
						   $orig_value=$total_array[$k]['value'];
						   $new_value = $orig_value -( $order2['products_quantity'] * $order2['final_price']); 
						   $new_text = $currencies->format($new_value, true, $order_new->info['currency'], $order_new->info['currency_value']); 
						//   echo '<br>subtotal value'.$orig_value;
						//   echo '<br>new value'.$new_value;
						//   echo '<br>new_text'.$new_text;
						 tep_db_query("update " . TABLE_ORDERS_TOTAL . " set value ='".$new_value."' , text = '".$new_text."' where orders_id = '" . $order_id. "' and class='ot_subtotal'");
						  }//end ot_subtotal
					 elseif( $total_array[$k]['class'] =='ot_total'){
						   $orig_value=$total_array[$k]['value'];
						   $new_value = $orig_value -( $order2['products_quantity'] * $order2['final_price']);
						   $new_text = '<b>'.$currencies->format($new_value, true, $order_new->info['currency'], $order_new->info['currency_value']).'</b>'; 
						 tep_db_query("update " . TABLE_ORDERS_TOTAL . " set value ='".$new_value."' , text = '".$new_text."' where orders_id = '" . $order_id ."' and class='ot_total'");
						  }//end ot_total
					}
      }
}
$comments .= "CONFIRMED : ";
foreach ($confirm_list_array as $key => $value){
        $order_query = tep_db_query("select products_id, products_name, products_quantity, events_type from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order_id. "' AND orders_products_id = '".$value."'");
        while ($order2 = tep_db_fetch_array($order_query)) {
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status = '".MODULE_PAYMENT_BOR_ORDER_MANUAL_STATUS_ID."' where products_id = '" . (int)$order2['products_id'] . "' AND orders_products_id = '".$value."'");
			
			$comments .= $order2['products_name'] .' ';
      }
}
  
} 
        $sql_data_array = array('orders_id' => $order_id,
        'orders_status_id' => MODULE_PAYMENT_BOR_ORDER_MANUAL_STATUS_ID,
        'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
        'customer_notified' => 0,
        'comments' => ORDER_ORIGINATED_BY.$old_operator. '. '.$comments . ' by: '.$this_operator);
        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
		
		tep_redirect(tep_href_link('bor_checkout_success.php?order_id='.$order_id.'&type=comp'));
  
  function canx_order($order_id, $note='', $operator)
{
    global $FSESSION;
    // if we have the order_id then do stuff
    if (tep_not_null($order_id)) {
        //grab customers name from order
        $cust_query = tep_db_query("select customers_name from " . TABLE_ORDERS . " where orders_id = '" . (int)$order_id . "'");
        if (tep_db_num_rows($cust_query) ) {
            $cust_query_result = tep_db_fetch_array($cust_query);
            $cust_name = $cust_query_result['customers_name'];
        }
        //change the order status
        $sql_data_array = array('orders_status' => MODULE_PAYMENT_BOR_ORDER_CANX_STATUS_ID,
        'customers_name'=> RESERVATIONS_CANCELLED.$cust_name)
        ;
        tep_db_perform(TABLE_ORDERS, $sql_data_array, "update", "orders_id='".$order_id."'");
        
        $sql_data_array = array('orders_id' => $order_id,
        'orders_status_id' => MODULE_PAYMENT_BOR_ORDER_CANX_STATUS_ID,
        'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
        'customer_notified' => 0,
        'comments' => $note . $operator);
        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        
		include_once('includes/functions/ga_tickets.php');
        
        //reset the products quantity and status
		//n.b. that in the orders_products table that the products_type field does not reflect the products_type field in
		//the products table - you need to use events_type
		
        $order_query = tep_db_query("select products_id, products_quantity, events_type from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order_id. "'");
        while ($order = tep_db_fetch_array($order_query)) {
            tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = products_quantity + " . $order['products_quantity'] . ", products_ordered = products_ordered - " . $order['products_quantity'] . ", products_status='1' where products_id = '" . (int)$order['products_id'] . "'");
			//tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status = '".MODULE_PAYMENT_BOR_ORDER_CANX_STATUS_ID."' where products_id = '" . (int)$order['products_id'] . "'");
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status = '".MODULE_PAYMENT_BOR_ORDER_CANX_STATUS_ID."' where products_id = '" . (int)$order['products_id'] . "' AND orders_id = '".$order_id."'");
			
		if (function_exists('ga_check_process_restock')){
			ga_check_process_restock((int)$order['products_id'], $order['products_quantity'], $order['events_type']);	
			}													
        }
        //give the order total a value of 0.00
        tep_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order_id. "'");
        tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set products_quantity = '0' where orders_id = '" . $order_id . "'");
        tep_db_query("insert into " . TABLE_ORDERS_TOTAL. " (orders_id, title, text, value, class, sort_order) values ('" . $order_id . "', 'Total', '0.00', '0','ot_total', '99')");
		
		tep_redirect(tep_href_link('bor_checkout_success.php?order_id='.$order_id.'&type=canx'));
		
       return false;
    }
}
?>