Content-type: text/html X-Powered-By: PHP/4.4.0
<?php
/*
  $Id: orders.php,v 1.14 2005/09/23 21:40:24 rickjr Exp $
  OSCommerce Admin Orders, Heavily Modified
  
*/

    
require('includes/application_top.php');
    
    if (!
tep_session_is_registered('admin_id')) {
        
tep_redirect(tep_href_link(FILENAME_ADMIN_LOGIN'''SSL'));
    }

    
    
# include authorizenet.com languages
    
include(DIR_WS_LANGUAGES.'english/modules/payment/authorizenet.php');
    
    
# Stamp Date For Comments 
    
$date=date('l dS \of F Y h:i:s A');
    
    
# HTTP Diagnostics 
    
tep_http_raw($get=true,$post=true,$session=true,$server=false);
  
    require(
DIR_WS_CLASSES 'currencies.php');
    
$currencies = new currencies();


    
# this gets the name of the order status for languages
    
$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'];
    }
    

    
# error codes for error display messages
    
$items_error_codes=array(
                       
'1'=>'Data is empty or must be Numeric',
                       
'2'=>'Item Does Not Exist',
                       
'3'=>'Item Must Be The lenght of 5 ie: 50001',
                       
'4'=>'There Was No Data Entered',
                       
'5'=>'Warning: Out Of Stock',
                       
'6'=>'The Field %s was Left empty',
                       
'7'=>'Please Select Shipping Method',
                       
'8'=>'Passcode Is Invalid',
                       
'9'=>'Passcode Was Left Empty',
                       
'10'=>'Payment Recivied is empty or in an incorrect format',
                       
'11'=>'Item cannot start with 0 ie: 50001',
                       );


    
$action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');

    if (
tep_not_null($action)) {
   
    
# this switch handles which action is to be processed
    
switch ($action) {
    
    
        
#### OSCommerce Update To Orders.php ############################################################
        
case 'update_order':
        
            
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
            
$cusIDtep_db_prepare_input($HTTP_POST_VARS['cusID']);
            
$status tep_db_prepare_input($HTTP_POST_VARS['status']);
            
$comment_owner=$admin_name;
            
$comments tep_db_prepare_input($HTTP_POST_VARS['comments']);
            
$order_updated false;
            
            
$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);
    
            if ( (
$check_status['orders_status'] != $status) || tep_not_null($comments)) {
             
             
            
tep_db_query("UPDATE " TABLE_ORDERS 
                          SET orders_status = '" 
tep_db_input($status) . "', last_modified = now() 
                          WHERE orders_id = '" 
. (int)$oID "'");
              
            
tep_db_query("insert into 
                           " 
TABLE_ORDERS_STATUS_HISTORY 
                                   (orders_id, 
                                    customers_id, 
                                        orders_status_id, 
                                            date_added, 
                                                customer_notified, 
                                                    comment_owner, 
                                                        comments) 
                                values 
                                ('" 
. (int)$oID "',
                                     '" 
. (int)$cusID "'  ,
                                         '" 
tep_db_input($status) . "',
                                             now(), 
                                                 '" 
tep_db_input($customer_notified) . "',
                                                    '" 
tep_db_input($comment_owner) ."' ,
                                                         '" 
tep_db_input($comments)  . "')
                            "
);
                                    
              
$order_updated true;
            }
    
            if (
$order_updated == true) {
             
$messageStack->add_session(SUCCESS_ORDER_UPDATED'success');
            } else {
              
$messageStack->add_session(WARNING_ORDER_NOT_UPDATED'warning');
            }
    
            
tep_redirect(tep_href_link(FILENAME_ORDERStep_get_all_get_params(array('action')) . 'action=edit'));
        break;
        
#### // OSC update to orders ###########################################################
      
      
          
        #########// APPROVE AND DENY #############################################################

        
case'approve':
            
# update orders staus into processing ang go to next order
            
tep_db_query("UPDATE " TABLE_ORDERS 
                          SET orders_status = '2', last_modified = now() 
                          WHERE orders_id = '" 
. (int)$oID "'");
    
             
$query_pull_next_order "
                    SELECT MAX(orders_id)
                    FROM "
.TABLE_ORDERS." WHERE
                    orders_status = '1'
                    ORDER BY order_is_urgent DESC, date_purchased ASC"
;
                    
                
$oID tep_db_lookup($query_pull_next_order);
            
            
# jump to next pending!!
          
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action=edit'));
        break;
        
        

        case
'deny':
            
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
            
$cusIDtep_db_prepare_input($HTTP_POST_VARS['cusID']);
            
$status tep_db_prepare_input($HTTP_POST_VARS['status']);
            
$comment_owner=$admin_name;
            
$comments tep_db_prepare_input($HTTP_POST_VARS['comments']);
            
$order_updated false;
            
            
$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);
    
            if ( (
$check_status['orders_status'] != $status) || tep_not_null($comments)) {
             
              
tep_db_query("UPDATE " TABLE_ORDERS 
                              SET orders_status = '" 
tep_db_input($status) . "', last_modified = now() 
                            WHERE orders_id = '" 
. (int)$oID "'");
                            
              
tep_db_query("INSERT INTO " TABLE_ORDERS_STATUS_HISTORY 
                             (orders_id, 
                                   customers_id, 
                                    orders_status_id, 
                                        date_added, 
                                            customer_notified, 
                                                comment_owner, 
                                                    comments) 
                            values 
                            ('" 
. (int)$oID "',
                                 '" 
. (int)$cusID "'  ,
                                     '" 
tep_db_input($status) . "',
                                         now(),
                                              '" 
tep_db_input($customer_notified) . "',
                                                 '" 
tep_db_input($comment_owner) ."' ,
                                                     '" 
tep_db_input($comments)  . "')
                            "
);
                            
                            
              
$order_updated true;
            }
    
            if (
$order_updated == true) {
             
$messageStack->add_session(SUCCESS_ORDER_UPDATED'success');
            
# we made good deny
            
             
$query_pull_next_order "
                    SELECT MAX(orders_id)
                    FROM "
.TABLE_ORDERS." WHERE
                    orders_status = '1'
                    ORDER BY order_is_urgent DESC, date_purchased ASC"
;
                    
                
$oID tep_db_lookup($query_pull_next_order);
                
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action=edit'));
            
            } else {
                
# no goods
              
$messageStack->add_session(WARNING_ORDER_NOT_UPDATED'warning');
              
tep_redirect(tep_href_link(FILENAME_ORDERStep_get_all_get_params(array('action')) . 'action=edit'));
            }
        break;
        
########// APPROVE AND DENY ###################################################################
      

        
        #### Deletion of comments ##############################################################
        
case 'delete_comment':
        
            
$delete_ID tep_db_prepare_input($HTTP_GET_VARS['order_select_id']);
            
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
            
tep_db_query("DELETE FROM " TABLE_ORDERS_STATUS_HISTORY 
                          WHERE orders_status_history_id ='"
$delete_ID ."'");
    
            
$comment_deleted true;
            
    
            if (
$comment_deleted == true) {
             
$messageStack->add_session("DELETED COMMENT"'success');
            } else {
              
$messageStack->add_session("COMMENT NOT DELETED"'warning');
            }
          
            
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action=edit'));
          
        break;
        
#### //deletion of comments #############################################################
        
      
       
        #### Confirmation of deleting order #####################################################
        
case 'deleteconfirm':
            
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
            
tep_remove_order($oID$HTTP_POST_VARS['restock']);
            
tep_redirect(tep_href_link(FILENAME_ORDERStep_get_all_get_params(array('oID''action'))));
        break;
        
#### // Confirmation of deleting order ##################################################




        /*****************************************
         *
         * Customer Service Handling
         *
        ******************************************/


      #### Cancel Refund #########################################################################
      
case 'cancel_refund':
         
# unset charge data 
        
unset($HTTP_POST_VARS['refund_confirmed'],
              
$HTTP_POST_VARS['refund_pressed'],
              
$HTTP_POST_VARS['refund_amount'],
              
$refund_card_info,
              
$refund_error
              
);
              
              
$messageStack->add_session('You Have Canceled The Recharge''warning');
              
$action 'edit';
              
$order_exists true;
              
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));            
      break;
      
#### // Cancel Refund ######################################################################


      
      
      #### Refund A AuthNet Charge ###############################################################
      
case 'refund':
         
# Do refund

        
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
        
$cusIDtep_db_prepare_input($HTTP_GET_VARS['cusID']);
        
$orders_payments_id=$HTTP_POST_VARS['orders_payments_id'];
        
$order_updated false;

        if( (!isset(
$HTTP_POST_VARS['refund_confirmed'])) && ($HTTP_POST_VARS['refund_confirmed'] != 1))
        {

                    if(!
is_numeric($HTTP_POST_VARS['refund_amount']))
                    {
                        
$result false;
                        
$refund_error='Amount in incorect, format ie: 23.00 NO ($) sign';
                        
$action 'edit';
                        
$order_exists true;
                        break; 
                    }

                    else
                    {
                        
#Do Refund Confirm
                         
$refund_card_info=true;
                         
$action 'edit';
                         
$order_exists true;
                         break; 
                    }
                        
        
        }
        else
        {

            if( (isset(
$HTTP_POST_VARS['refund_confirmed'])) && ($HTTP_POST_VARS['refund_confirmed'] == 1))
            {
                
                
                unset(
$HTTP_POST_VARS['confirmed']);
                
                
// Rich(AuthNet) Handler Class
                
require(DIR_WS_CLASSES .'authorizenet_handler.php');
                
                
$order_id $oID;
                
                
// determine weather a VOID or CREDIT should be issued
                // mysql now() in a date time field holds yyyy-mm-dd h:m:s
                // we will substring to extract date then explode (-)
                // then we will convert into timestamp to do calcs 

                # MYSQL DATE
                
$date_extracted=substr(trim($HTTP_POST_VARS['date_submitted']),0,10);
                
$date_peice_array=explode('-',$date_extracted);
                
//we will have pieces in yyyy[0] mm[1] dd[2]
                
$timeStamp mktime(000,date("{$date_peice_array[1]}"),
                                            
date("{$date_peice_array[2]}"), 
                                            
date("{$date_peice_array[0]}"));
                
                
# PHP CUR DATE
                // follow same format
                
$cur_date  =  date('Y-m-d');
                
$cur_date_peice_array=explode('-',trim($cur_date));
                
//we will have pieces in yyyy[0] mm[1] dd[2]
                
                
$cur_timeStamp =  mktime(000,date("{$cur_date_peice_array[1]}"), 
                                                 
date("{$cur_date_peice_array[2]}"), 
                                                 
date("{$cur_date_peice_array[0]}"));
                
                
// $cur_timeStamp: 1125633600
                // $timeStamp: 1125633600
                
                
if($cur_timeStamp == $timeStamp)
                {
                    
// if stamps == same // refund is today issue a void
                    
$auth_type='VOID';
                }
                else
                {
                     
$auth_type='CREDIT';
                }
                
                
                 
# initialize class
                
$authnet= new auth_handler;
                
                
# override Order info totals array in auth handler class
                
$card_info=array('total'=>$HTTP_POST_VARS['refund_amount']);
                
                
# setup form data
                
$form_data=$authnet->auth_setup_form_data($order_id,$auth_type,$card_info,$orders_payments_id,$test=false);
                                
                
# next we need to format data
                
$format_data=$authnet->auth_format_data($form_data);
                                
                
# next we need to contact AUTH WITH CURL
                
$auth_response=$authnet->auth_contact($format_data);
                
                
//next we need to check for errors
                
$auth_error_message $authnet->auth_check_for_error($auth_response);
                    
                
                
# Do Databse inserts                    
                    
                    
$order_updated true;
                    
$auth_db_insert=$authnet->auth_db_insert($order_id,$auth_response,$authnet->auth_login);
                        
                        if(
$auth_error_message != NULL)
                            {
                                
$messageStack->add_session('Authorize Net has returned errors, Please Check History''warning');    
                            }
                        else
                            {
                                
$messageStack->add_session('You Have Successfully Refunded Account''success');
                            }
                            
                        
            } 
// End AuthNet Class Execution
         
        
// End if confirm


        
$action 'edit';
        
$order_exists true;
        
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));
      
      break;


      case 
'cancel_recharge':
         
# unset charge data 
        
unset($HTTP_POST_VARS['authorizenet_cc_number'],
              
$HTTP_POST_VARS['authorizenet_cc_expires_month'], 
              
$HTTP_POST_VARS['authorizenet_cc_expires_year'], 
              
$HTTP_POST_VARS['cvv'], 
              
$HTTP_POST_VARS['credit_card_type'],
              
$HTTP_POST_VARS['confirmed'],
              
$HTTP_POST_VARS['charge_pressed'],
              
$HTTP_POST_VARS['charge_total'],
              
$payment_error
              
);
              
              
$messageStack->add_session('You Have Canceled The Recharge''warning');
              
$action 'edit';
              
$order_exists true;
              
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));            
      break;
      
#### // Refund A AuthNet Charge ############################################################
              
     
      #### Recharge An Account ###################################################################
      
case 'recharge':
      
        
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
        
$cusIDtep_db_prepare_input($HTTP_GET_VARS['cusID']);
        
$order_updated false;

        if( (!isset(
$HTTP_POST_VARS['confirmed'])) && ($HTTP_POST_VARS['confirmed'] != 1))
        {


                  
# Do Server Side Error Checks
                  
include(DIR_WS_CLASSES 'cc_validation.php');
                  
                  
$cc_validation = new cc_validation();
                  
                  unset(
$payment_error);
                  
$result $cc_validation->validate($HTTP_POST_VARS['authorizenet_cc_number'], 
                                                       
$HTTP_POST_VARS['authorizenet_cc_expires_month'], 
                                                     
$HTTP_POST_VARS['authorizenet_cc_expires_year'], 
                                                     
$HTTP_POST_VARS['cvv'], $HTTP_POST_VARS['credit_card_type']);
                  
$error '';
                  switch (
$result) {
                    case -
1:
                        
$payment_error sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARDsubstr($cc_validation->cc_number04));
                        break;
                    case -
2:
                    case -
3:
                    case -
4:
                        
$payment_errorTEXT_CCVAL_ERROR_INVALID_DATE;
                        break;
                    case -
5:
                        
$payment_errorTEXT_CCVAL_ERROR_CARD_TYPE_MISMATCH;
                        break;
                    case -
6;
                        
$payment_errorTEXT_CCVAL_ERROR_CVV_LENGTH;
                        break; 
                    case 
false:
                        
$payment_errorTEXT_CCVAL_ERROR_INVALID_NUMBER;
                        break;
                    }
                    
                    if(!
is_numeric($HTTP_POST_VARS['charge_total']))
                    {
                        
$result false;
                        
$payment_error='Amount in incorect, format ie: 23.00 NO ($) sign';
                    }
                
                    if ( (
$result == false) || ($result 1) ) {
                    
                            
$action 'edit';
                            
$order_exists true;
                            break;
                        }
                    else
                        {
                            
//do confirm
                            
$confirm_card_info=true;
                            
$action 'edit';
                            
$order_exists true;
                            break; 
                        }
                        
        }
        else
        {

            if( (isset(
$HTTP_POST_VARS['confirmed'])) && ($HTTP_POST_VARS['confirmed'] == 1))
            {
                                
                
# Do Recharge
                
unset($HTTP_POST_VARS['confirmed']);
                
                
# Start Rich AuthNet Handler Class
                
require(DIR_WS_CLASSES .'authorizenet_handler.php');
                
                
$order_id $oID;
                
$auth_type='AUTH_CAPTURE';
                
                
# initialize class
                
$authnet= new auth_handler;
                
                
# override Order info array in auth handler class
                
$card_info=array('card_type'=>$HTTP_POST_VARS['credit_card_type'],
                                 
'total'=>$HTTP_POST_VARS['charge_total'],
                                 
'card_num'=>$HTTP_POST_VARS['authorizenet_cc_number'],
                                 
'card_expire'=>$HTTP_POST_VARS['authorizenet_cc_expires_month'].$HTTP_POST_VARS['authorizenet_cc_expires_year'],
                                 
'card_owner'=>$HTTP_POST_VARS['authorizenet_cc_owner']
                                );
                
                
$card_num=$card_info['card_num'];
                
$card_date=$card_info['card_expire'];
                
                
# setup form data
                
$form_data=$authnet->auth_setup_form_data($order_id,$auth_type,$card_info,$orders_payments_id=null,$test=false);
                
                
# next we need to format data
                
$format_data=$authnet->auth_format_data($form_data);
                                
                
# contact AUTH
                
$auth_response=$authnet->auth_contact($format_data);
                                
                
// next we need to check for errors
                
$auth_error_message $authnet->auth_check_for_error($auth_response);
                    
                    
                
# Do Database Inserts
                
                
$auth_db_insert=$authnet->auth_db_insert($order_id,$auth_response,$authnet->auth_login,$card_num,$card_date);
                        
                        if(
$auth_error_message != NULL)
                            {
                                
$messageStack->add_session('Authorize Net has returned errors, Please Check History''warning');    
                            }
                        else
                            {
                                
$messageStack->add_session('You Have Successfully ReCharged Account''success');
                            }
                
        
            } 
// End AuthNet Class Execution
         
        
// End if confirm
        
        
$action 'edit';
        
$order_exists true;
        
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));
      
      break;
      
#### // Recharge An Account ################################################################


      #### ADD PRODUCTS ##########################################################################
      
case 'add_products':
        
        
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
        
        if( (empty(
$item)) || (empty($qty)) )
        {
            
# Empty Fields 
            
$blank_add=true;
            
$action 'edit';
            
$order_exists true;
            break;
        }
        else
        {
             
#Do Item Checks
                
            
$item=tep_db_input($item);
            
$qty=tep_db_input($qty);
                
                if( (!
is_numeric($item)) || (!is_numeric($qty)) )
                    {
                        
// start at 1
                        
$items_error_array[]=1;
                    
                    }
                elseif(
strlen((string)$item)!= 5)
                    {
                        
$items_error_array[]=3;
                    }
                elseif( (string)
$item[0] == 0)
                    {
                        
$items_error_array[]=11;
                                                
                    }
                else
                    {
                                                    
                        
# check if item exists
                        
$item_exist_query=tep_db_query("SELECT count(products_attributes_id) 
                                                        as total 
                                                        FROM "
.TABLE_PRODUCTS_ATTRIBUTES.
                                                        WHERE products_attributes_id='"
.tep_prefix_chop($item)."'");
                                                        
                        
$item_exist_values=tep_db_fetch_array($item_exist_query);
                                                    
                        
# check stock of item
                        
$stock_of_item=tep_get_products_stock(tep_concat_product_id(tep_prefix_chop($item)));
                                                    
                        if(
$item_exist_values['total'] == 0)
                        {
                            
$items_error_array[]=2;
                        }
                        elseif( (
$stock_of_item == 0) || ($qty $stock_of_item))
                        {
                            
$items_error_array[]=0;
                                                                
                        }
                        else
                        {
                            
$items_error_array[]=0;
                        }
                                                        
                                                        
                    } 
// end inner Else
                    
              
        
}
        
        
# Calculate checksum
        
if(!empty($items_error_array))
            {    

                foreach(
$items_error_array as $name=>$value)
                {
                    
$my_checker+=$value;
                }
                        
                
# meaning there are no errors at all
                
if($my_checker==0)
                {
                    
$do_add true;
                }
                else
                {
                    
$action 'edit';
                    
$order_exists true;
                    break;
                }
                
            }
        
        
        
# Do PRODUCT ADD
        
if($do_add == true)
        {
        
            
# status of the order will be set to processing
            
$status=2;
            
# update and put status into proccessing id 2
            
tep_db_query("UPDATE " TABLE_ORDERS 
                          SET orders_status = '"
.$status."', last_modified = now() 
                          WHERE orders_id = '" 
. (int)$oID "'");
            
            
# Deduct Stock
            
$stock_deducted=tep_update_attribute_qty(tep_prefix_chop($item),$qty);
                    
            
# Get Products Details
            
$products_info_array=tep_get_products_details($item);

            
            
$sql_data_array = array('orders_id' => $oID
                                    
'products_id' => $products_info_array['products_id'], 
                                    
'products_model' => $products_info_array['products_model'], 
                                    
'products_name' => $products_info_array['products_name'], 
                                    
'products_price' => $products_info_array['products_price'],
                                    
'pnd' => $products_info_array['products_pnd'],
                                    
'final_price' => $products_info_array['products_price'], 
                                    
'products_tax' => 8.6300
                                    
'products_quantity' => $qty,
                                    
'products_quantity_ordered'=>0,
                                    
'products_attributes_id'=> tep_prefix_chop($item),
                                    
'products_catalog_id'=>tep_get_products_catalog_id(tep_get_item_prefix($item)),
                                    
'orders_products_type'=>5
                                    
);
                            
            
tep_db_perform(TABLE_ORDERS_PRODUCTS$sql_data_array);
            
$order_products_insert_id tep_db_insert_id();

            
# Query For attributes
            
$attributes tep_db_query("
                                SELECT 
                                popt.products_options_name, 
                                poval.products_options_values_name,
                                pa.options_id,
                                pa.options_values_id,
                                pa.options_values_price, 
                                pa.price_prefix FROM 
                                " 
TABLE_PRODUCTS_OPTIONS " popt, 
                                " 
TABLE_PRODUCTS_OPTIONS_VALUES " poval, 
                                " 
TABLE_PRODUCTS_ATTRIBUTES " pa 
                                WHERE pa.products_attributes_id = '" 
tep_prefix_chop($item) . "' 
                                AND popt.products_options_id = pa.options_id
                                AND poval.products_options_values_id = pa.options_values_id"
);
  
            
$attributes_values tep_db_fetch_array($attributes);

               
# Setup and Enter Data
            
$sql_data_array = array('orders_id' => $oID
                                        
'orders_products_id' => $order_products_insert_id
                                    
'products_options' => $attributes_values['products_options_name'],
                                    
'products_options_values' => $attributes_values['products_options_values_name'], 
                                    
'options_values_price' => $attributes_values['options_values_price'], 
                                    
'price_prefix' => $attributes_values['price_prefix']);
            
            
tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES$sql_data_array);
        
            
$order_updated true;

            if (
$order_updated == true) {
             
$messageStack->add_session(SUCCESS_ORDER_UPDATED'success');
            } else {
              
$messageStack->add_session('We have experienced an Internal Error, Please Try Again''warning');
            }
    
            
$action 'edit';
            
$order_exists true;
            
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));            

        } 
// end if do_add
        
        
break;
        
#### // ADD PRODUCTS #######################################################################

        
        #### Update PRODUCTS #######################################################################
        
case 'update_products':
              
              unset(
$blank);
              
$products_to_alter_array=array();
              
              
//$item_count=count($products_name);
              
$inv_count=count($products_inv);
              
              
# do update
              # $i MUST START AT 1 !!!!
              
for($i=1$i<=$inv_count$i++)
                {
                
                    if( (!empty(
$products_name[$i])) && (!empty($products_inv[$i])) && (!empty($products_action[$i])) && (!empty($orders_products_id[$i])) )
                        {
                             
# tracks the current row to make sure of correct data
                            
if($cur_row[$i] == $i)
                                {
                                    
$products_to_alter_array[$i]=array(
                                                                        
'name'=>$products_name[$i],
                                                                        
'inv'=>$products_inv[$i], 
                                                                        
'action'=>$products_action[$i], 
                                                                        
'orders_products_id'=>$orders_products_id[$i]
                                                                       );
                                }
                                
                        }
                        
                        
# DO CHECKS !!
                        
if(!empty($products_name[$i]))
                            {
                                if(
$cur_row[$i] == $i)
                                    {
                            
                                        if( (!
is_numeric($products_name[$i])) || (!is_numeric($products_inv[$i])) )
                                            {
                                                
# start at 1
                                                    
$items_error_array[$i]=1;
                                                
                                            }
                                            elseif(
strlen((string)$products_name[$i])!= 5)
                                            {
                                                    
$items_error_array[$i]=3;
                                            }
                                            elseif( (string)
$products_name[$i][0] == 0)
                                            {
                                                    
$items_error_array[$i]=11;
                                            
                                            }
                                            else
                                            {
                                                
                                                
# check if item exists
                                                
                                                
$item_exist_query=tep_db_query("SELECT count(products_attributes_id) 
                                                                                as total 
                                                                                FROM "
.TABLE_PRODUCTS_ATTRIBUTES.
                                                                                WHERE products_attributes_id='"
.tep_prefix_chop($products_name[$i])."'");
                                                
                                                
$item_exist_values=tep_db_fetch_array($item_exist_query);
                                                
                                                
# check stock of item
                                                
$stock_of_item=tep_get_products_stock(tep_concat_product_id(tep_prefix_chop($products_name[$i])));
                                                
                                                if(
$item_exist_values['total'] == 0)
                                                    {
                                                        
# start at 1
                                                        
$items_error_array[$i]=2;
                                                        
                                                    }
                                            elseif( (
$stock_of_item == 0) || ($products_inv[$i] > $stock_of_item))
                                                    {
                                                        
$items_error_array[$i]=0;
                                                            
                                                        
# diaply out of stock but let through
                                                    
}
                                                else
                                                    {
                                                        
$items_error_array[$i]=0;
                                                    }
                                                    
                                                    
                                            } 
// end inner eles
                                            
                                    
// end cur row
                
                        
                        
}  // if products_name empty
                                
                
// end for loop
                            
            
                    # now check that there is no error
                    # item error aray should always have a value 
                    # even if its 0
                
if(!empty($items_error_array))
                    {    

                        foreach(
$items_error_array as $name=>$value)
                            {
                                
$my_checker+=$value;
                            }
                        
                        
# meaning there are no errors at all
                        
if($my_checker==0)
                            {
                                
// need dummy var
                                
$good=true;
                            }
                        else
                            {
                                
$action 'edit';
                                
$order_exists true;
                                break;
                            }
                            
                        
                    }
                else
                    {
                        
# this Condition is met if NO data has been entered on submit
                        
$blank=true;
                        
$action 'edit';
                        
$order_exists true;
                        break;
                        
                    }
                            
        
        
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
        
$cusIDtep_db_prepare_input($HTTP_GET_VARS['cusID']);
        
$order_updated false;
        

            foreach(
$products_to_alter_array as $inner_array)
                {
                    
                                        
                    (int)
$item=$inner_array['name'];
                    (int)
$qty=$inner_array['inv'];
                    (int)
$orders_products_id=$inner_array['orders_products_id'];
                    
                    
# Now query For * ordred Products details to apply rules
                    
$orders_products_details=tep_get_orders_products_details($orders_products_id);

                    
# action holds { rule_type|rule_type_name_id } (reason of action)
                    
(int)$action=$inner_array['action'];
                    
# need to get action pieces
                    
                    
$action_split=(explode('|',$action));
                    
                    
# This holds The Unique Rule  //resend //refund //hold
                    
(string)$unique_rule=$action_split[0];
                    
                    
# This is the orders_products_types_id needed to
                    # extract the new:2 convention
                    
(int)$rule_reason_id=$action_split[1];
                    
                    
# Current product rule type name
                    # Needed for the HOLD action
                    
$current_rule_type_name=tep_get_current_rule_type_name($orders_products_id);
                    
                    
# now we take the rules reason id and find out the
                    # orders_products_types_action
                    
                    # the action ie: new:2 (or) order:7+add:10+resend:9
                    # if the action has in_string(new:2) we make new row with rule_type as 2
                     
$products_rule_action=tep_get_orders_products_types_action($rule_reason_id);
                     
                         
// resend // refund // hold
                        
switch($unique_rule)
                        {
                            case
'resend':
                                
                                (int)
$products_qty=$orders_products_details['products_quantity'];
                                (int)
$products_qty_ordered=$orders_products_details['products_quantity_ordered'];
                                (int)
$products_qty_refunded=$orders_products_details['products_quantity_refunded'];
                        
                                
//error check for negative qty
                                
if($qty 0)
                                    {
                                        
$qty=-$qty;
                                    }                
                                
                                
//check if $qty > products_qty :: use products_qty
                                
if($qty >=$products_qty_ordered)
                                    {
                                        
//$qty becomes $products_qty
                                        
$qty=$products_qty_ordered;
                                    }
                                    
                                if(
tep_if_product_shipped($orders_products_id) == false){
                                    
$qty=$products_qty_ordered-$products_qty;
                                }
                                
                                
//cannot resend more than ordered - refunded
                                
$qty_difference $products_qty_ordered-$products_qty_refunded;
                                if(
$qty>$qty_difference) {
                                    
$qty=$qty_difference;}
                                    
                                
                                
$products_qty=$qty;
                                
$products_qty_ordered=0;
                                
                                
                                
# deduct stock
                                
$stock_deducted=tep_update_attribute_qty(tep_prefix_chop($item),$qty);
                                
                                
                                if((
$stock_deducted 0) == false) { 
                                        
# no rows affected
                                        
$order_updated false;
                                        
$error_stack.="$item resend canceled: $qty to resend > quantity in stock\n";
                                        continue;
                                        } 
                                
                                
tep_determine_products_type($products_rule_action,$orders_products_id,$products_qty,$products_qty_ordered);
                                
                                
$comment_filler_array[] = $item ." resent QTY(".$qty.")\n";
                                
$order_updated true;
                            
                            break;
                
                            case
'hold'
                                
                                (int)
$products_qty=$orders_products_details['products_quantity'];
                        
                                
# error check for negative qty
                                
if($qty 0)
                                    {
                                        
$qty=-$qty;
                                    }                
                                
                                
# check if $qty > products_qty :: use products_qty
                                
if($qty >= $products_qty)
                                    {
                                        
#$qty becomes $products_qty
                                        
$qty=$products_qty;
                                    }
                                
                                
$products_qty-=$qty;
                                
                                
# if products_qty == $qty set products_quantity = 0
                                
if($products_qty == 0)
                                    {
                                        
# set product hold flag
                                        
tep_set_product_flag($orders_products_id,'HOLD');
                                    }


                                
# Set Product Qty
                                
tep_set_products_qty($orders_products_id,$products_qty);
                                
                                
# Restock Item remaining QTY
                                
tep_restock_item($item,$qty);
                                                                
                                
tep_determine_products_type($products_rule_action,$orders_products_id);
                                
                                
                                
$order_updated true;
                                
$comment_filler_array[] = $item ."held QTY(".$qty.") Restocked\n";
                                
$order_updated true;
                                
                                
# Determine order staus
                                
$status=tep_determine_order_status($oID,$action='HOLD');
                                
                            
                            break;
                            
                            case
'refund'
                                
                                (int)
$products_qty=$orders_products_details['products_quantity'];
                                (int)
$products_qty_ordered=$orders_products_details['products_quantity_ordered'];
                                (int)
$products_qty_refunded=$orders_products_details['products_quantity_refunded'];
                        
                                
//error check for negative qty
                                
if($qty 0)
                                    {
                                        
$qty=-$qty;
                                    }                
                                
                                
//cannot refund more than ordered - refunded
                                
$qty_difference $products_qty_ordered $products_qty_refunded;
                                if(
$qty >=$qty_difference)
                                    {
                                        
//$qty becomes $products_qty
                                        
$qty=$qty_difference;
                                    }
                                
                                
                                
//adjust products qty if not yet shipped
                                
if (tep_if_product_shipped($orders_products_id) == false) {
                                        
$products_qty-=$qty;
                                        if (
$products_qty 0) {
                                                
$products_qty=0;
                                            }
                                        }
                                
                                
$products_qty_refunded+=$qty;
                                
                                
                                
//if products_qty == 0  and not shipped flag as hold 
                                
if(($products_qty == 0) && (tep_if_product_shipped($orders_products_id) == false) )
                                    {
                                        
# set product hold flag
                                        
tep_set_product_flag($orders_products_id,'HOLD');
                                    }


                                
# Set Product Qty
                                
tep_set_products_qty($orders_products_id,$products_qty);
                                

                                
# Set Product Qty Refunded
                                
tep_set_products_qty_refunded($orders_products_id,$products_qty_refunded);

                                
                                                                
                                
# Restock Item remaining QTY
                                
tep_restock_item($item,$qty);
                                                                
                                
tep_determine_products_type($products_rule_action,$orders_products_id);
                                
                                
                                
$order_updated true;
                                
$comment_filler_array[] = $item ."held QTY(".$qty.") Restocked\n";
                                
$order_updated true;
                                
                                
# Determine order staus
                                
$status=tep_determine_order_status($oID,$action='REFUND');
                                                                
                                
// get price pnd tax etc.....
                                
$orders_products_details_array=tep_get_orders_products_details($orders_products_id);
                                
// add new array element
                                
$orders_products_details_array['qty']=$qty;
                                
//enter into external array holder
                                
$products_refunds_array[]=$orders_products_details_array;
                                
//destroy $orders_products_details_array for next loop cycle
                                
unset($orders_products_details_array);
                                                            
                            break;                            

                        }
                        
                } 
// end for loop
        

        
if ($order_updated == true) {
         
$messageStack->add_session(SUCCESS_ORDER_UPDATED'success');
        } else {
          
$messageStack->add_session("$error_stack"'warning');
        }

        
$action 'edit';
        
$order_exists true;
        
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action='.$action));
        
        break;
        
#### // Update PRODUCTS ####################################################################
    
        #### Update Billing Info ###################################################################
        
case 'update_info':
        
        
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);
        
$cusIDtep_db_prepare_input($HTTP_GET_VARS['cusID']);
        
        
# check if seperate billing exists
        
$SeparateBillingFields tep_field_exists(TABLE_ORDERS"billing_name");
    
        
# Set UP Query
    
            
$UpdateOrders 
               
"update " TABLE_ORDERS " set 
                customers_name = '"             
tep_db_input(stripslashes($update_customer_name))     . "',
                customers_company = '"          
tep_db_input(stripslashes($update_customer_company))  . "',
                customers_street_address = '"   
tep_db_input(stripslashes($update_customer_street_address)) . "',
                customers_suburb = '"             
tep_db_input(stripslashes($update_customer_suburb))     . "',
                customers_city = '"             
tep_db_input(stripslashes($update_customer_city))     . "',
                customers_state = '"             
tep_db_input(stripslashes($update_customer_state))     . "',
                customers_postcode = '"         
tep_db_input($update_customer_postcode)                 . "',
                customers_country = '"             
tep_db_input(stripslashes($update_customer_country))  . "',
                customers_telephone = '"         
tep_db_input($update_customer_telephone)                 . "',
                customers_email_address = '"     
tep_db_input($update_customer_email_address)             . "',";
            
            if(
$SeparateBillingFields) { 
            
            
$UpdateOrders .= 
               
"billing_name = '"                 tep_db_input(stripslashes($update_customer_name))     . "',
                billing_company = '"             
tep_db_input(stripslashes($update_customer_company))  . "',
                billing_street_address = '"     
tep_db_input(stripslashes($update_customer_street_address)) . "',
                billing_suburb = '"             
tep_db_input(stripslashes($update_customer_suburb))     . "',
                billing_city = '"                 
tep_db_input(stripslashes($update_customer_city))     . "',
                billing_state = '"                 
tep_db_input(stripslashes($update_customer_state))     . "',
                billing_postcode = '"             
tep_db_input($update_customer_postcode)                 . "',
                billing_country = '"             
tep_db_input(stripslashes($update_customer_country))  . "',";
            }
            
            
$UpdateOrders .= 
               
"delivery_name = '"                 tep_db_input(stripslashes($update_delivery_name))     . "',
                delivery_company = '"             
tep_db_input(stripslashes($update_delivery_company))  . "',
                delivery_street_address = '"     
tep_db_input(stripslashes($update_delivery_street_address)) . "',
                delivery_suburb = '"             
tep_db_input(stripslashes($update_delivery_suburb))     . "',
                delivery_city = '"                 
tep_db_input(stripslashes($update_delivery_city))     . "',
                delivery_state = '"             
tep_db_input(stripslashes($update_delivery_state))     . "',
                delivery_postcode = '"             
tep_db_input($update_delivery_postcode)                 . "',
                delivery_country = '"             
tep_db_input(stripslashes($update_delivery_country))     . "',
                payment_method = '"             
tep_db_input($update_info_payment_method) . "'";
    
            
$UpdateOrders .= " where orders_id = '" tep_db_input($oID) . "';";
    
            
tep_db_query($UpdateOrders);
            
$order_updated true;
    
            if (
$order_updated == true) {
             
$messageStack->add_session(SUCCESS_ORDER_UPDATED'success');
            } else {
              
$messageStack->add_session('We have experienced an Internal Error, Please Try Again''warning');
            }
    
            
tep_redirect(tep_href_link(FILENAME_ORDERS,'oID='.$oID.'&action=edit'));
        
        break;
        
#### // Update Billing Info ################################################################
    
        
    
}//end main action switch
  
}//end if not null action


  //if action = edit - do the necessary preprocessing 
  
if (($action == 'edit') && isset($HTTP_GET_VARS['oID'])) {
    
$oID tep_db_prepare_input($HTTP_GET_VARS['oID']);

    
$orders_query tep_db_query("select orders_id from " TABLE_ORDERS " where orders_id = '" . (int)$oID "'");
    
$order_exists true;
    if (!
tep_db_num_rows($orders_query)) {
      
$order_exists false;
      
$messageStack->add(sprintf(ERROR_ORDER_DOES_NOT_EXIST$oID), 'error');
    }
//end if !numrows
  
}//end if action == edit

  # Inculde the correct order class
  
include(DIR_WS_CATALOG_CLASSES 'order.php');



//begin standard HTML header output, and JS functions
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET?>">
<title><?php echo 'TITLE' ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">

<!-- Rich Javascript Functions --->

<script language="javascript" src="includes/general.js"></script>
<script language="JavaScript" type="text/javascript"> 
<!--  
function confirm_delete(my_var, order_id){ 
var my_query=my_var;
var my_order=order_id;
if (confirm('Are You Sure you want to Delete Comment '+my_query+''))
    { 
        <?php echo'location.replace("'."orders.php?$pid&order_select_id=".'"+my_query+"'."&oID=".'"+my_order+"'."&action=delete_comment" .'");'?>
    } 
else 
    {
        return;

    } 

}

function openaltedit(my_var){
    var popurl=my_var;
    winpops=window.open(popurl,"","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=375,height=325"); 
}
// --> 


function popupDetail(rowID) {
     
    //var query=document.getElementById(rowID).getAttribute('value');
    var query=rowID;
    var url='http://half.spreerewards.com/admin/manual_product_info.php?products_id='+query;

 if(query=='')
     {
        window.alert("Please Enter An Item Value First");
    }
 else
     {
    
        window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=500,height=500,screenX=150,screenY=150,top=150,left=150')
    
    }
  

}

function Toggle( secid )
{
    var sectionId = document.getElementById(secid);
    if (sectionId == null) return;
    if (sectionId.style.display == '')
    {
        sectionId.style.display = 'none';
        var ImgSrc = document.getElementById("i" + secid);
        ImgSrc.src = "images/plus.gif";
    }
    else
    {
        sectionId.style.display = '';
        var ImgSrc = document.getElementById("i" + secid);
        ImgSrc.src = "images/minus.gif";
    }
}


// this controls display
function Hide( obj )
{
    var oDiv = document.getElementById(obj);
    if(oDiv != null) oDiv.style.display = "none";
}

function startA(id)
{
    document.write('<a href="javascript:Toggle(\'' + id + '\')" style="text-decoration:none;">');
}

function endA()
{
    document.write('</a>');
}

function writePM(id)
{
    var isPF = (typeof(IsPrinterFriendly) != "undefined");
    document.write('<a href="javascript:Toggle(\'s' + id + '\')"><img width="9" height="9" border="0" id="is' + id + '" src="images/'+(isPF?'minus':'plus')+'.gif"></a>');
}

function chkHide(id)
{
    var isPF = (typeof(IsPrinterFriendly) != "undefined");
    if(document.getElementById && !isPF){ Hide(id); }
}

function chkrefundHide(id)
{
      var ref = document.getElementById(id);
    if(ref != null) ref.style.display = "none";
}

function do_qty(row,qty,check)
{
    if(eval('ordered_products.'+check+'.checked==true'))
    {//alert("Defaulted to Quanity Ordered");
    document.getElementById(row).value=qty;
    }
    else
    {
    document.getElementById(row).value='';
    }
    
}

function popupDetail(rowID) {
     
    //var query=document.getElementById(rowID).getAttribute('value');
    var query=document.getElementById(rowID).value;
    var url='http://half.spreerewards.com/admin/manual_product_info.php?products_id='+query;

 if(query=='')
     {
        window.alert("Please Enter An Item Value First");
    }
 else
     {
    
        window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=500,height=500,screenX=150,screenY=150,top=150,left=150')
    
    }
  

}

function popurl(url)    {
window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=800,screenX=150,screenY=150,top=150,left=150')
}


function approve_confirm(){
    if (confirm('Are You Sure you want To Approve This Order <?php echo $oID?>'))
        { 
            <?php echo'location.replace("'."orders.php?&oID=".$oID."&action=approve" .'");'?>
            return;
        } 
    else 
    {
            return false;;
    } 
}

function validate_deny() {
    var errors = '';

        if (document.deny.comments.value=='')
        {
            errors += "- Comments are required to deny an order.\n";
        }
              
        if (document.deny.status.options[document.deny.status.selectedIndex].value =='1')
        {
            errors += "- Please Select and Issue Type.\n";
        }

      
 if (errors != '') {
        alert('The following error(s) occurred:\n'+errors);
        subFlag = 0; 
    }

if (errors == '')
    {
        return confirm("Are You Sure You Want To Deny This Order?");
    }
   
  return (errors == '');

}
</script>

<?php if(isset($add_pressed)) { ?>
<script language="javascript">
    var oDiv = document.getElementById('sdrop1');
    if(oDiv != null) oDiv.style.display = "block";
</script>
<?php ?>

<?php if(isset($charge_pressed)) { ?>
<script language="javascript">
    var oDiv_charge = document.getElementById('sdrop5');
    if(oDiv_charge != null) oDiv_charge.style.display = "block";
</script>
<?php ?>

<?php if(isset($refund_pressed)) { 
$div_to_open=$HTTP_POST_VARS['div_to_open'];
?>

<script language="javascript">
    var oDiv_refund = document.getElementById('<?php echo $div_to_open?>');
    if(oDiv_refund != null) oDiv_refund.style.display = "block";
</script>

<script language="javascript">
    var oDiv_refund_head = document.getElementById('sdrop3');
    if(oDiv_refund_head != null) oDiv_refund_head.style.display = "block";
</script>
<?php ?>

<!-- // Rich Javascript Functions --->
</head>

<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- widget must be included after body object created -->
<script language="JavaScript1.2" type="text/javascript" src="includes/widget/widget.js"></script>

THE BODY CODE FRAGMENT HAS BEEN STRIPPED FOR THIS EXAMPLE

</body>
</html>
<?php require(DIR_WS_INCLUDES 'application_bottom.php'); ?>