<?php
/*
  $Id: edit_orders.php,v 6.5.4 2017/12/17 01:41:11 datazen Exp $

  CRE Loaded, Open Source E-Commerce Solutions
  http://www.loadedcommerce.com

  Copyright (c) 2017 Loaded Commerce
  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

require('includes/application_top.php');
require(DIR_WS_FUNCTIONS . 'c_orders.php');
require(DIR_WS_CLASSES . 'Product.class.php');
require(DIR_WS_CLASSES . 'Products.class.php');
require(DIR_WS_CLASSES . 'currencies.php');
$currencies = new currencies();

require_once(DIR_WS_CLASSES . 'PriceFormatter.php');
$pf = new PriceFormatter;

include(DIR_WS_CLASSES . 'order.php');

// RCI top
echo $cre_RCI->get('global', 'top', false);
echo $cre_RCI->get('editorders', 'top', false);

// Optional Tax Rate/Percent
$AddShippingTax = "0.0"; // e.g. shipping tax of 17.5% is "17.5"

// intilize variables
$update_products = '';
$update_totals = '';
$add_products_model = '';
$add_products_name = '';
$add_products_price = '';
$products_tax_class_id = '';
$add_product_options = '';
$item_has_down = '';
$products_options_name = '';
$AddedOptionsPrice = '';
$customer_id = '' ;

if (isset($_GET['product_count'])) {
  $product_count = $_GET['product_count'] ;
} else if (isset($_POST['product_count'])) {
  $product_count = $_POST['product_count'] ;
} else {
  $product_count = '' ;
}

// New "Status History" table has different format.
$OldNewStatusValues = (tep_field_exists(TABLE_ORDERS_STATUS_HISTORY, "old_value") && tep_field_exists(TABLE_ORDERS_STATUS_HISTORY, "new_value"));
$CommentsWithStatus = tep_field_exists(TABLE_ORDERS_STATUS_HISTORY, "comments");
$SeparateBillingFields = tep_field_exists(TABLE_ORDERS, "billing_name");

// Optional Tax Rate/Percent
$AddShippingTax = "0.0"; // e.g. shipping tax of 17.5% is "17.5"

$orders_statuses = array();
$orders_status_array = array();
$orders_status_query = tep_db_query("select orders_status_id, orders_status_name from " . TABLE_ORDERS_STATUS . " where language_id = '" . (int)$languages_id . "'");
while ($orders_status = tep_db_fetch_array($orders_status_query)) {
  $orders_statuses[] = array('id' => $orders_status['orders_status_id'],
                             'text' => $orders_status['orders_status_name']);
  $orders_status_array[$orders_status['orders_status_id']] = $orders_status['orders_status_name'];
}

//get shipping method
$orders_ship_method = array();
$orders_ship_method_array = array();
$orders_ship_method_query = tep_db_query("select ship_method from orders_ship_methods where ship_method_language = '" . (int)$languages_id . "'");
while ($orders_ship_methods = tep_db_fetch_array($orders_ship_method_query)) {
  $orders_ship_method[] = array('id'   => $orders_ship_methods['ship_method'],
                                'text' => $orders_ship_methods['ship_method']);
  $orders_ship_method_array[$orders_ship_methods['ship_method']] = $orders_ship_methods['ship_method'];
}

//get pay method
$orders_pay_method = array();
$orders_pay_method_array = array();
$orders_pay_method_query = tep_db_query("select pay_method from orders_pay_methods where pay_method_language =  '" . (int)$languages_id . "'");
while ($orders_pay_methods = tep_db_fetch_array($orders_pay_method_query)) {
  $orders_pay_method[] = array('id'   => $orders_pay_methods['pay_method'],
                                'text' => $orders_pay_methods['pay_method']);
  $orders_pay_method_array[$orders_pay_methods['pay_method']] = $orders_pay_methods['pay_method'];
}
//get variables
if (isset($_GET['oID'])){
  $oID = tep_db_prepare_input($_GET['oID']);
} else if (isset($_POST['oID'])) {
  $oID = $_POST['oID'] ;
} else {
  $oID = '' ;
}

if (isset($_GET['step'])) {
  $step = $_GET['step'] ;
} else if (isset($_POST['step'])) {
  $step = $_POST['step'] ;
} else {
  $step = 1 ;
}

// begin action
if (isset($_GET['action'])) {
  $action = $_GET['action'] ;
} else if (isset($_POST['action'])) {
  $action = $_POST['action'] ;
} else {
  $action = 'edit' ;
}
//$action = (isset($_GET['action']) ? $_GET['action'] : 'edit');

if (tep_not_null($action)) {
  switch ($action) {
    case 'update_order':
		if(count($_POST) <= 2) {
			$messageStack->add_session('search', 'No Post Data', 'error');
			tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, 'oID=' . $oID));
			exit();
		}

		if(trim($_POST['update_customer_name']) == '' || trim($_POST['update_billing_name']) == '' || trim($_POST['update_delivery_name']) == '') {
			$messageStack->add_session('search', 'No Post Data', 'error');
			tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, 'oID=' . $oID));
			exit();
		}

      $order = new order($oID);
      $status = tep_db_prepare_input($_POST['status']);
      $tracking_nr = tep_db_prepare_input($_POST['tracking_nr']);
      $shipping_type = tep_db_prepare_input($_POST['shipping_type']);
      $comments = tep_db_prepare_input($_POST['comments']);
	  if($shipping_type == 'ups') {
	     $trackinglink = 'http://wwwapps.ups.com/WebTracking/track?trackNums='.$tracking_nr.'&track.x=Track';
	  }elseif($shipping_type == 'fedex'){
		 $trackinglink = 'https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber='.$tracking_nr.'&cntry_code=us';
	  }elseif($shipping_type == 'usps'){
	     $trackinglink = 'https://tools.usps.com/go/TrackConfirmAction.action?tLabels='.$tracking_nr;
	  }else{
	  	$trackinglink = '';
	  }
      if($trackinglink != ''){
      	$generatedtrackinglink = '<p style="margin:0">Tracking Number: <a href=\''.$trackinglink.'\' target=\'_blank\'>'.$tracking_nr.'</a></p>';
      	$comments .= $generatedtrackinglink;
      }
	  if($status == 3 && $tracking_nr == ''){
		  $messageStack->add_session('search', 'For shipping status you need to enter tracking number !', 'warning');
		  tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, tep_get_all_get_params(array('action')) . 'oID=' . $oID . '&action=edit', 'SSL'));
	  }

      // Update Order Info
      $UpdateOrders = "update " . TABLE_ORDERS . " set
        customers_name = '" . tep_db_input(stripslashes($_POST['update_customer_name'])) . "',
        customers_company = '" . tep_db_input(stripslashes($_POST['update_customer_company'])) . "',
        customers_street_address = '" . tep_db_input(stripslashes($_POST['update_customer_street_address'])) . "',
        customers_suburb = '" . tep_db_input(stripslashes($_POST['update_customer_suburb'])) . "',
        customers_city = '" . tep_db_input(stripslashes($_POST['update_customer_city'])) . "',
        customers_state = '" . tep_db_input(stripslashes($_POST['update_customer_state'])) . "',
        customers_postcode = '" . tep_db_input($_POST['update_customer_postcode']) . "',
        customers_country = '" . tep_db_input(stripslashes($_POST['update_customer_country'])) . "',
        customers_telephone = '" . tep_db_input($_POST['update_customer_telephone']) . "',
        customers_email_address = '" . strtolower(tep_db_input($_POST['update_customer_email_address'])) . "',";

      if($SeparateBillingFields)
      {
      $UpdateOrders .= "billing_name = '" . tep_db_input(stripslashes($_POST['update_billing_name'])) . "',
        billing_company = '" . tep_db_input(stripslashes($_POST['update_billing_company'])) . "',
        billing_street_address = '" . tep_db_input(stripslashes($_POST['update_billing_street_address'])) . "',
        billing_suburb = '" . tep_db_input(stripslashes($_POST['update_billing_suburb'])) . "',
        billing_city = '" . tep_db_input(stripslashes($_POST['update_billing_city'])) . "',
        billing_state = '" . tep_db_input(stripslashes($_POST['update_billing_state'])) . "',
        billing_telephone = '" . tep_db_input($_POST['update_billing_telephone']) . "',
        billing_fax = '" . tep_db_input($_POST['update_billing_fax']) . "',
        billing_email_address = '" . tep_db_input($_POST['update_billing_email_address']) . "',
        billing_postcode = '" . tep_db_input($_POST['update_billing_postcode']) . "',
        billing_country = '" . tep_db_input(stripslashes($_POST['update_billing_country'])) . "',";
      }

      // Becasue of the way the form is written these variable may not be passed from the previous form
      // so they must be checked to see if they are set if not the must be emtied,

      //initlize variable
      $account_name = '';
      $account_number = '';
      $po_number = '';
      //check to see if form passed these variable
      if(isset($_POST['account_name'])){
        $account_name = tep_db_input($_POST['account_name']);
        }
      if(isset($_POST['account_name'])){
        $account_number = tep_db_input($_POST['account_number']);
        }
      if(isset($_POST['po_number'])){
        $po_number = tep_db_input($_POST['po_number']);
        }

      $UpdateOrders .= "delivery_name = '" . tep_db_input(stripslashes($_POST['update_delivery_name'])) . "',
        delivery_company = '" . tep_db_input(stripslashes($_POST['update_delivery_company'])) . "',
        delivery_street_address = '" . tep_db_input(stripslashes($_POST['update_delivery_street_address'])) . "',
        delivery_suburb = '" . tep_db_input(stripslashes($_POST['update_delivery_suburb'])) . "',
        delivery_city = '" . tep_db_input(stripslashes($_POST['update_delivery_city'])) . "',
        delivery_state = '" . tep_db_input(stripslashes($_POST['update_delivery_state'])) . "',
        delivery_postcode = '" . tep_db_input($_POST['update_delivery_postcode']) . "',
        delivery_country = '" . tep_db_input(stripslashes($_POST['update_delivery_country'])) . "',
        delivery_telephone = '" . tep_db_input($_POST['update_delivery_telephone']) . "',
        delivery_fax = '" . tep_db_input($_POST['update_delivery_fax']) . "',
        delivery_email_address = '" . tep_db_input($_POST['update_delivery_email_address']) . "',
        payment_method = '" . tep_db_input($_POST['update_info_payment_method']) . "',
        account_name = '" . $account_name . "',
        account_number = '" . $account_number . "',
        po_number = '" . $po_number . "',
        last_modified = now() ";
      $UpdateOrders .= " where orders_id = '" . tep_db_input($oID) . "' ";
      tep_db_query($UpdateOrders);

	  if($tracking_nr != ''){
		 $update_order = "UPDATE orders SET  shipment_track_num = '".$tracking_nr."', shipment_method = '".$shipping_type."' WHERE orders_id = '".(int)$oID."'";
		 tep_db_query($update_order);
	  }

      $Query1 = "update orders set last_modified = now() where orders_id = '" . tep_db_input($oID) . "';";
      tep_db_query($Query1);
      $order_updated = 1;

        $check_status_query = tep_db_query("select customers_name, customers_email_address, orders_status, date_purchased from " . TABLE_ORDERS . " where orders_id = '" . (int)$oID . "'");
        $check_status = tep_db_fetch_array($check_status_query);

        // NOTE: you must post the order status to both the order, and order status history
        if($CommentsWithStatus) {
          // always update date and time on order_status
          //check to see if can download status change
          if ( ($check_status['orders_status'] != $status) || $comments != '' || ($status ==DOWNLOADS_ORDERS_STATUS_UPDATED_VALUE) ) {
            tep_db_query("update " . TABLE_ORDERS . " set orders_status = '" . tep_db_input($status) . "' , last_modified = now() where orders_id = '" . (int)$oID . "'");
            $check_status_query2 = tep_db_query("select customers_name, customers_email_address, orders_status, date_purchased from " . TABLE_ORDERS . " where orders_id = '" . (int)$oID . "'");
            $check_status2 = tep_db_fetch_array($check_status_query2);
            if ( $check_status2['orders_status']==DOWNLOADS_ORDERS_STATUS_UPDATED_VALUE ) {
              tep_db_query("update " . TABLE_ORDERS_PRODUCTS_DOWNLOAD . " set download_maxdays = '" . tep_get_configuration_key_value('DOWNLOAD_MAX_DAYS') . "', download_count = '" . tep_get_configuration_key_value('DOWNLOAD_MAX_COUNT') . "' where orders_id = '" . (int)$oID . "'");
            }
            $customer_notified = '0';
            //if notify = 1 then send email update
            if (isset($_POST['notify']) && ($_POST['notify'] == 'on')) {
              $notify_comments = '';

              if (isset($_POST['notify_comments']) && ($_POST['notify_comments'] == 'on')) {
                $notify_comments = sprintf(EMAIL_TEXT_COMMENTS_UPDATE, $comments) . "\n\n";
              }

              $email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' .
              tep_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL') . "\n" . EMAIL_TEXT_DATE_ORDERED .
              ' ' . tep_date_long($check_status['date_purchased']) . "\n\n" . $notify_comments .
              sprintf(EMAIL_TEXT_STATUS_UPDATE, $orders_status_array[$status]);

              tep_mail($check_status['customers_name'], $check_status['customers_email_address'], EMAIL_TEXT_SUBJECT, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);

              $customer_notified = '1';
            }

			$sql_data_oh_array = array('orders_id' => (int)$oID,
								  'admin_id' => $_SESSION['login_id'],
								  'orders_status_id' => tep_db_input($status),
								  'date_added' => 'now()',
								  'comments' => tep_db_input($comments),
								  'customer_notified' => tep_db_input($customer_notified));
			tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_oh_array);

            $order_updated = 1;

          }
        }

        // RCI code start
        echo $cre_RCI->get('editorders', 'updateorder', false);
        // RCI code eof

        // check to see if there are products to update
        if (count($update_products) > 0) {
          // Update Products
          $RunningSubTotal = 0;
          $RunningTax = 0;
          // CWS EDIT (start) -- Check for existence of subtotals...
          // Do pre-check for subtotal field existence
          $ot_subtotal_found = 0;
          //$total_details = $_GET['total_details'];

          //update_totals
          if (isset($_GET['update_totals'])) {
            $update_totals = $_GET['update_totals'] ;
          } else if (isset($_POST['update_totals'])) {
            $update_totals = $_POST['update_totals'] ;
          } else {
           $update_totals = array();
          }

          if (isset($_GET['update_products'])) {
            $update_products = $_GET['update_products'] ;
          } else if (isset($_POST['update_products'])) {
            $update_products = $_POST['update_products'] ;
          } else {
           $update_products = array();
          }

          $ot_class = '';
          foreach($update_totals as $total_details) {
            extract($total_details,EXTR_PREFIX_ALL,"ot");

            if($ot_class == "ot_subtotal") {
              $ot_subtotal_found = 1;
              break;
            }
          }

          // CWS EDIT (end) -- Check for existence of subtotals...
          //check to see if any product as in order yet.
          if (!(empty($update_products))) {
            foreach($update_products as $orders_products_id => $products_details) {
              // Update orders_products Table
              //UPDATE_INVENTORY_QUANTITY_START##############################################################################################################
              $order_query = tep_db_query("select products_id, products_quantity from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id = '" . (int)$orders_products_id . "'");
              if (tep_db_num_rows($order_query) > 0) {
                $order_array = tep_db_fetch_array($order_query);
              } else {
                $order_array['products_quantity'] = 0;
              }
              if ($products_details['qty'] != $order_array['products_quantity']) {
                $quantity_difference = (int)($products_details["qty"]) - (int)($order_array['products_quantity']);
                $products_quantity = tep_db_fetch_array(tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int)$order_array['products_id'] . "'"));
                $products_new_quantity = (int)$products_quantity['products_quantity'] - $quantity_difference;
                $products_ordered = 0;
                if ($order_array['products_quantity'] == 0) {
                  $products_ordered = 1;
                }
                tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = " . $products_new_quantity . ", products_ordered = products_ordered + " . (int)$products_ordered . " where products_id = '" . (int)$order_array['products_id'] . "'");
              }

              //UPDATE_INVENTORY_QUANTITY_END##############################################################################################################
              if ($products_details["qty"] > 0) {
                //check for qty pricing.
                if ($products_details['qty'] >= 1){
                  $customer_id = $order->customer['id'];
                  $products_check = $pf->loadProduct((int)$order_array['products_id'], $languages_id, $customer_id);
                  $p_products_price = $pf->computePrice($products_details['qty']);
                  // compare final price to computed price if differnet then use computed price.
                  if ($products_details['price'] != $p_products_price){
                    $products_details['price'] = $p_products_price ;
                  }
                } // end qtycheck

                //if price is 0, get the regular price
                if($p_products_price == 0) {
                  $product_price_query = tep_db_query("select products_price from " . TABLE_PRODUCTS . " where products_id = '" . $order_array['products_id'] . "'");
                  if (tep_db_num_rows($product_price_query)) {
                    $product_price = tep_db_fetch_array($product_price_query);
                    $p_products_price = $product_price['products_price'];
                  }
                }

                /*
                //get product per order
                 $attributes_order_query = tep_db_query("select poa.options_values_price, poa.price_prefix FROM
                  " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " poa
                   WHERE
                  orders_id = '" . $oID . "'
                  and orders_products_id= '" . $orders_products_id. "'");
                   $AddedOptionsPrice = '';
                while($attributes_order = tep_db_fetch_array($attributes_order_query)){
                           if ($attributes_order['price_prefix'] == '+'){
                              $AddedOptionsPrice += $attributes_order['options_values_price'];
                             }else{
                              $AddedOptionsPrice -= $attributes_order['options_values_price'];
                            }
                   }
                */
                $Query = "update " . TABLE_ORDERS_PRODUCTS . " set
                  products_model = '" . $products_details['model'] . "',
                  products_name = '" . str_replace("'", "&#39;", $products_details['name']) . "',
                  final_price = '" . $products_details['final_price']. "',
                  products_tax = '" . $products_details['tax'] . "',
                  products_quantity = '" . $products_details['qty'] . "'
                  where orders_products_id = '$orders_products_id';";
                tep_db_query($Query);

                // Update Tax and Subtotals
                $RunningSubTotal += $products_details["qty"] * $products_details['final_price'];
                $RunningTax += (($products_details["tax"]/100) * ($products_details['qty'] * $products_details['final_price']));
              } else {
                // 0 Quantity = Delete
                $Query = "delete from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id = '$orders_products_id';";
                tep_db_query($Query);
                $Query = "delete from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_products_id = '$orders_products_id';";
                tep_db_query($Query);
              }
            }
          }//end empty


          // Shipping Tax
          foreach ($update_totals as $total_index => $total_details) {
            extract($total_details,EXTR_PREFIX_ALL,"ot");
            if ($ot_class == "ot_shipping") {
              $RunningTax += (($AddShippingTax / 100) * $ot_value);
            }
          }

          // Update Totals
          $RunningTotal = 0;
          $sort_order = 0;

          // Do pre-check for Tax field existence
          $ot_tax_found = 0;
          foreach ($update_totals as $total_details) {
            extract($total_details,EXTR_PREFIX_ALL,"ot");
            if ($ot_class == "ot_tax") {
              $ot_tax_found = 1;
              break;
            }
          }
          

          foreach ($update_totals as $total_index => $total_details) {
            extract($total_details,EXTR_PREFIX_ALL,"ot");

             if (($ot_tax_found == 0) && ($RunningTax > 0)) {
              //check to see if it's  an admin order or catalog order
              $order_type = 0;

              $ot_total_tax_exists = 0;
              $totals_query_5= tep_db_query("select class as ot_class_1  from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $oID . "' and class = 'ot_tax'");

              while ($totals_5 = tep_db_fetch_array($totals_query_5)) {
                $ot_total_tax_exists = 1;
              }

              //get ot_total from db since that does not exist yet.
              $totals_query_4= tep_db_query("select class as ot_class_1, sort_order  from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $oID . "' and class = 'ot_total' order by sort_order");
              while ($totals_4 = tep_db_fetch_array($totals_query_4)) {
                $sort_order_tmp_4 = $totals_4['sort_order'];
                $ot_class_tmp_4 = $totals_4['ot_class_1'];
              }

              if ( ($ot_class_tmp_4 == "ot_total" ) && ($sort_order_tmp_4 <= 5)) {
                $sort_order_tmp = $sort_order_tmp_4 - 1;
              } else {
                $sort_order_tmp = MODULE_ORDER_TOTAL_TAX_SORT_ORDER ;
              }
              $ot_title_tax = 'Tax';
              $ot_text_tax = $currencies->format($RunningTax, 1, $order->info['currency'], $order->info['currency_value']);
              $ot_value_tax = $RunningTax;
              $ot_class_tax = 'ot_tax';
              $sort_order_tax = $sort_order_tmp;

              if ($ot_total_tax_exists == 0){
                $Query = "insert into " . TABLE_ORDERS_TOTAL . " set
                          orders_id = '$oID',
                          title = '$ot_title_tax',
                          text = '$ot_text_tax',
                          value = '$ot_value_tax',
                          class = '$ot_class_tax',
                          sort_order = '$sort_order_tax'";
                        tep_db_query($Query);

                $ot_tax_found = 1;
              }
            }
            if( trim(strtolower($ot_title)) == "tax" || trim(strtolower($ot_title)) == "tax:" ) {
              if($ot_class != "ot_tax" && $ot_tax_found == 0) {
                // Inserting Tax
                $ot_class = "ot_tax";
                $ot_value = "x"; // This gets updated in the next step
                $ot_tax_found = 1;
              }
            }

            if( trim($ot_title) && trim($ot_value) ) {
              $sort_order++;

              // Update ot_subtotal, ot_tax, and ot_total classes
              if($ot_class == "ot_subtotal") $ot_value = $RunningSubTotal;

              if($ot_class == "ot_tax") {
                $ot_value = $RunningTax;
                // print "ot_value = $ot_value<br>\n";
              }

              //discount
              // CWS EDIT (start) -- Check for existence of subtotals...
              if($ot_class == "ot_total") {
                $ot_value = $RunningTotal;
                if ( !$ot_subtotal_found ) {
                  // There was no subtotal on this order, lets add the running subtotal in.
                  $ot_value = $ot_value + $RunningSubTotal;
                }
              }
              // CWS EDIT (end) -- Check for existence of subtotals...

              // Set $ot_text (display-formatted value)
              // $ot_text = "\$" . number_format($ot_value, 2, '.', ',');

              $order = new order($oID);
              $ot_text = $currencies->format($ot_value, 1, $order->info['currency'], $order->info['currency_value']);

              if($ot_class == "ot_total") $ot_text = "<b>" . $ot_text . "</b>";

              if($ot_total_id > 0)
               $Query = "update " . TABLE_ORDERS_TOTAL . " set title = '$ot_title', text = '$ot_text', value = '$ot_value' where orders_total_id = '$ot_total_id'";
              else
                $Query = "insert into " . TABLE_ORDERS_TOTAL . " set orders_id = '$oID', title = '$ot_title', text = '$ot_text', value = '$ot_value', class = '$ot_class', sort_order = '$sort_order'";
			  tep_db_query($Query);

              if ($ot_class == "ot_shipping" || $ot_class == "ot_lev_discount" || $ot_class == "ot_custom" || $ot_class == "ot_cod_fee") {
                // Again, because products are calculated in terms of default currency, we need to align shipping, custom etc. values with default currency
                $RunningTotal += $ot_value;
              } else if($ot_class == "ot_coupon" ||$ot_class == "ot_customer_discount" || $ot_class == "ot_discount" || $ot_class == "ot_gv"){
                //subtract discounts
                $RunningTotal -= $ot_value;
              } else {
                //add to gether all other ot-totals
                if($ot_class != "ot_tax") {
                  $RunningTotal += $ot_value;
                } else if (($ot_class == "ot_tax") && (DISPLAY_PRICE_WITH_TAX == true) ) {
                  //add tax to ot-total
                  $RunningTotal += $ot_value;
                }
              }
            } elseif (($ot_total_id > 0) && ($ot_class != "ot_shipping")) {
              // Delete Total Piece
              $Query = "delete from " . TABLE_ORDERS_TOTAL . " where orders_total_id = '$ot_total_id'";
              tep_db_query($Query);
            }
          }
        } //end count($update_products)

        if ($order_updated == 1) {
          //  $messageStack->add_session('search', SUCCESS_ORDER_UPDATED, 'success');
        } else {
          $messageStack->add_session('search', WARNING_ORDER_NOT_UPDATED, 'warning');
        }
		$mode = (isset($_POST['mode']) && $_POST['mode'] != '') ? $_POST['mode'] : 'save';
		//echo $_SESSION['back_url'];exit;
		if ($mode == 'save')
			tep_redirect(tep_href_link(FILENAME_ORDERS, 'oID=' . $oID .'&'.$_SESSION['back_url'], 'SSL'));
		else
        	tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, tep_get_all_get_params(array('action')) . 'oID=' . $oID . '&action=edit', 'SSL'));
        break;


      //********************* add product *************
      // Add a Product
    case 'add_product':
      if ($step == 5) {

        // Get Order Info
        $order = new order($oID);

        if (isset($_GET["add_product_options"])) {
          $add_product_options = $_GET["add_product_options"];
        } else if (isset($_POST["add_product_options"])) {
          $add_product_options = $_POST["add_product_options"];
        } else {
          $add_product_options = array();
        }

        if (isset($_POST["id"])) {
          $add_product_options = $_POST["id"];
        } else {
          $add_product_options = array();
        }

        $add_product_products_id = (isset($_POST['add_product_products_id']) ? $_POST['add_product_products_id'] : '');
        $add_product_quantity = (isset($_POST['add_product_quantity']) ? $_POST['add_product_quantity'] : '');
        $customer_id = (isset($order->customer['id']) ? $order->customer['id'] : '');

        // intialize for first attribute
        $AddedOptionsPrice = 0;
        $option_is_text = 0;
        $item_has_down = 0;
        $query_products_options_values = '';
        $products_options_values= '';

        $customer_id = $order->customer['id'];
        // Get Product Info
        $product_info_guery_1 = tep_db_query("select
           pd.products_name,
           p.products_id,
           p.products_price,
           p.products_tax_class_id,
           p.products_model,
           p.products_status
          FROM " . TABLE_PRODUCTS . " p,
               " . TABLE_PRODUCTS_DESCRIPTION . " pd
          where
           p.products_id = '" . $add_product_products_id . "'
           and pd.products_id = p.products_id
           and pd.language_id = '" . (int)$languages_id . "'
          ");

        while ($product_info_array = tep_db_fetch_array($product_info_guery_1)){
          $add_products_model = $product_info_array['products_model'];
          $add_products_name = $product_info_array['products_name'] ;
          $add_products_price = $product_info_array['products_price'];
          $products_tax_class_id = $product_info_array['products_tax_class_id'];
        }

        $products = $pf->loadProduct($add_product_products_id, $languages_id, $customer_id);
        $p_products_price = $pf->computePrice($add_product_quantity);

        //if price is 0, get the regular price
        if($p_products_price == 0){
          $product_price_query = tep_db_query("select products_price from " . TABLE_PRODUCTS . " where products_id = '" . $add_product_products_id . "'");
          if (tep_db_num_rows($product_price_query)) {
            $product_price = tep_db_fetch_array($product_price_query);
            $p_products_price = $product_price['products_price'];
          }
        }

        // Following functions are defined at the bottom of this file
        $CountryID = tep_get_country_id($order->delivery["country"]);
        $ZoneID = tep_get_zone_id($CountryID, $order->delivery["state"]);

        $ProductsTax = tep_get_tax_rate($products_tax_class_id, $CountryID, $ZoneID);

        $Query = "insert into " . TABLE_ORDERS_PRODUCTS . " set
            orders_id = '" . $oID . "',
            products_id = '" . $add_product_products_id . "',
            products_model = '" . $add_products_model . "',
            products_name = '" . str_replace("'", "&#39;", $add_products_name) . "',
            products_price = '" . $p_products_price . "',
            final_price = '" . ($p_products_price + $AddedOptionsPrice) . "',
            products_tax = '" . $ProductsTax . "',
            products_quantity = '" . $add_product_quantity . "'";
        tep_db_query($Query);
        $new_product_id = tep_db_insert_id();

        // Get Product Attribute Info

        if( (isset($add_product_options)) && (is_array($add_product_options)) ){

          foreach($add_product_options as $attri_id => $attri_option_value_id){
            $products_id_query = $add_product_products_id;

            //get option type:
            $attributes_type_query = tep_db_query("select pa.products_attributes_id, pa.options_values_id, po.options_type
                  FROM
                  " . TABLE_PRODUCTS_ATTRIBUTES . " pa,
                  " . TABLE_PRODUCTS_OPTIONS . " po
                WHERE
                pa.products_id = '" . $products_id_query . "'
                and pa.products_attributes_id = '" . $attri_id. "'
                and po.products_options_id = pa.options_id" );

            while ($attributes_type = tep_db_fetch_array($attributes_type_query)){
                    $attributes_options_type = $attributes_type['options_type'];
            }

            // if drop down select
            if($attributes_options_type == 0){
              $attri_id = $attri_option_value_id ;
            }

            //echo '$attri_id ' . $attri_id ;
            //echo  '$attri_option_value_id ' . $attri_option_value_id;
            ////echo '$attributes_options_type ' . $attributes_options_type;
            //echo '<br>';

            //check box array
            if (is_array($attri_option_value_id)){
              $attri_option_value_id_tmp = $attri_option_value_id ;
              foreach($attri_option_value_id_tmp as $attri_option_id_tmp => $attri_option_value_id_tmp){
                $attri_option_id = $attri_option_id_tmp ;
                $attri_option_value_id= $attri_option_value_id_tmp;
              }

              unset($attri_option_value_id);
            }

            //intialize values
            $option_is_text = 0;
            $item_has_down = 0;
            $query_products_options_values = '';
            $products_options_values= '';

            // check to see if there is a downloadable file
            if (DOWNLOAD_ENABLED ==  1) {
              //check for downloads
              $attributes_download_query = tep_db_query("select pa.products_attributes_id, poval.products_options_values_id, pa.products_id, pa.options_id, pa.options_values_id, pa.options_values_price, pa.price_prefix, poptt.products_options_name, poval.products_options_values_name, pad.products_attributes_filename, pad.products_attributes_maxdays, pad.products_attributes_maxcount  FROM
                   " . TABLE_PRODUCTS_OPTIONS . " popt,
                   " . TABLE_PRODUCTS_OPTIONS_TEXT . " poptt,
                   " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval,
                   " . TABLE_PRODUCTS_ATTRIBUTES . " pa,
                   " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
                 WHERE
                  pa.products_id = '" . $products_id_query . "'
                  and pa.products_attributes_id = '" . $attri_id. "'
                  and poptt.products_options_text_id = pa.options_id
                  and poval.products_options_values_id =  pa.options_values_id
                  and poptt.language_id = '" . (int)$languages_id . "'
                  and poval.language_id = '" . (int)$languages_id . "'
                 and pad.products_attributes_id = pa.products_attributes_id
                order by pa.products_options_sort_order
                  limit 1");

              if (tep_db_num_rows($attributes_download_query)) {
                $item_has_down = '1';
              } // end if tep_db_num_rows
            }// end if DOWNLOAD_ENABLED

            //check for text
            if($attributes_options_type != '1' && $attributes_options_type != '4'){
              $query_products_options_values = $attri_option_value_id ;
              $option_is_text = 0 ;
            } else {
              if (!empty($attri_option_value_id)){
                $query_products_options_values = 0;
                $option_is_text = 1 ;
              }
            }

            // get attibutes data
            if ($item_has_down == '1')  {
              $attributes_query = tep_db_query("select pa.products_attributes_id, poval.products_options_values_id, pa.products_id, pa.options_id, pa.options_values_id, pa.options_values_price, pa.price_prefix, poptt.products_options_name, poval.products_options_values_name, pad.products_attributes_filename, pad.products_attributes_maxdays, pad.products_attributes_maxcount  FROM
                  " . TABLE_PRODUCTS_OPTIONS . " popt,
                  " . TABLE_PRODUCTS_OPTIONS_TEXT . " poptt,
                  " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval,
                  " . TABLE_PRODUCTS_ATTRIBUTES . " pa,
                  " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
                   WHERE
                    pa.products_id = '" . $products_id_query . "'
                    and pa.products_attributes_id = '" . $attri_id. "'
                  and poptt.products_options_text_id = pa.options_id
                  and poval.products_options_values_id =  pa.options_values_id
                  and poptt.language_id = '" . (int)$languages_id . "'
                  and poval.language_id = '" . (int)$languages_id . "'
                  and pad.products_attributes_id = pa.products_attributes_id
                  order by pa.products_options_sort_order
                  limit 1
                  ");
            } else if (($item_has_down == '0') && ($option_is_text == 0)){
              $attributes_query = tep_db_query("select pa.products_attributes_id, poval.products_options_values_id, pa.products_id, pa.options_id, pa.options_values_id, pa.options_values_price, pa.price_prefix, poptt.products_options_name, poval.products_options_values_name from
                  " . TABLE_PRODUCTS_OPTIONS . " popt,
                  " . TABLE_PRODUCTS_OPTIONS_TEXT . " poptt,
                  " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval,
                  " . TABLE_PRODUCTS_ATTRIBUTES . " pa
                where
                    pa.products_id = '" . $products_id_query . "'
                    and pa.products_attributes_id = '" . $attri_id. "'
                  and poptt.products_options_text_id = pa.options_id
                  and poval.products_options_values_id =  pa.options_values_id
                  and poptt.language_id = '" . (int)$languages_id . "'
                  and poval.language_id = '" . (int)$languages_id . "'
                  order by pa.products_options_sort_order
                  limit 1
                  ");
            } else if ($option_is_text == 1){
              $attributes_query = tep_db_query("select poval.products_options_values_id, pa.products_attributes_id, pa.products_id, pa.options_id, pa.options_values_id, pa.options_values_price, pa.price_prefix, poptt.products_options_name  FROM
                  " . TABLE_PRODUCTS_OPTIONS . " popt,
                  " . TABLE_PRODUCTS_OPTIONS_TEXT . " poptt,
                  " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval,
                  " . TABLE_PRODUCTS_ATTRIBUTES . " pa
                   WHERE
                    pa.products_id = '" . $products_id_query . "'
                    and pa.products_attributes_id = '" . $attri_id. "'
                  and poptt.products_options_text_id = pa.options_id
                  and poptt.language_id = '" . (int)$languages_id . "'
                  order by pa.products_options_sort_order
                  limit 1
                  ");
            }

            while  ($attributes = tep_db_fetch_array($attributes_query)){
              if($option_is_text == 1){
                $products_options_values = htmlentities(stripslashes($attri_option_value_id), ENT_QUOTES);
              } else {
                $products_options_values = $attributes['products_options_values_name'];
              }

              $orders_products_id = $new_product_id;
              $products_options = $attributes['products_options_name'];
              $options_values_price = $attributes['options_values_price'];
              $price_prefix = $attributes['price_prefix'];
              $products_options_id = $attributes['options_id'];
              $products_options_values_id = $attributes['options_values_id'];

              //downloads
              if ($item_has_down == '1') {
                $orders_products_filename = $attributes['products_attributes_filename'];
                $download_maxdays = $attributes['products_attributes_maxdays'];
                $download_count = $attributes['products_attributes_maxcount'];
              }

              //add attibute price to product price
              if ($price_prefix == '+'){
                $AddedOptionsPrice += $options_values_price;
              } else {
                $AddedOptionsPrice -= $options_values_price;
              }

              // update final price
              $product_price_update = tep_db_query("select final_price from
                                           " . TABLE_ORDERS_PRODUCTS . "
                                          where
                                          orders_id = $oID and
                                          orders_products_id = $orders_products_id ");

              while  ($product_price_array_1 = tep_db_fetch_array($product_price_update)){
                  $Query_final_price = "update " . TABLE_ORDERS_PRODUCTS . " set
                   final_price = '" . ($p_products_price + $AddedOptionsPrice) . "'
                   where orders_id = $oID and orders_products_id = $orders_products_id ";
                 tep_db_query($Query_final_price);
              }

              if(isset($add_product_options)){
                 $Query = "insert into " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " set
                             orders_id = $oID,
                             orders_products_id = $orders_products_id,
                             products_options = '". $products_options . "',
                             products_options_values = '" . $products_options_values . "',
                             options_values_price = $options_values_price,
                             price_prefix = '" . $price_prefix . "',
                             products_options_id = '" . $products_options_id . "' ,
                             products_options_values_id =  '" . $products_options_values_id . "' ";

                tep_db_query($Query);
              }

              // add download insert
              if ((DOWNLOAD_ENABLED ==  1) && isset($orders_products_filename) && tep_not_null($orders_products_filename)) {
                $sql_data_array = array('orders_id' => $oID,
                                        'orders_products_id' => $new_product_id,
                                        'orders_products_filename' => $orders_products_filename,
                                        'download_maxdays' => $download_maxdays,
                                        'download_count' => $download_count);
                tep_db_perform(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
              }
            } // end while get option
          } //
        }

        //UPDATE_INVENTORY_QUANTITY_START##############################################################################################################
        tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = products_quantity - " . $add_product_quantity . ", products_ordered = products_ordered + " . $add_product_quantity . " where products_id = '" . $add_product_products_id . "'");
        //UPDATE_INVENTORY_QUANTITY_END##############################################################################################################

        //get total of product using order class
        $order = new order($oID);
        $RunningSubTotal = 0;
        $RunningTax = 0;

        for ($i=0; $i<sizeof($order->products); $i++) {
          $RunningSubTotal += ($order->products[$i]['qty'] * $order->products[$i]['final_price']);
          //tax caculated on a per product bases
          $RunningTax += (($order->products[$i]['tax'] / 100) * ($order->products[$i]['qty'] * $order->products[$i]['final_price']));
        }

        //subtotal to total
        $RunningTotal = $RunningSubTotal;

        //add tax
        $RunningTotal += $RunningTax;

        // Calculate Tax and Sub-Totals
        // get exsisting order details so we can update them

        $totals_query_5 = tep_db_query("select title as ot_title, text as ot_text, value as ot_value, class as ot_class  from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $oID . "' order by sort_order");
        while ($totals_1 = tep_db_fetch_array($totals_query_5)) {
          $totals_array[] = array('ot_title' => $totals_1['ot_title'],
                                  'ot_text' => $totals_1['ot_text'],
                                  'ot_value' => $totals_1['ot_value'],
                                  'ot_class' => $totals_1['ot_class']);
        }

        //parse array
        for ($i=0, $n=sizeof($totals_array); $i<$n; $i++) {
          $totals = $totals_array[$i];

          //add other order totals
          if ($totals['ot_class'] == "ot_shipping" || $totals['ot_class'] == "ot_custom" || $totals['ot_class'] == "ot_cod_fee") {
            // add ot_ items not already added
            $RunningTotal += $totals['ot_value'] / $order->info['currency_value'];
            //deduct discounts
          } else if($totals['ot_class'] == "ot_coupon" ||$totals['ot_class'] == "ot_customer_discount" || $totals['ot_class'] == "ot_discount" || $totals['ot_class'] == "ot_gv" || $totals['ot_class'] == "ot_lev_discount" ){
            //subtract discounts
            $RunningTotal -= $totals['ot_value'] / $order->info['currency_value'];
          }

          // Tax
          $Query = "update " . TABLE_ORDERS_TOTAL . " set
            text = '\$" . number_format($RunningTax, 2, '.', ',') . "',
            value = '" . $RunningTax . "'
            where class='ot_tax' and orders_id=$oID";
          tep_db_query($Query);

          // Sub-Total
          $Query = "update " . TABLE_ORDERS_TOTAL . " set
            text = '\$" . number_format($RunningSubTotal, 2, '.', ',') . "',
            value = '" . $RunningSubTotal . "'
            where class='ot_subtotal' and orders_id=$oID";
          tep_db_query($Query);

          $Query = "update " . TABLE_ORDERS_TOTAL . " set
            text = '<b>\$" . number_format($RunningTotal, 2, '.', ',') . "</b>',
            value = '" . $RunningTotal . "'
            where class='ot_total' and orders_id=$oID";
          tep_db_query($Query);
        } //end of for

        tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, tep_get_all_get_params(array('action')) . 'oID=' . $_GET['oID'] . '&action=edit', 'SSL'));
      }
      break;
  } //end action
}// end action NUll

if (($action == 'edit') && isset($_GET['oID'])) {
  $oID = (int)$_GET['oID'];

  $orders_query = tep_db_query("select orders_id from " . TABLE_ORDERS . " where orders_id = '" . (int)$oID . "'");
  $order_exists = 1;
  if (!tep_db_num_rows($orders_query)) {
    $order_exists = 0;
    $messageStack->add('search', sprintf(ERROR_ORDER_DOES_NOT_EXIST, $oID), 'error');
  }
}

for ($i=1; $i<13; $i++) {
  $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime(' %m',mktime(0,0,0,$i,1,2000)));
}
$today = getdate();
for ($i=$today['year']; $i < $today['year']+10; $i++) {
  $expires_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
}
for ($i=1; $i < 13; $i++) {
  $start_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime(' %m',mktime(0,0,0,$i,1,2000)));
}
$today = getdate();
for ($i=$today['year']-4; $i <= $today['year']; $i++) {
  $start_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
}

include(DIR_WS_INCLUDES . 'html_top.php');
include(DIR_WS_INCLUDES . 'header.php');
include(DIR_WS_INCLUDES . 'column_left.php');

$order = new order($oID);

?>
<div id="content" class="content p-relative">
  <h1 class="page-header"><i class="fa fa-laptop"></i> <?php echo HEADING_TITLE; ?></h1>

  <?php if (file_exists(DIR_WS_INCLUDES . 'toolbar.php')) include(DIR_WS_INCLUDES . 'toolbar.php'); ?>

  <div class="col">
	<?php
		if ($messageStack->size('search') > 0) {
		  echo $messageStack->output('search');
		}
	?>
    <!-- begin button bar -->
    <div id="button-bar" class="row">
      <div class="col-9 m-b-10 w-100 pt-1 pl-0 pr-0">
        <a href="<?php echo tep_href_link(FILENAME_ORDERS, ((isset($_SESSION['back_url']) && $_SESSION['back_url'] != '' )?$_SESSION['back_url']:'')); ?>" class="btn btn-link m-r-3 f-w-200 text-primary hidden-xs hidden-sm"><i class="fa fa-chevron-left"></i> <?php echo IMAGE_CANCEL; ?></a>
        <button type="button" onclick="submitOrder('save');" class="btn btn-primary m-r-3"><i class="fa fa-plus"></i> <?php echo BUTTON_SAVE; ?></button>
        <button type="button" onclick="submitOrder('stay');" class="btn btn-info m-r-3 btn-save-stay"><i class="fa fa-plus-square"></i> <?php echo BUTTON_SAVE_STAY; ?></button>
      </div>
      <div class="col-3 m-b-10 pt-1 pr-2" style="display:inherit;">
		<?php
			echo '<a href="javascript:;" onclick="javascript:packaging_slip('.$oID.',\'packaging_slip\')" class="btn btn-grey btn-sm mr-1 ml-1 mt-2 btn-packingslip">' . IMAGE_ORDERS_PACKINGSLIP . '</a>
			<a href="javascript:;" onclick="javascript:invoice('.$oID.',\'invoice\')" class="btn btn-grey btn-sm mr-1 ml-1 mt-2 btn-packingslip">Invoice</a>';
		?>
      </div>
    </div>
    <!-- end button bar -->

    <!-- begin panel -->
    <div class="dark">
      <!-- body_text //-->
      <div id="table-edit-orders" class="table-edit-orders">
        <div class="row">

          <div class="col-12 dark panel-left rounded-left">
            <?php
            if ($order_exists == 1) {
              ?>
              <form role="form" name="edit_order" id="edit_order" method="post" data-parsley-validate>

              <!-- begin invoice -->
              <div class="invoice dark">
                  <!-- div class="invoice-company">
                      <span class="pull-right hidden-print">
                      <a href="javascript:;" class="btn btn-sm btn-success m-b-10"><i class="fa fa-download m-r-5"></i> Export as PDF</a>
                      <a href="javascript:;" onclick="window.print()" class="btn btn-sm btn-success m-b-10"><i class="fa fa-print m-r-5"></i> Print</a>
                      </span>
                      Company Name, Inc
                    </div -->
                <div class="invoice-header">
                      <div class="invoice-from">
                        <small><?php
                        $cID = ($order->customer['id'] == 0) ? ADDRESS_LABEL_PWA : $order->customer['id'];
                        echo strtoupper(ADDRESS_HEADING_CUSTOMER) . ' ID:<span class="label label-inverse ml-1 f-s-11">' . $cID . '</span>'; ?>
                      </small>
                      <button type="button" class="btn btn-success btn-xs ml-2" data-toggle="modal" data-target="#editCustomerModal">Edit</button>
                      <address class="m-t-5 m-b-5">
                        <strong><span id="order_customer_name"><?php echo $order->customer['name']; ?></span></strong><br />
                        <strong><span id="order_customer_company"><?php echo $order->customer['company']; ?></span></strong><br />
                        <span id="order_customer_street_address"><?php echo $order->customer['street_address']; ?></span><br />
                        <?php if (isset($order->customer['suburb']) && $order->customer['suburb'] != '') echo '<span id="order_customer_suburb">' . $order->customer['suburb']; ?></span><br />
                        <span id="order_customer_city"><?php echo $order->customer['city'] . '</span>, <span id="order_customer_state">' . $order->customer['state'] . '</span> <span id="order_customer_postcode">' . $order->customer['postcode']; ?></span><br />
                        <span id="order_customer_country"><?php echo $order->customer['country']; ?></span><br />
                        Phone: <span id="order_customer_telephone"><?php echo $order->customer['telephone']; ?></span><br />
                        E-mail: <span id="order_customer_email_address"><?php echo $order->customer['email_address']; ?></span>
                      </address>
                    </div>
                    <div class="invoice-to">
                      <small><?php echo strtoupper(ADDRESS_HEADING_BILLING); ?></small>
                      <button type="button" class="btn btn-success btn-xs ml-2" data-toggle="modal" data-target="#editBillingModal">Edit</button>
                      <address class="m-t-5 m-b-5">
                        <strong><span id="order_billing_name"><?php echo $order->billing['name']; ?></span></strong><br />
                        <strong><span id="order_billing_company"><?php echo $order->billing['company']; ?></span></strong><br />
                        <span id="order_billing_street_address"><?php echo $order->billing['street_address']; ?></span><br />
                        <?php if (isset($order->billing['suburb']) && $order->billing['suburb'] != '') echo '<span id="order_billing_suburb">' . $order->billing['suburb']; ?></span><br />
                        <span id="order_billing_city"><?php echo $order->billing['city'] . '</span>, <span id="order_billing_state">' . $order->billing['state'] . '</span> <span id="order_billing_postcode">' . $order->billing['postcode']; ?></span><br />
                        <span id="order_billing_country"><?php echo $order->billing['country']; ?></span><br />
                        Phone: <span id="order_billing_telephone"><?php echo $order->billing['telephone']; ?></span><br />
                        E-mail: <span id="order_billing_email_address"><?php echo $order->billing['email_address']; ?></span>
                      </address>
                    </div>
                    <div class="invoice-to">
                      <small><?php echo strtoupper(ADDRESS_HEADING_SHIPPING); ?></small>
                      <button type="button" class="btn btn-success btn-xs ml-2" data-toggle="modal" data-target="#editDeliveryModal">Edit</button>
                      <address class="m-t-5 m-b-5">
                        <strong><span id="order_delivery_name"><?php echo $order->delivery['name']; ?></span></strong><br />
                        <strong><span id="order_delivery_company"><?php echo $order->delivery['company']; ?></span></strong><br />
                        <span id="order_delivery_street_address"><?php echo $order->delivery['street_address']; ?></span><br />
                        <?php if (isset($order->delivery['suburb']) && $order->delivery['suburb'] != '') echo '<span id="order_delivery_suburb">' . $order->delivery['suburb']; ?></span><br />
                        <span id="order_delivery_city"><?php echo $order->delivery['city'] . '</span>, <span id="order_delivery_state">' . $order->delivery['state'] . '</span> <span id="order_delivery_postcode">' . $order->delivery['postcode']; ?></span><br />
                        <span id="order_delivery_country"><?php echo $order->delivery['country']; ?></span><br />
                        Phone: <span id="order_delivery_telephone"><?php echo $order->delivery['telephone']; ?></span><br />
                        E-mail: <span id="order_delivery_email_address"><?php echo $order->delivery['email_address']; ?></span><br>
						<a href="http://maps.google.com/maps?q=<?php echo $order->delivery['street_address'];?>,<?php echo $order->delivery['city']; ?>,<?php echo $order->delivery['state']; ?>,<?php echo $order->delivery['postcode'];?>,<?php echo $order->delivery['country']; ?>" target="new"><font color="red">google map</a></font></span>
                      </address>
                    </div>
                    <div class="invoice-date">
                      <small>ORDER INFORMAITON</small>
                      <div class="date m-t-5"><?php
                      $o_date = new DateTime($order->date_purchased);
                      echo $o_date->format('F d, Y'); ?>
                    </div>
                    <div class="invoice-detail mt-2">
                      Order Number: <span class="label label-inverse ml-1 f-s-20"><?php echo $oID; ?></span><br />
                    </div>

                    <div class="invoice-detail mt-3">
                      <?php echo ENTRY_PAYMENT_METHOD; ?><span class="label label-inverse ml-1 f-s-11"><?php echo $order->info['payment_method']; ?></span>
                    </div>

                   <?php if($order->info['transaction_id'] != '') {?>
                    <div class="invoice-detail mt-2">
                      <?php echo ENTRY_PAYMENT_TRANS_ID; ?><span class="label label-inverse ml-1 f-s-11"><?php echo $order->info['transaction_id']; ?></span>
                    </div>
                   <?php } ?>

                    <div class="invoice-detail mt-2">
                      <?php echo ENTRY_IPADDRESS; ?><span class="label label-inverse ml-1 f-s-11"><?php echo $order->customer['ipaddy']; ?></span>
                    </div>
                    <div class="invoice-detail mt-2">
                      <?php echo ENTRY_IPISP; ?><span class="label label-inverse ml-1 f-s-11"><?php echo $order->customer['ipisp']; ?></span>
                    </div>
                  </div>
                </div>

                <input type="hidden" id="update_customer_name" name="update_customer_name" value="<?php echo tep_html_quotes($order->customer['name']); ?>">
                <input type="hidden" id="update_customer_company" name="update_customer_company" value="<?php echo tep_html_quotes($order->customer['company']); ?>">
                <input type="hidden" id="update_customer_street_address" name="update_customer_street_address" value="<?php echo tep_html_quotes($order->customer['street_address']); ?>">
                <input type="hidden" id="update_customer_suburb" name="update_customer_suburb" value="<?php echo tep_html_quotes($order->customer['suburb']); ?>">
                <input type="hidden" id="update_customer_city" name="update_customer_city" value="<?php echo tep_html_quotes($order->customer['city']); ?>">
                <input type="hidden" id="update_customer_state" name="update_customer_state" value="<?php echo tep_html_quotes($order->customer['state']); ?>">
                <input type="hidden" id="update_customer_postcode" name="update_customer_postcode" value="<?php echo $order->customer['postcode']; ?>">
                <input type="hidden" id="update_customer_country" name="update_customer_country" value="<?php echo tep_html_quotes($order->customer['country']); ?>">
                <input type="hidden" id="update_customer_telephone" name="update_customer_telephone" value="<?php echo tep_html_quotes($order->customer['telephone']); ?>">
                <input type="hidden" id="update_customer_email_address" name="update_customer_email_address" value="<?php echo tep_html_quotes($order->customer['email_address']); ?>">

                <input type="hidden" id="update_billing_name" name="update_billing_name" value="<?php echo tep_html_quotes($order->billing['name']); ?>">
                <input type="hidden" id="update_billing_company" name="update_billing_company" value="<?php echo tep_html_quotes($order->billing['company']); ?>">
                <input type="hidden" id="update_billing_street_address" name="update_billing_street_address" value="<?php echo tep_html_quotes($order->billing['street_address']); ?>">
                <input type="hidden" id="update_billing_suburb" name="update_billing_suburb" value="<?php echo tep_html_quotes($order->billing['suburb']); ?>">
                <input type="hidden" id="update_billing_city" name="update_billing_city" value="<?php echo tep_html_quotes($order->billing['city']); ?>">
                <input type="hidden" id="update_billing_state" name="update_billing_state" value="<?php echo tep_html_quotes($order->billing['state']); ?>">
                <input type="hidden" id="update_billing_postcode" name="update_billing_postcode" value="<?php echo $order->billing['postcode']; ?>">
                <input type="hidden" id="update_billing_country" name="update_billing_country" value="<?php echo tep_html_quotes($order->billing['country']); ?>">
                <input type="hidden" id="update_billing_telephone" name="update_billing_telephone" value="<?php echo tep_html_quotes($order->billing['telephone']); ?>">
                <input type="hidden" id="update_billing_email_address" name="update_billing_email_address" value="<?php echo tep_html_quotes($order->billing['email_address']); ?>">

                <input type="hidden" id="update_delivery_name" name="update_delivery_name" value="<?php echo tep_html_quotes($order->delivery['name']); ?>">
                <input type="hidden" id="update_delivery_company" name="update_delivery_company" value="<?php echo tep_html_quotes($order->delivery['company']); ?>">
                <input type="hidden" id="update_delivery_street_address" name="update_delivery_street_address" value="<?php echo tep_html_quotes($order->delivery['street_address']); ?>">
                <input type="hidden" id="update_delivery_suburb" name="update_delivery_suburb" value="<?php echo tep_html_quotes($order->delivery['suburb']); ?>">
                <input type="hidden" id="update_delivery_city" name="update_delivery_city" value="<?php echo tep_html_quotes($order->delivery['city']); ?>">
                <input type="hidden" id="update_delivery_state" name="update_delivery_state" value="<?php echo tep_html_quotes($order->delivery['state']); ?>">
                <input type="hidden" id="update_delivery_postcode" name="update_delivery_postcode" value="<?php echo $order->delivery['postcode']; ?>">
                <input type="hidden" id="update_delivery_country" name="update_delivery_country" value="<?php echo tep_html_quotes($order->delivery['country']); ?>">
                <input type="hidden" id="update_delivery_telephone" name="update_delivery_telephone" value="<?php echo tep_html_quotes($order->delivery['telephone']); ?>">
                <input type="hidden" id="update_delivery_email_address" name="update_delivery_email_address" value="<?php echo tep_html_quotes($order->delivery['email_address']); ?>">

                <div class="invoice-content">
                  <div class="table-responsive">
                    <table id="products-table" class="table table-invoice">
                      <thead>
                        <tr>
                          <th scope="col" class="th-pcol dark text-left"><?php echo TABLE_HEADING_QUANTITY; ?></th>
                          <th scope="col" class="th-pcol dark text-left"><?php echo TABLE_HEADING_PRODUCT; ?></th>
                          <th scope="col" class="th-pcol dark text-left"><?php echo TABLE_HEADING_PRODUCTS_MODEL; ?></th>
                          <th scope="col" class="th-pcol dark text-right"><?php echo TABLE_HEADING_TAX; ?></th>
                          <th scope="col" class="th-pcol dark text-right"><?php echo TABLE_HEADING_BASE_PRICE; ?></th>
                          <th scope="col" class="th-pcol dark text-right"><?php echo TABLE_HEADING_UNIT_PRICE; ?></th>
                          <th scope="col" class="th-pcol dark text-right"><?php echo TABLE_HEADING_TOTAL_PRICE; ?></th>
                          <?php
                          if ( DISPLAY_PRICE_WITH_TAX == 'true'){
                            echo  '<th scope="col" class="th-pcol dark text-right">' . TABLE_HEADING_TOTAL_PRICE_TAXED . '</th>';
                          }
                          ?>
                          <!-- th scope="col" class="th-pcol dark text-right"><?php echo TABLE_HEADING_ACTION; ?></th -->
                        </tr>
                      </thead>
                      <tbody>
                        <!-- Begin Products Listings Block -->
                        <?php
                          // Override order.php Class's Field Limitations
                          $index = 0;
                          $order->products = array();
                          $orders_products_query = tep_db_query("select * from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . (int)$oID . "'");
                          while ($orders_products = tep_db_fetch_array($orders_products_query)) {
                            $order->products[$index] = array('qty' => $orders_products['products_quantity'],
                                                                'name' => str_replace("'", "&#39;", $orders_products['products_name']),
                                                                'model' => $orders_products['products_model'],
                                                                'tax' => $orders_products['products_tax'],
                                                                'price' => $orders_products['products_price'],
                                                                'final_price' => $orders_products['final_price'],
                                                                'orders_products_id' => $orders_products['orders_products_id']);

                            $subindex = 0;
                            $attributes_query_string = "select * from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_id = '" . (int)$oID . "' and orders_products_id = '" . (int)$orders_products['orders_products_id'] . "'";
                            $attributes_query = tep_db_query($attributes_query_string);

                            if (tep_db_num_rows($attributes_query)) {
                              while ($attributes = tep_db_fetch_array($attributes_query)) {
                                $order->products[$index]['attributes'][$subindex] = array('option' => $attributes['products_options'],
                                                                                         'option_id' => $attributes['products_options_id'],
                                                                                         'value' => $attributes['products_options_values'],
                                                                                         'value_id' => $attributes['products_options_values_id'],
                                                                                         'prefix' => $attributes['price_prefix'],
                                                                                         'price' => $attributes['options_values_price'],
                                                                                         'orders_products_attributes_id' => $attributes['orders_products_attributes_id']);
                                $subindex++;
                              }
                            }
                            $index++;
                          }

                          for ($i=0; $i<sizeof($order->products); $i++) {
                            $orders_products_id = $order->products[$i]['orders_products_id'];
                            echo '<tr id="row-' . $i . '" class="table-row dark">' . "\n" ;
                            if (ORDER_EDIT_EDT_PRICE == '1'){
                              echo '<td class="table-col dark text-right">' . "<input class='form-control' name='update_products[$orders_products_id][qty]' type='input' size='2' value='" . $order->products[$i]['qty'] . "'></td>\n" .
                                   '<td class="table-col dark text-left">' . "<input class='form-control' name='update_products[$orders_products_id][name]' type='input' size='25' value='" . $order->products[$i]['name'] . "'>";
                            } else {
                              echo '<td class="table-col dark text-right">' . "<input class='form-control' name='update_products[$orders_products_id][qty]' size='2' value='" . $order->products[$i]['qty'] . "'></td>\n" .
                                   '<td class="table-col dark text-left">' . $order->products[$i]['name'] . "<input class='form-control' name='update_products[$orders_products_id][name]' type='hidden' size='25' value='" . $order->products[$i]['name'] . "'>";
                            }
                            // Has Attributes?
                            if (isset($order->products[$i]['attributes'])){
                              if (sizeof($order->products[$i]['attributes']) > 0) {
                                for ($j=0; $j<sizeof($order->products[$i]['attributes']); $j++) {
                                  $orders_products_attributes_id = $order->products[$i]['attributes'][$j]['orders_products_attributes_id'];
                                  echo '<div class="mt-0 p-0"><small>&nbsp;<i> - ' . $order->products[$i]['attributes'][$j]['option'] . ' : ' . $order->products[$i]['attributes'][$j]['value'] . ' ' . $order->products[$i]['attributes'][$j]['prefix'] . ' ' . $currencies->format($order->products[$i]['attributes'][$j]['price']) ;
                                  echo '</i></small><input type="hidden" name="id[' . $orders_products_id . '][' . $order->products[$i]['attributes'][$j]['option_id'] . ']" value="' . $order->products[$i]['attributes'][$j]['value_id'] . '"></div>';
                                }
                              }
                            }
                            if (ORDER_EDIT_EDT_PRICE == '1'){
                              $edit_price = ('<td class="table-col dark text-right">' . "<input class='form-control text-right' name='update_products[$orders_products_id][final_price]' size='5' value='" . number_format($order->products[$i]['final_price'], 2, '.', '') . "'>" . '</td>');
                            } else {
                              $edit_price = ('<td class="table-col dark text-right">' . $currencies->format($order->products[$i]['final_price'], 1, $order->info['currency'], $order->info['currency_value']) . "<input name='update_products[$orders_products_id][final_price]' type='hidden' size='5' value='" . number_format($order->products[$i]['final_price'], 2, '.', '') . "'>" . '</td>' );
                            }
                            echo '</td>' . "\n" .
                                 '<td class="table-col dark text-left">' . $order->products[$i]['model'] . "<input class='form-control' name='update_products[$orders_products_id][model]' type='hidden' size='12' value='" . $order->products[$i]['model'] . "'>" . '</td>' . "\n" .
                                 '<td class="table-col dark text-left" valign="top">' . "<input class='form-control text-right' name='update_products[$orders_products_id][tax]' size='3' value='" . tep_display_tax_value($order->products[$i]['tax']) . "'>" . '</td>' . "\n" .
                                 '<td class="table-col dark text-right">' . $currencies->format($order->products[$i]['price'], 1, $order->info['currency'], $order->info['currency_value']). "<input name='update_products[$orders_products_id][price]' type='hidden' size='5' value='" . number_format($order->products[$i]['price'], 2, '.', '') . "'>" . '</td>' . "\n" .
                                 $edit_price . "\n" .
                                 '<td class="table-col dark text-right">' . $currencies->format($order->products[$i]['final_price'] * $order->products[$i]['qty'], 1, $order->info['currency'], $order->info['currency_value']) . '</td>' . "\n" ;
                            if ( DISPLAY_PRICE_WITH_TAX == 'true'){
                              echo '<td class="table-col dark text-right"><b>' . $currencies->format(tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], 1, $order->info['currency'], $order->info['currency_value']) . '</b></td>' . "\n";
                            }
                            //echo '<td class="table-col dark text-right"><span onclick="$(\'#row-' . $i . '\').remove();" class="fa fa-times fa-2x text-danger"></span></td>';
                            echo '</tr>' . "\n";
                          }
                        ?>
                        <!-- End Products Listings Block -->
                      </tbody>
                    </table>
                    <div class="pull-right mb-3">
                      <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#addProductModal">Add Product</button>
                    </div>

                  </div>
                  <div class="row">
                    <div class="col-6">
                      <!-- Begin Payment Block -->
                      <?php
                      if (stristr($order->info['payment_method'], 'paypal')) {
                        include(DIR_FS_CATALOG_MODULES . 'payment/paypal/admin/TransactionSummaryLogs.inc.php');
                      }
                      if (strtolower($order->info['payment_method']) == 'ignore') {
                      } else {
                        //list exsisting payment if not in current order_pay_methods table
                        $orders_pay_methodA[] = array('id'   => $order->info['payment_method'], 'text' => $order->info['payment_method']);
                        $orders_pay_method1 = array_merge($orders_pay_methodA, $orders_pay_method);
                        ?>
                        <div class="form-inline m-t-20">
                          <label class="form-label m-r-10 m-l-10 main-text"><?php echo ENTRY_PAYMENT_METHOD; ?></label>
                          <div class="m-r-10">
                            <?php echo tep_draw_pull_down_menu('update_info_payment_method', $orders_pay_method1, $order->info['payment_method'], 'class="form-control"'); ?>
                          </div>
                          <!-- button type="submit" class="btn btn-sm btn-success m-r-5"><?php echo IMAGE_UPDATE; ?></button -->
                        </div>
                        <?php
                        if ((isset($order->info['account_name']) && $order->info['account_name']) ||
                          (isset($order->info['account_number']) && $order->info['account_number']) ||
                          (isset($order->info['payment_method']) && ($order->info['payment_method']) == "Purchase Order") ||
                          (isset($order->info['po_number']) && $order->info['po_number'])) {
                          ?>
                          <div class="form-inline m-t-10 m-l-10">
                            <div class="form-group">
                              <label class="form-label mr-2 main-text"><?php echo ENTRY_PO_NAME ?></label>
                              <input type="text" class="form-control" name="account_name" value='<?php echo (isset($order->info['account_name']) ? $order->info['account_name'] : ''); ?>'>
                            </div>
                            <div class="form-group mt-1">
                              <label class="form-label mr-2 main-text"><?php echo ENTRY_PO_ACCT ?></label>
                              <input type="text" class="form-control" name="account_number" value='<?php echo (isset($order->info['account_number']) ? $order->info['account_number'] : ''); ?>'>
                            </div>
                            <div class="form-group mt-1">
                              <label class="form-label mr-2 main-text"><?php echo ENTRY_PO_NUMBER ?></label>
                              <input type="text" class="form-control" name="po_number" value='<?php echo (isset($order->info['po_number']) ? $order->info['po_number'] : ''); ?>'>
                            </div>
                          </div>
                          <?php
                        }
                      }
                      // RCI edit orders payment data handling
                      echo $cre_RCI->get('editorders', 'paymentdata');
                      ?>
                      <!-- End Payment Block -->
                    </div>
                    <div class="col-6 invoice-totals-right">

                    <?php
                      // Override order.php Class's Field Limitations
                      $totals_query = tep_db_query("select * from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . (int)$oID . "' order by sort_order");
                      $order->totals = array();
                      while ($totals = tep_db_fetch_array($totals_query)) {
                        $order->totals[] = array('title' => $totals['title'], 'text' => $totals['text'], 'class' => $totals['class'], 'value' => $totals['value'], 'orders_total_id' => $totals['orders_total_id']);
                      }

                      $TotalsArray = array();
                      for ($i=0; $i<sizeof($order->totals); $i++) {
                        $TotalsArray[] = array("Name" => (defined(strtoupper($order->totals[$i]['title']))?constant(strtoupper($order->totals[$i]['title'])):$order->totals[$i]['title']), "Price" => number_format($order->totals[$i]['value'], 2, '.', ''), "Class" => $order->totals[$i]['class'], "TotalID" => $order->totals[$i]['orders_total_id']);
                        $TotalsArray[] = array("Name" => "          ", "Price" => "", "Class" => "ot_custom", "TotalID" => "0");
                      }
                      array_pop($TotalsArray);

                      $output = '<div class="invoice-price"><div class="invoice-price-right">';
                      foreach($TotalsArray as $TotalIndex => $TotalDetails) {
                        if($TotalDetails["Class"] == "ot_subtotal") {
                          $output .= '<div class="p-relative main-text"><small>' . strtoupper($TotalDetails["Name"]) . '</small><span class="ot-price">' . $TotalDetails["Price"] . '</span>' .
                                     '<input name="update_totals[' . $TotalIndex . '][title]" type="hidden" value="' . trim($TotalDetails['Name']) . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][value]" type="hidden" value="' . $TotalDetails['Price'] . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][class]" type="hidden" value="' . $TotalDetails['Class'] . '" />' . "\n" .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '"></div>';
                        } elseif($TotalDetails["Class"] == "ot_total") {
                          $output .= '<div class="hr mt-3 mb-2"></div>';
                          $output .= '<div class="p-relative main-text"><small>' . strtoupper($TotalDetails["Name"]) . '</small>' . $TotalDetails["Price"] .
                                     '<input name="update_totals[' . $TotalIndex . '][title]" type="hidden" value="' . trim($TotalDetails['Name']) . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][value]" type="hidden" value="' . $TotalDetails['Price'] . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][class]" type="hidden" value="' . $TotalDetails['Class'] . '" />' . "\n" .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '"></div>';
                        } elseif($TotalDetails["Class"] == "ot_customer_discount") {
                          $output .= '<div class="p-relative main-text clearfix"><small>' . strtoupper(ENTRY_DISCOUNT) . '</small>
                                      <div><table class="float-right"><tr><td class="clearfix"><input class="form-control w-50 pull-right text-right" style="height:38px; font-size:16px;" name="update_totals[' . $TotalIndex . '][value]" value="' . $TotalDetails['Price'] . '">' .
                                     '<input name="update_totals[' . $TotalIndex . '][title]" type="hidden" value="' . trim($TotalDetails['Name']) . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][class]" type="hidden" value="' . $TotalDetails['Class'] . '" />' . "\n" .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '"></td></tr></table></div></div>';
                        } elseif(($TotalDetails["Class"] == "ot_gv") || ($TotalDetails["Class"] == "ot_coupon")) {
                          $output .= '<div class="p-relative main-text clearfix"><small>' . strtoupper(ENTRY_CUSTOMER_GV) . '</small>
                                      <div><table class="float-right"><tr><td class="clearfix"><input class="form-control w-50 pull-right text-right" style="height:38px; font-size:16px;" name="update_totals[' . $TotalIndex . '][value]" value="' . $TotalDetails['Price'] . '">' .
                                     '<input name="update_totals[' . $TotalIndex . '][title]" type="hidden" value="' . trim($TotalDetails['Name']) . '" />' .
                                     '<input name="update_totals[' . $TotalIndex . '][class]" type="hidden" value="' . $TotalDetails['Class'] . '" />' . "\n" .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '"></td></tr></table></div></div>';
                        } elseif($TotalDetails["Class"] == "ot_tax" || $TotalDetails["Class"] == "ot_buysafe") {
                           $output .= '<div class="p-relative main-text"><small>' . strtoupper($TotalDetails["Name"]) . '</small><span class="ot-price">' . $TotalDetails["Price"] . '</span>' .
                                      '<input name="update_totals[' . $TotalIndex . '][title]" type="hidden" value="' . trim($TotalDetails['Name']) . '" />' .
                                      '<input name="update_totals[' . $TotalIndex . '][value]" type="hidden" value="' . $TotalDetails['Price'] . '" size="6" />' .
                                      '<input name="update_totals[' . $TotalIndex . '][class]" type="hidden" value="' . $TotalDetails['Class'] . '" />' . "\n" .
                                      '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '" /></div>';
                        } elseif($TotalDetails["Class"] == "ot_shipping") {
                          //list exsisting shipping if not in current order_ship_meahtods table
                          $orders_ship_methodA[] = array('id'   => $TotalDetails["Name"],
                                                         'text' => $TotalDetails["Name"]);

                          //  $orders_ship_method1 = array_merge($orders_ship_method, $orders_ship_methodA) ;
                          // check to see if method in totals  is in same as in order_ship_meahtods table
                          // if 0 merge if 1 dont merge

                          $orders_ship_method1 = array_merge($orders_ship_methodA, $orders_ship_method) ;

                          $output .= '<div class="p-relative main-text clearfix"><small>' . strtoupper(HEADING_SHIPPING) . '</small>
                                      <div><table class="float-right" style="width:60%;"><tr><td class="">' . tep_draw_pull_down_menu('update_totals[' . $TotalIndex . '][title]', $orders_ship_method1, $TotalDetails["Name"], 'class="form-control"') . '</td>
                                      <td style="width:40%;"><input class="form-control text-right" style="height:38px; font-size:16px;" name="update_totals[' . $TotalIndex . '][value]" value="' . $TotalDetails['Price'] . '" />' .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][class]" value="' . $TotalDetails['Class'] . '" />' .
                                     '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '" /></td>
                                      </tr></table></div></div>';
                        } else {
                            $output .= '<div class="p-relative main-text"><small>' . strtoupper($TotalDetails["Name"]) . '</small><span class="ot-price">' . $TotalDetails["Price"] . '</span>' .
                                  '<input type="hidden" name="update_totals[' . $TotalIndex . '][value]" value="' . $TotalDetails['Price'] . '" />' .
                                  '<input type="hidden" name="update_totals[' . $TotalIndex . '][title]" value="' . trim($TotalDetails['Name']) . '" />' .
                                  '<input type="hidden" name="update_totals[' . $TotalIndex . '][class]" value="' . $TotalDetails['Class'] . '" />' .
                                  '<input type="hidden" name="update_totals[' . $TotalIndex . '][total_id]" value="' . $TotalDetails['TotalID'] . '" /></div>';
                        }
                      }
                      $output .= '</div></div>';
                      echo $output;
                      ?>
                    </div>
                  </div>
                </div>

                <!-- comments/status -->
                <table class="table table-order-comments w-100 mt-2">
                  <thead>
                    <tr class="th-row">
                      <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_DATE_ADDED; ?></th>
                      <th scope="col" class="th-col dark text-center"><?php echo TABLE_HEADING_CUSTOMER_NOTIFIED; ?></th>
                      <th scope="col" class="th-col dark text-center"><?php echo TABLE_HEADING_STATUS; ?></th>
                      <th scope="col" class="th-col dark text-left"><?php echo TABLE_HEADING_COMMENTS; ?></th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php
                    $orders_status_query = tep_db_query("select orders_status from " . TABLE_ORDERS . " where orders_id = '" . tep_db_input($oID) . "'");
                    while ($orders_status_1 = tep_db_fetch_array($orders_status_query)) {
                      $orders_status_test = $orders_status_1['orders_status'];
                    }
                    $orders_history_query = tep_db_query("select * from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id = '" . tep_db_input($oID) . "' order by date_added");

                    if (tep_db_num_rows($orders_history_query)) {
                      while ($orders_history = tep_db_fetch_array($orders_history_query)) {
                        echo '<tr class="table-row">' . "\n" .
                             '  <td class="table-col">' . tep_datetime_short($orders_history['date_added']) . '</td>' . "\n" .
                             '  <td class="table-col text-center">';
                        if ($orders_history['customer_notified'] == '1') {
                          echo '<span class="fa fa-check fa-2x text-success"></span>';
                        } else {
                          echo '<span class="fa fa-times fa-2x text-danger"></span>';
                        }
                        $order_status = '';
                        if (isset($orders_status_array[$orders_history['orders_status_id']])){
                          $order_status = $orders_status_array[$orders_history['orders_status_id']];
                         }
                        echo '  <td class="table-col text-center">' . $order_status . '</td>' . "\n";
                        echo '  <td class="table-col" width="300">' . nl2br(htmlspecialchars_decode(tep_db_output($orders_history['comments']),ENT_NOQUOTES)) . '&nbsp;</td>' . "\n";
                        echo '</tr>' . "\n";
                      }
                    } else {
                        echo '<tr>' . "\n" .
                             '  <td class="table-col" colspan="4">' . TEXT_NO_ORDER_HISTORY . '</td>' . "\n" .
                             '</tr>' . "\n";
                    }
                    ?>
                  </tbody>
                </table>

                <div class="row">
                  <div class="col-6">
                    <div class="form-group">
                      <label class="main-text"><?php echo TABLE_HEADING_COMMENTS; ?></label>
                      <?php echo tep_draw_textarea_field('comments', 'soft', '60', '5', null, 'class="form-control"'); ?>
                    </div>
                    <div class="pull-right">
                      <button type="button" onclick="submitOrder('stay');" class="btn btn-primary m-r-3 btn-save-stay"><i class="fa fa-plus-square"></i> <?php echo IMAGE_UPDATE; ?></button>
                    </div>
                  </div>

                  <div class="col-6">
                    <div class="form-group">
                      <label class="main-text"><?php echo ENTRY_STATUS; ?></label>
                      <?php echo tep_draw_pull_down_menu('status', $orders_statuses, $order->info['orders_status_number'], 'onchange="javascript:show_tracking(this.value);" class="form-control"'); ?>
                    </div>
                    <?php
                    	$trackingorderDiv = 'display:none;';
                    	if($order->info['orders_status_number'] == 3){
                    		$trackingorderDiv = '';
                    	}
                    ?>
                    <div id="tracking_section" style="width:100%;padding-bottom:10px;<?php echo $trackingorderDiv; ?>">
                        <label class="main-text"><?php  echo TRACKING_TYPE; ?>&nbsp;</label>
                        <select name="shipping_type" id="tracking_type" class="form-control" style="width:23%;display: inline-block;">
                        	<option value="">--Select--</option>
                        	<option value="ups" <?php echo (($order->info['shipment_method'] == 'ups') ? 'selected':''); ?> >UPS</option>
                        	<option value="usps" <?php echo (($order->info['shipment_method'] == 'usps') ? 'selected':''); ?> >USPS</option>
                        	<option value="fedex" <?php echo (($order->info['shipment_method'] == 'fedex') ? 'selected':''); ?> >FEDEX</option>
                        </select> &nbsp;&nbsp;
						<label class="main-text"><?php  echo TRACKING_NUMBER; ?></label>
						<input type="text" name="tracking_nr" id="tracking_nr" value="<?php echo $order->info['shipment_track_num']; ?>" class="form-control" style="width:52%;display:inline-block;">
				    </div>
                    <div class="form-check">
                      <?php echo tep_draw_checkbox_field('notify', '', 0, null, 'class="form-check-input js-switch"'); ?>
                      <label class="form-check-label main-text ml-1" for="notify"><?php echo ENTRY_NOTIFY_CUSTOMER; ?></label>
                    </div>
                    <div class="form-check mt-2">
                      <?php echo tep_draw_checkbox_field('notify_comments', '', 0, null, 'class="form-check-input js-switch"'); ?>
                      <label class="form-check-label main-text ml-1" for="notify_comments"><?php echo ENTRY_NOTIFY_COMMENTS; ?></label>
                    </div>
                  </div>
                </div>
                <?php
                // RCI edit orders below comments
                echo $cre_RCI->get('editorders', 'belowcomments');
                ?>
                <!-- comments/status end -->
              </div>
              <!-- end invoice -->
              <?php
              echo '</form>';
            }
            ?>
          </div>
        </div>
      </div>

      <!-- add product modal -->
      <div class="modal fade" id="addProductModal" tabindex="-1" role="dialog" aria-labelledby="addProductModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title f-s-14" id="addProductModalLabel"><?php echo ADDING_TITLE; ?> #<?php echo $oID; ?></h4>
              <button type="button" class="close modal-close-fix" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form role="form" name="add_product" id="add_product" method="post">
                <div class="form-group">
                  <label for="add_product_categories_id"><?php echo TEXT_SELECT_CAT; ?></label>
                  <?php echo tep_draw_pull_down_menu('add_product_categories_id', tep_get_category_tree('0'), '', 'onchange="setCategoryFilter(this);" class="form-control"'); ?>
                </div>

                <div class="form-group">
                  <label for="add_product_categories_id"><?php echo TEXT_SELECT_PROD; ?></label>
                  <?php echo tep_draw_pull_down_menu('add_product_products_id', Products::getAll(), '', 'onchange="getAttributes();" id="add_product_products_id" class="form-control"'); ?>
                </div>

                <div id="attributes"></div>
                <script> $(document).ready(function(){ getAttributes() }); </script>

                <div class="form-group">
                  <label for="add_product_quantity"><?php echo ENTRY_QUANTITY; ?></label>
                  <?php echo tep_draw_input_field('add_product_quantity', '1', 'id="add_product_quantity" class="form-control"'); ?>
                </div>
                <input type="hidden" name="oID" value="<?php echo $oID; ?>">
                <input type="hidden" name="step" value="5">
                <input type="hidden" name="products_name_step" value="">
                <input type="hidden" name="add_products_price" value="">

              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              <button type="button" onclick="addProduct();" class="btn btn-primary">Add Product</button>
            </div>
          </div>
        </div>
      </div>

      <!-- edit customer modal -->
      <div class="modal fade" id="editCustomerModal" tabindex="-1" role="dialog" aria-labelledby="editCustomerModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title f-s-14" id="editCustomerModalLabel">Edit Customer Info</h4>
              <button type="button" class="close modal-close-fix" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form role="form" name="edit_customer" id="edit_customer">

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_NAME; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_name' id='customer_name' class="form-control" value='<?php echo tep_html_quotes($order->customer['name']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COMPANY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_company' id='customer_company' class="form-control" value='<?php echo tep_html_quotes($order->customer['company']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CUSTOMER_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_street_address' id='customer_street_address' class="form-control" value='<?php echo tep_html_quotes($order->customer['street_address']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_SUBURB; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_suburb' id='customer_suburb' class="form-control" value='<?php echo tep_html_quotes($order->customer['suburb']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CITY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_city' id='customer_city' class="form-control" value='<?php echo tep_html_quotes($order->customer['city']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_STATE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_state' id='customer_state' class="form-control" value='<?php echo tep_html_quotes($order->customer['state']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_POST_CODE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_postcode' id='customer_postcode' class="form-control" value='<?php echo tep_html_quotes($order->customer['postcode']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COUNTRY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_country' id='customer_country' class="form-control" value='<?php echo tep_html_quotes($order->customer['country']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_TELEPHONE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_telephone' id='customer_telephone' class="form-control" value='<?php echo tep_html_quotes($order->customer['telephone']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_EMAIL_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='customer_email_address' id='customer_email_address' class="form-control" value='<?php echo tep_html_quotes($order->customer['email_address']); ?>' required>
                  </div>
                </div>

                <div class="d-sm-inline float-right mt-3 pr-1">
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Billing?'; ?></label><input type="checkbox" id="copyto_billing" name="copyto_billing" class="js-switch js-copyto-billing"></div>
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Shipping?'; ?></label><input type="checkbox" id="copyto_delivery" name="copyto_delivery" class="js-switch js-copyto-delivery"></div>
                </div>

              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              <button type="button" onclick="updateCustomerInfo();" class="btn btn-primary">Update</button>
            </div>
          </div>
        </div>
      </div>

      <!-- edit billing modal -->
      <div class="modal fade" id="editBillingModal" tabindex="-1" role="dialog" aria-labelledby="editBillingModalModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title f-s-14" id="editBillingModalModalLabel">Edit Billing Info</h4>
              <button type="button" class="close modal-close-fix" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form role="form" name="edit_billing" id="edit_billing">

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_NAME; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_name' id='billing_name' class="form-control" value='<?php echo tep_html_quotes($order->billing['name']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COMPANY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_company' id='billing_company' class="form-control" value='<?php echo tep_html_quotes($order->billing['company']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CUSTOMER_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_street_address' id='billing_street_address' class="form-control" value='<?php echo tep_html_quotes($order->billing['street_address']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_SUBURB; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_suburb' id='billing_suburb' class="form-control" value='<?php echo tep_html_quotes($order->billing['suburb']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CITY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_city' id='billing_city' class="form-control" value='<?php echo tep_html_quotes($order->billing['city']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_STATE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_state' id='billing_state' class="form-control" value='<?php echo tep_html_quotes($order->billing['state']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_POST_CODE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_postcode' id='billing_postcode' class="form-control" value='<?php echo tep_html_quotes($order->billing['postcode']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COUNTRY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_country' id='billing_country' class="form-control" value='<?php echo tep_html_quotes($order->billing['country']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_TELEPHONE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_telephone' id='billing_telephone' class="form-control" value='<?php echo tep_html_quotes($order->billing['telephone']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_EMAIL_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='billing_email_address' id='billing_email_address' class="form-control" value='<?php echo tep_html_quotes($order->billing['email_address']); ?>' required>
                  </div>
                </div>

                <div class="d-sm-inline float-right mt-3 pr-1">
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Customer?'; ?></label><input type="checkbox" id="copyto_customer" name="copyto_customer" class="js-switch js-copy_billing_to-customer"></div>
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Shipping?'; ?></label><input type="checkbox" id="copyto_delivery" name="copyto_delivery" class="js-switch js-copy_billing_to-delivery"></div>
                </div>

              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              <button type="button" onclick="updateBillingInfo();" class="btn btn-primary">Update</button>
            </div>
          </div>
        </div>
      </div>

      <!-- edit delivery modal -->
      <div class="modal fade" id="editDeliveryModal" tabindex="-1" role="dialog" aria-labelledby="editDeliveryModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title f-s-14" id="editDeliveryModalLabel">Edit Delivery Info</h4>
              <button type="button" class="close modal-close-fix" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form role="form" name="edit_delivery" id="edit_delivery">

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_NAME; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_name' id='delivery_name' class="form-control" value='<?php echo tep_html_quotes($order->delivery['name']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COMPANY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_company' id='delivery_company' class="form-control" value='<?php echo tep_html_quotes($order->delivery['company']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CUSTOMER_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_street_address' id='delivery_street_address' class="form-control" value='<?php echo tep_html_quotes($order->delivery['street_address']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_SUBURB; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_suburb' id='delivery_suburb' class="form-control" value='<?php echo tep_html_quotes($order->delivery['suburb']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_CITY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_city' id='delivery_city' class="form-control" value='<?php echo tep_html_quotes($order->delivery['city']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_STATE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_state' id='delivery_state' class="form-control" value='<?php echo tep_html_quotes($order->delivery['state']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_POST_CODE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_postcode' id='delivery_postcode' class="form-control" value='<?php echo tep_html_quotes($order->delivery['postcode']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_COUNTRY; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_country' id='delivery_country' class="form-control" value='<?php echo tep_html_quotes($order->delivery['country']); ?>' required>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_TELEPHONE; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_telephone' id='delivery_telephone' class="form-control" value='<?php echo tep_html_quotes($order->delivery['telephone']); ?>'>
                  </div>
                </div>

                <div class="form-group row mb-3">
                  <label class="col-3 control-label main-text mt-1"><?php echo ENTRY_EMAIL_ADDRESS; ?></label>
                  <div class="col-9 meta-input">
                    <input name='delivery_email_address' id='delivery_email_address' class="form-control" value='<?php echo tep_html_quotes($order->delivery['email_address']); ?>' required>
                  </div>
                </div>

                <div class="d-sm-inline float-right mt-3 pr-1">
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Customer?'; ?></label><input type="checkbox" id="copyto_customer" name="copyto_customer" class="js-switch js-copy_delivery_to-customer"></div>
                  <div class="col d-sm-inline p-0"><label class="control-label ml-3 mr-2 main-text"><?php echo 'Copy to Billing?'; ?></label><input type="checkbox" id="copyto_billing" name="copyto_billing" class="js-switch js-copy_delivery_to-billing"></div>

                </div>

              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              <button type="button" onclick="updateDeliveryInfo();" class="btn btn-primary">Update</button>
            </div>
          </div>
        </div>
      </div>

      <!-- end body_text //-->
    </div>
    <!-- end panel -->
  </div>
</div>
<script>
$(document).ready(function(){
  //  instantiate checkbox switches
  var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  elems.forEach(function(html) {
    var switchery = new Switchery(html, { size: 'small',
                                          color: '#ff4044',
                                          secondaryColor: '#a8acb1' });
  });

});

function show_tracking(sid){
	if(sid == 3) {
	  $('#tracking_section').show(500);
    }else{
		$('#tracking_section').hide(500);
	}
}
function getAttributes() {
  var pid = $('#add_product_products_id').val();
  if (pid == undefined || pid == '') return;

  var rpcUrl = "./rpc.php?action=getProductInfo&pid=PID";

  $.get( rpcUrl.replace('PID', pid), function( data ) {
    $('#attributes').html('');
    var html = ''
    $.each(data.products_attributes, function(i, v) {
      html += '<div class="form-group"><label for="' + v.label + '">' + v.label + '</label>' + v.html + '</div>';
    });
    $('#attributes').html(html);
  });

}

function addProduct() {
  var action = '<?php echo tep_href_link(FILENAME_EDIT_ORDERS, "oID=" . $oID . "&action=add_product"); ?>';
  $('#add_product').attr('action', action);
  $('#add_product').submit();
  $('#addProductModal').modal('hide');
}

function setCategoryFilter(e) {
  var cid = e.value;
  var rpcUrl = "./rpc.php?action=getProductsInCategory&cid=CID";
  var options = '';
  $.get( rpcUrl.replace('CID', cid), function( data ) {
    $.each(data, function(i, v) {
        options += '<option value="' + v.id + '">' + v.text  + '</option>';
    });
    $('#attributes').html('');
    $('#add_product_products_id').html(options);
    getAttributes();
  });
}

function updateCustomerInfo() {

  var copyto_billing = document.querySelector('.js-copyto-billing');
  var copyto_delivery = document.querySelector('.js-copyto-delivery');


  var cname = $('#customer_name').val();
  $('#update_customer_name').val(cname);
  $('#order_customer_name').html(cname);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_name').val(cname);
    $('#order_billing_name').html(cname);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_name').val(cname);
    $('#order_delivery_name').html(cname);
  }

  var company = $('#customer_company').val();
  $('#update_customer_company').val(company);
  $('#order_customer_company').html(company);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_company').val(company);
    $('#order_billing_company').html(company);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_company').val(company);
    $('#order_delivery_company').html(company);
  }

  var street_address = $('#customer_street_address').val();
  $('#update_customer_street_address').val(street_address);
  $('#order_customer_street_address').html(street_address);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_street_address').val(street_address);
    $('#order_billing_street_address').html(street_address);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_street_address').val(street_address);
    $('#order_delivery_street_address').html(street_address);
  }

  var suburb = $('#customer_suburb').val();
  $('#update_customer_suburb').val(suburb);
  $('#order_customer_suburb').html(suburb);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_suburb').val(suburb);
    $('#order_billing_suburb').html(suburb);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_suburb').val(suburb);
    $('#order_delivery_suburb').html(suburb);
  }

  var city = $('#customer_city').val();
  $('#update_customer_city').val(city);
  $('#order_customer_city').html(city);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_city').val(city);
    $('#order_billing_city').html(city);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_city').val(city);
    $('#order_delivery_city').html(city);
  }

  var state = $('#customer_state').val();
  $('#update_customer_state').val(state);
  $('#order_customer_state').html(state);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_state').val(state);
    $('#order_billing_state').html(state);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_state').val(state);
    $('#order_delivery_state').html(state);
  }

  var postcode = $('#customer_postcode').val();
  $('#update_customer_postcode').val(postcode);
  $('#order_customer_postcode').html(postcode);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_postcode').val(postcode);
    $('#order_billing_postcode').html(postcode);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_postcode').val(postcode);
    $('#order_delivery_postcode').html(postcode);
  }

  var country = $('#customer_country').val();
  $('#update_customer_country').val(country);
  $('#order_customer_country').html(country);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_country').val(country);
    $('#order_billing_country').html(country);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_country').val(country);
    $('#order_delivery_country').html(country);
  }

  var telephone = $('#customer_telephone').val();
  $('#update_customer_telephone').val(telephone);
  $('#order_customer_telephone').html(telephone);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_telephone').val(telephone);
    $('#order_billing_telephone').html(telephone);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_telephone').val(telephone);
    $('#order_delivery_telephone').html(telephone);
  }

  var email_address = $('#customer_email_address').val();
  $('#update_customer_email_address').val(email_address);
  $('#order_customer_email_address').html(email_address);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_email_address').val(email_address);
    $('#order_billing_email_address').html(email_address);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_email_address').val(email_address);
    $('#order_delivery_email_address').html(email_address);
  }

  // close the modal
  $('#editCustomerModal').modal('hide');
}

function updateBillingInfo() {

  var copyto_customer = document.querySelector('.js-copy_billing_to-customer');
  var copyto_delivery = document.querySelector('.js-copy_billing_to-delivery');

  var cname = $('#billing_name').val();
  $('#update_billing_name').val(cname);
  $('#order_billing_name').html(cname);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_name').val(cname);
    $('#order_customer_name').html(cname);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_name').val(cname);
    $('#order_delivery_name').html(cname);
  }

  var company = $('#billing_company').val();
  $('#update_billing_company').val(company);
  $('#order_billing_company').html(company);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_company').val(company);
    $('#order_customer_company').html(company);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_company').val(company);
    $('#order_delivery_company').html(company);
  }

  var street_address = $('#billing_street_address').val();
  $('#update_billing_street_address').val(street_address);
  $('#order_billing_street_address').html(street_address);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_street_address').val(street_address);
    $('#order_customer_street_address').html(street_address);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_street_address').val(street_address);
    $('#order_delivery_street_address').html(street_address);
  }

  var suburb = $('#billing_suburb').val();
  $('#update_billing_suburb').val(suburb);
  $('#order_billing_suburb').html(suburb);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_suburb').val(suburb);
    $('#order_customer_suburb').html(suburb);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_suburb').val(suburb);
    $('#order_delivery_suburb').html(suburb);
  }

  var city = $('#billing_city').val();
  $('#update_billing_city').val(city);
  $('#order_billing_city').html(city);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_city').val(city);
    $('#order_customer_city').html(city);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_city').val(city);
    $('#order_delivery_city').html(city);
  }

  var state = $('#billing_state').val();
  $('#update_billing_state').val(state);
  $('#order_billing_state').html(state);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_state').val(state);
    $('#order_customer_state').html(state);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_state').val(state);
    $('#order_delivery_state').html(state);
  }

  var postcode = $('#billing_postcode').val();
  $('#update_billing_postcode').val(postcode);
  $('#order_billing_postcode').html(postcode);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_postcode').val(postcode);
    $('#order_customer_postcode').html(postcode);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_postcode').val(postcode);
    $('#order_delivery_postcode').html(postcode);
  }

  var country = $('#billing_country').val();
  $('#update_billing_country').val(country);
  $('#order_billing_country').html(country);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_country').val(country);
    $('#order_customer_country').html(country);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_country').val(country);
    $('#order_delivery_country').html(country);
  }

  var telephone = $('#billing_telephone').val();
  $('#update_billing_telephone').val(telephone);
  $('#order_billing_telephone').html(telephone);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_telephone').val(telephone);
    $('#order_customer_telephone').html(telephone);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_telephone').val(telephone);
    $('#order_delivery_telephone').html(telephone);
  }

  var email_address = $('#billing_email_address').val();
  $('#update_billing_email_address').val(email_address);
  $('#order_billing_email_address').html(email_address);
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_email_address').val(email_address);
    $('#order_customer_email_address').html(email_address);
  }
  if (copyto_delivery && copyto_delivery.checked) {
    $('#update_delivery_email_address').val(email_address);
    $('#order_delivery_email_address').html(email_address);
  }

  // close the modal
  $('#editBillingModal').modal('hide');
}

function updateDeliveryInfo() {

  var copyto_billing = document.querySelector('.js-copy_delivery_to-billing');
  var copyto_customer = document.querySelector('.js-copy_delivery_to-customer');

  var cname = $('#delivery_name').val();
  $('#update_delivery_name').val(cname);
  $('#order_delivery_name').html(cname);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_name').val(cname);
    $('#order_billing_name').html(cname);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_name').val(cname);
    $('#order_customer_name').html(cname);
  }

  var company = $('#delivery_company').val();
  $('#update_delivery_company').val(company);
  $('#order_delivery_company').html(company);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_company').val(company);
    $('#order_billing_company').html(company);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_company').val(company);
    $('#order_customer_company').html(company);
  }

  var street_address = $('#delivery_street_address').val();
  $('#update_delivery_street_address').val(street_address);
  $('#order_delivery_street_address').html(street_address);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_street_address').val(street_address);
    $('#order_billing_street_address').html(street_address);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_street_address').val(street_address);
    $('#order_customer_street_address').html(street_address);
  }

  var suburb = $('#delivery_suburb').val();
  $('#update_delivery_suburb').val(suburb);
  $('#order_delivery_suburb').html(suburb);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_suburb').val(suburb);
    $('#order_billing_suburb').html(suburb);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_suburb').val(suburb);
    $('#order_customer_suburb').html(suburb);
  }

  var city = $('#delivery_city').val();
  $('#update_delivery_city').val(city);
  $('#order_delivery_city').html(city);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_city').val(city);
    $('#order_billing_city').html(city);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_city').val(city);
    $('#order_customer_city').html(city);
  }

  var state = $('#delivery_state').val();
  $('#update_delivery_state').val(state);
  $('#order_delivery_state').html(state);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_state').val(state);
    $('#order_billing_state').html(state);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_state').val(state);
    $('#order_customer_state').html(state);
  }

  var postcode = $('#delivery_postcode').val();
  $('#update_delivery_postcode').val(postcode);
  $('#order_delivery_postcode').html(postcode);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_postcode').val(postcode);
    $('#order_billing_postcode').html(postcode);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_postcode').val(postcode);
    $('#order_customer_postcode').html(postcode);
  }

  var country = $('#delivery_country').val();
  $('#update_delivery_country').val(country);
  $('#order_delivery_country').html(country);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_country').val(country);
    $('#order_billing_country').html(country);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_country').val(country);
    $('#order_customer_country').html(country);
  }

  var telephone = $('#delivery_telephone').val();
  $('#update_delivery_telephone').val(telephone);
  $('#order_delivery_telephone').html(telephone);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_telephone').val(telephone);
    $('#order_billing_telephone').html(telephone);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_telephone').val(telephone);
    $('#order_customer_telephone').html(telephone);
  }

  var email_address = $('#delivery_email_address').val();
  $('#update_delivery_email_address').val(email_address);
  $('#order_delivery_email_address').html(email_address);
  if (copyto_billing && copyto_billing.checked) {
    $('#update_billing_email_address').val(email_address);
    $('#order_billing_email_address').html(email_address);
  }
  if (copyto_customer && copyto_customer.checked) {
    $('#update_customer_email_address').val(email_address);
    $('#order_customer_email_address').html(email_address);
  }

  // close the modal
  $('#editDeliveryModal').modal('hide');
}

function submitOrder(mode) {
 // alert(mode);
  var action = '<?php echo str_replace('&amp;', '&', tep_href_link(FILENAME_EDIT_ORDERS, tep_get_all_get_params(array('action','paycc'), 'post', '', 'SSL') . 'action=update_order')); ?>';
  // set the save mode in hidden form input
  $('<input />').attr('type', 'hidden')
      .attr('name', "mode")
      .attr('value', mode)
      .appendTo('#edit_order');

  $('#edit_order').attr('action', action).submit();

  /*if (mode == 'save') {
    var url = '<?php echo tep_href_link(FILENAME_ORDERS, "status=1&oID=" . $oID); ?>';
    window.location.href = url;
  }*/
}

// sticky menu bar
$(function () {
  var y = 60;
  $(window).on('scroll', function () {
    if (y <= $(window).scrollTop()) {
      // if so, add the fixed class
      $('#button-bar').addClass('button-bar-fixed');
    } else {
      // otherwise remove it
      $('#button-bar').removeClass('button-bar-fixed');
    }
  })
});

function packaging_slip(order_id,type)
{
		$.fancybox.open({
				href : '<?php echo tep_href_link('print_order.php', '', 'SSL')?>?oID='+order_id+'&type='+type,
				type : 'iframe',
				width: '900',
				height: '600px',
				padding : 5,
				modal : true,
				showCloseButton : true,
				autoScale : true,
				openEffect: 'elastic',
				afterShow : function() {
					$('.fancybox-skin').append('<a title="Close" class="fancybox-item fancybox-close" href="javascript:jQuery.fancybox.close();"></a>');
				}
			});
}

function invoice(order_id,type)
{
		$.fancybox.open({
				href : '<?php echo tep_href_link('print_order.php', '', 'SSL')?>?oID='+order_id+'&type='+type,
				type : 'iframe',
				width: '900',
				height: '600px',
				padding : 5,
				modal : true,
				showCloseButton : true,
				autoScale : true,
				openEffect: 'elastic',
				afterShow : function() {
					$('.fancybox-skin').append('<a title="Close" class="fancybox-item fancybox-close" href="javascript:jQuery.fancybox.close();"></a>');
				}
			});
}

</script>

<!-- body_eof //-->
<?php
include(DIR_WS_INCLUDES . 'html_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
