<?php
/*
    Freeway eCommerce
    http://www.openfreeway.org
    Copyright (c) 2007 ZacWare
    
    Released under the GNU General Public License
*/
	define('_FEXEC',1);
	require('includes/application_top.php');
	require(DIR_WS_INCLUDES . '/tweak/general.php');
	frequire($FSESSION->language.'/customers_orders.php',RLANG);
	frequire($FSESSION->language.'/customers_orders_refund.php',RLANG);
	

		//delete/restore tables - array
		//pop them into an array - this makes adding new tables in later easier
		$table_array=array();
		$table_array[]='orders';
		$table_array[]='orders_products';
		$table_array[]='orders_status_history';
		$table_array[]='orders_total';
		//$table_array[]='orders_products_attributes';
		$table_array[]='payment_response';
		//$table_array[]='paypalipn_txn';
		$table_array[]='coupon_redeem_track';
		$table_array[]='refunds';
		$table_array[]='customers_basket';
		$table_array[]='customers_temp_basket';
		
		if (table_exists('orders_tickets'))
					{
			$table_array[]='orders_tickets';
					}	
		
		if (table_exists('orders_barcode'))
					{
			$table_array[]='orders_barcode';
					}
		
		if (table_exists('stripe_data'))
					{
			$table_array[]='stripe_data';
					}
		if (table_exists('email_data'))
					{
			$table_array[]='email_data';
					}
		
//jump in here looking for the $_POST
//delete	
	if ($_POST['delete_all']=='YES' && $_POST['wipe_all']=='wipe_all'){		
		foreach($table_array as $k=>$v){
				//(1) Create the backup tables if not exist
		          tep_db_query("create table if not exists bax_".$v." like ".$v);
				//(2)wipe them
				  tep_db_query("truncate bax_".$v);
                //(3) copy over
                  tep_db_query("insert into bax_".$v." select * from ".$v);
                //(4) truncate originals
		          tep_db_query("truncate ".$v);
		//end the delete all orders loop
		}
		//create a session to hold the undelete option
		$_SESSION['order_restore']='YES';
		}
	
//undo the delete this leaves both tables identical
    	if ($_POST['restore_all']=='YES' && $_POST['unwipe_all']=='unwipe_all'){		
		foreach($table_array as $k=>$v){
				//(1) Create the backup tables if not exist
		          //tep_db_query("create table if not exists bax_".$v." like ".$v);
				//(2)wipe them
				  tep_db_query("truncate ".$v);
                //(3) copy over
                  tep_db_query("insert into ".$v." select * from bax_".$v);
                //(4) truncate originals
		          //tep_db_query("truncate ".$v);
		//end the delete all orders loop
		}
		}
		
	// ############################################################################
	function table_exists($tablename, $database = false)
					{
					$res = tep_db_query("
         SHOW TABLES IN " . DB_DATABASE . " LIKE '$tablename'
        ");
					if (tep_db_num_rows($res) < 1)
						{
						return 0;
						}
					  else
						{
						return 1;
						}
					}	
		
	
	frequire('currencies.php',RCLA);
	$currencies = new currencies();
	
	//kill any referrer session
	 if ($FSESSION->is_registered('the_referrer')) {
	 $FSESSION->remove('the_referrer');}

	$LANGUAGES=tep_get_languages();

	$CUSTORD=&instance::getTweakObject('display.customersOrders');
	$CUSTORD->pagination=true;
	checkAJAX('CUSTORD');

	$FSESSION->set("AJX_ENCRYPT_KEY",rand(1,10));
	$jsData->VARS["page"]=array('lastAction'=>false,
								'opened'=>array(),
								'locked'=>false,
								'NUlanguages'=>$LANGUAGES,
								'imgPath'=>DIR_WS_IMAGES,
								"menu"=>array(),
								'link'=>tep_href_link('customers_orders.php'),
								'searchMode'=>false,
								'AJX_KEY'=>$FSESSION->AJX_ENCRYPT_KEY,
								'crypted'=>$ENCRYPTED,
								'alterRows'=>true);
	$jsData->VARS["page"]["template"]=array("TEXT_DELIVERED_ID"=>TEXT_DELIVERED_ID,
											"ERROR_EMPTY_SHIPPING_DATE"=>ERROR_EMPTY_SHIPPING_DATE,
											"TEXT_LOADING"=>TEXT_LOADING_DATA,
											"IMAGE_DELETE_MANUFACTURER"=>IMAGE_DELETE_MANUFACTURER,
											"INFO_SEARCHING_DATA"=>INFO_SEARCHING_DATA,
											"INFO_LOADING_DATA"=>INFO_LOADING_DATA,
											"ERROR_EMPTY_AMOUNT"=>ERROR_EMPTY_AMOUNT,
											"ERROR_EMPTY_RESTOCK_CHOICE"=>ERROR_EMPTY_RESTOCK_CHOICE,
											"ERR_CHOICE_EMPTY"=>ERR_CHOICE_EMPTY,
											"ERR_AMOUNT_EMPTY"=>ERR_AMOUNT_EMPTY,
											"ERR_REFUND_AMOUNT"=>ERR_REFUND_AMOUNT,
											"ERR_PERCENTAGE_VALUE"=>ERR_PERCENTAGE_VALUE
											
											);

	$jsData->VARS["page"]["NUmenuGroups"]=array("normal","update","refund");
    $display_order_id=$FREQUEST->getvalue('oID','int',0);
    $page='';

         if($display_order_id>0)
        {
         $jsData->FUNCS[]="doDisplayAction({'id':" . $display_order_id . ",get:'EditCustomerOrder','result':doDisplayResult,'type':'custord','params':'oID=" . $display_order_id . "','style':'boxRow'})";
         $orders_ids_query=tep_db_query("select o.orders_id   from " . TABLE_ORDERS . " o left join " . TABLE_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_ORDERS_STATUS . " s, " .TABLE_ORDERS_PRODUCTS." op, ".TABLE_CUSTOMERS ." c where o.customers_id=c.customers_id and o.orders_status = s.orders_status_id and o.orders_id=op.orders_id and  s.language_id = '" . (int)$FSESSION->languages_id . "' and ot.class = 'ot_total' group by o.orders_id  order by o.orders_id DESC");
         $i=0;
          while($orders_ids_array=tep_db_fetch_array($orders_ids_query))
            {
                $count_orders_ids_query=tep_db_query("select orders_id from ".TABLE_ORDERS." where orders_id >=".$display_order_id." and orders_id='".$orders_ids_array['orders_id']."'");
                while($count_orders_ids_array=tep_db_fetch_array($count_orders_ids_query))
                {
                if($count_orders_ids_array['orders_id']>0)$i++;
                }
            }
            

         $page=(int)($i/MAX_DISPLAY_SEARCH_RESULTS)+ (($i % MAX_DISPLAY_SEARCH_RESULTS)>0? 1 :0);

        }
     /* if($display_order_id>0)
     
        $jsData->FUNCS[]="doDisplayAction({'id':" . $display_order_id . ",get:'EditCustomerOrder','result':doDisplayResult,'type':'custord','params':'oID=" . $display_order_id . "','style':'boxRow'})";*/

        
        tep_get_last_access_file();
?>
<!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">
<script language="javascript" src="includes/general.js"></script>
<script language="javascript" src="includes/http.js"></script>

<script language="javascript" src="includes/jquery-1.10.2.js"></script> <!-- Added By R -->

<script language="javascript" src="includes/date-picker.js"></script>
<script type="text/javascript" src="includes/aim.js"></script>
<script type="text/javascript" src="includes/tweak/js/ajax.js"></script>
<script type="text/javascript" src="includes/tweak/js/customersOrders.js"></script>
<script type="text/javascript">

$(function() {
    var limit = 4;
$('input.ordchkcls').on('change', function(evt) {
   if($("input[name='ord_status[]']:checked").length > limit) {
       this.checked = false;
	   alert('Quick order update limited to '+limit+' orders');
   }
});
});

</script>
<script type="text/javascript">

function doOrderBy(action)
{
	//alert(action.type+'  '+action.get+'  '+action.params+' '+action.message);
	//if (page.locked || (action.get!='Search' && page.searchMode)) return;
		if (action.closePrev && !closePreviousOpened(action)) return;
		checkMessageDisplay(action);
		page.lastAction=action;
		
			do_get_command(page.link+'?AJX_CMD='+action.get+'&order='+action.params+'&value='+action.value+'&search='+action.searchparam+'&filter='+action.filter);

}

function doPageAction1(action)
	{
		
		
		if (action.closePrev && !closePreviousOpened(action)) return;
		checkMessageDisplay(action);
		page.lastAction=action;
		do_get_command(page.link+'?AJX_CMD='+action.get+'&'+action.params+'&order='+action.orderby+'&value='+action.value+'&search='+action.search+'&filter='+action.filter+'&cID='+action.cID+'&search_word='+action.search_word);
		
	}

 function doPageAction2(action)
	{


		if (action.closePrev && !closePreviousOpened(action)) return;
		checkMessageDisplay(action);
		page.lastAction=action;
		do_get_command(page.link+'?AJX_CMD='+action.get+'&'+action.params);

	}
function showHide() {
    var showme= document.getElementById('showme');
    showme.style.display = (showme.style.display == 'none') ? 'block' : 'none';
}		

function validateMyForm() {
    var x = document.forms["myForm"]["delete_all"].value;
    if (x == null || x == "" || x !== "YES") {
        alert("Please enter YES to delete all records");
        return false;
    }
     return confirm('Are you really sure?')
}
function validateMyForm2() {
    var x = document.forms["myForm2"]["restore_all"].value;
    if (x == null || x == "" || x !== "YES") {
        alert("Please enter YES to restore all records");
        return false;
    }
     
}
// Added By R
function updateord()
	{
        var ordstr = '';
        $('.ordchkcls').each(function() {
            if($(this).is(':checked') == true)
                {
                    //alert($(this).val());
                    ordstr += $(this).val() + ",";
                }
            //$(this).prop("checked", all.prop("checked"));

        });
        if(ordstr == '')
        {
            alert("<?php echo TEXT_AT_LEAST; ?>");
            return false;
        }
        jQuery.ajax({
		type: "POST",
		data: "actval=updateordsta&ordid="+ordstr,
		url: "edit_orders.php",
		success: function(response){
		//console.log(response);
                if(response == 'Sucess')
                {
                    jQuery('#display-alert-msg').remove();
                    jQuery('<div id="display-alert-msg"></div>').appendTo('body');
                    jQuery('#display-alert-msg').removeClass('');
                    jQuery('#display-alert-msg').html('<?php echo ORDER_UPDATE_SUCCESS; ?>');
                    jQuery('#display-alert-msg').addClass('notify_label alert-success');
                    jQuery('.alert-success').slideDown().delay(2000).slideUp();
                    setInterval("location.href = 'customers_orders.php'",3000);
                }
		//var result =jQuery.parseJSON(response);
		//jQuery("#basecurrency").val(result['basecurrency']);
		//jQuery("#clientadd").show();
		//jQuery("#clientadd").html("<label >Address : </label><br>"+result['clientaddress']+"<br>"+result['state']+","+result['city']+","+result['zipcode']+"<br>"+result['countryname']);
		
		
	},
		complete: function(){
				console.log( "AJAX - complete()" );
				//hideLoadingBar();
		}
	});
        //alert(ordstr);
        //do_get_command(page.link+'?AJX_CMD='+action.get+'&'+action.params);
		/*if (action.closePrev && !closePreviousOpened(action)) return;
		checkMessageDisplay(action);
		page.lastAction=action;
		do_get_command(page.link+'?AJX_CMD='+action.get+'&'+action.params);*/
return false;
	}
</script>
<style>/* New CSS added for Error */
.notify_label{
		margin-bottom: 8px;
		padding: 8px 35px 8px 14px;
		position:fixed;
		display:none;
    	text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
		z-index:10000;
		top:0%;
		left:30%;
		width:50%;
		text-align:center;
	}


.alert-success {
    background-color: #DFF0D8;
    border-color: #46886A;
    color: #468847;
}

.success{background:#d8f59f}

.errormsg{background:#faa}
.warningmsg{background:#fff2aa}</style>
		</head>
		<body marginwidth="0"  marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onLoad="javascript:pageLoaded();">
			<!-- header //-->
			<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
			<!-- header_eof //-->
			<div style="font-size:14px;border: 1px solid red;padding:3px;width:950px;height:20px;"><strong>Use Box Office at the front-end to create orders or directly adjust orders Admin>Orders>Edit</div>
			<?php if(MODULE_PAYMENT_PAYPALIPN_STATUS=='True'){
						if(MODULE_PAYMENT_PAYPALIPN_ID !=SECURE_OWNER_EMAIL_ADDRESS){
							echo "<h3 class='red'>ALERT!! Paypal Email has been changed! without authorization. Paypal has been disabled</h3>";
						}

						?>
					<div style="font-size:16px;border: 0px solid red;padding:3px;width:99%;height:20px;">
					<strong>PayPal ID: </strong>
					<?php echo MODULE_PAYMENT_PAYPALIPN_ID ?><?php 
					if(MODULE_PAYMENT_PAYPALIPN_ID !=SECURE_OWNER_EMAIL_ADDRESS){
					echo ' (' .SECURE_OWNER_EMAIL_ADDRESS . ')';
					}
					?></div>
					<?php } ?>
			<!-- body //-->
			<table border="0" width="100%" cellspacing="2" cellpadding="2">
				<!-- body_text //-->
				<tr>
				<td valign="top">
				<table border="0" width="100%" cellspacing="0" cellpadding="2">
					<tr>
						<td valign="top">
						<table border="0" cellpadding="0" cellspacing="0" width="100%">
							<tr>
								<td class="main">
									<b><?php echo HEADING_TITLE;?></b>
								</td>
								<td class="main">
									<?php 
								  $orders_statuses = array();
								  $orders_status_array = array();
								  $orders_statuses=tep_get_orders_status();
								  //March 2014 new search array
								  $orders_search=array();
								  //add in the fields you want to search here
								  //tie into the code in includes/tweak/customersOrders.php
								  //in function doGetCustomersOrders()
								  //$orders_search[]=array('id' => 1, 'text'=>'Order ID');
								  
								  $orders_search[]=array('id' => 2, 'text'=>TEXT_CUSTOMER_NAME);
								  $orders_search[]=array('id' => 3, 'text'=>TEXT_SHOW_NAME);
								  $orders_search[]=array('id' => 4, 'text'=>TEXT_SEAT_NUMBER);
								  $orders_search[]=array('id' => 5, 'text'=>'Reference ID');
								  $orders_search[]=array('id' => 6, 'text'=>'Billing Name');
								  $orders_search[]=array('id' => 7, 'text'=>'Products ID');
								  $orders_search[]=array('id' => 8, 'text'=>'Date ID');

								  //end new code
								  echo TEXT_SEARCH . '&nbsp;'. tep_draw_input_field('psearch','','onkeyup="javascript:check_key(event)"').
								  '&nbsp;'.TEXT_SEARCH_IN.
								   tep_draw_pull_down_menu('filter_search', array_merge(array(array('id' => '1', 'text' => "Order ID")), $orders_search), '','').'
								  &nbsp;
								  <a href="javascript:void(0)" onClick="javascript:doOrderSearch(\'\');">' . tep_image(DIR_WS_IMAGES . 'icons/bar_search.gif',IMAGE_SEARCH,'','','align=absmiddle') . '</a>
								  &nbsp;&nbsp;'. 'Status ' . ' ' . tep_draw_pull_down_menu('filter_status', array_merge(array(array('id' => '', 'text' => TEXT_ALL_ORDERS)), $orders_statuses), '', "onChange=javascript:doFilterOrders();");?>
								  </td>
								  <td><table border="0" cellpadding="0" cellspacing="5" width="100%"><tr><td>
								    <?php echo DELETE_ALL_ORDERS; ?>
								     <input type="checkbox" onChange="showHide()" />
								</td></tr></table></td>
							</tr></table>
							<table>	
							<tr>
								<td><?php //delete all orders?>
							
							<table></td>
								<td id="showme" class="main" style="display: none" >
								   <form name="myForm" action="" onSubmit="return validateMyForm()" method="post"> 
									<br/>
									<?php echo TEXT_DELETE_ALL_ORDERS; ?> &nbsp;&nbsp;
									<input name="delete_all" id="delete_all" size="4" type="text"> &nbsp;&nbsp;
									<input type="submit" value="Delete">
									<input type="hidden" value="wipe_all" name="wipe_all" />
			                        </form>
								</td>
							</tr>
						<?php //undelete all orders option
						   if($_SESSION['order_restore']=='YES'){
						   	 //once only option
						   	  unset($_SESSION['order_restore']);
					     ?>
							<tr>
								<td></td>
								<td id='' class="main"  >
								   <form name="myForm2" action="" onSubmit="return validateMyForm2()" method="post"> 
									<br/>
									 <?php echo TEXT_ALL_ORDERS_DELETED; ?>&nbsp;&nbsp;
									<input name="restore_all" id="restore_all" size="4" type="text"> &nbsp;&nbsp;
									<input type="submit" value="Restore">
									<input type="hidden" value="unwipe_all" name="unwipe_all" />
			                        </form>
								</td>
							</tr>
							
						  <?php  }?>
						
						</table>
							<table border="0" cellpadding="0" cellspacing="0" width="100%">
							<tr>
							
                                <td height="30"><input type="button" name="updateord" value="<?php 
								if(EMAIL_QUICK_ORDER_UPDATE=='true')
								{
									echo QUICK_ORDER_UPDATE_EMAIL;
								}else
								{
									echo QUICK_ORDER_UPDATE ;
								}
								
								?>" onClick="updateord();" ></td>
							</tr>
							</table>
						</td>
					</tr>
				</table>
				</td>
			</tr>
				<tr height="20" id="messageBoard" style="display:none">
					<td id="messageBoardText">
					</td>
				</tr>
				<tr>
					<td class="main" id="custord-1message">
					</td>
				</tr>
				<tr>
					<td >
						<table border="0" cellpadding="0" cellspacing="0" width="100%">
							<tr>
								<td id="custordtotalContentResult">
								<?php $CUSTORD->doGetCustomersOrders($page);?>
								</td>
							</tr>
						</table>	
					</td>
				</tr>
				<tr style="display:none">
					<td id="ajaxLoadInfo"><div style="padding:5px 0px 5px 20px" class="main"><?php echo TEXT_LOADING . '&nbsp;' . tep_image(DIR_WS_IMAGES . 'layout/ajax_load.gif');?></div></td>
				</tr>
				<tr>
					<td id="ajaxLoadImage" style="display:none">
						<?php echo tep_image(DIR_WS_IMAGES . 'layout/ajax_load.gif');?>
					</td>
				</tr>
				<div class="ajxMessageWindow" id="ajxLoad" style="display:none;width:400px;height:70px;"><span id="ajxLoadMessage"><?php echo TEXT_LOADING_DATA; ?></span><br><?php echo tep_image(DIR_WS_IMAGES . 'layout/ajax_load.gif');?></div>
			</table>	
			<!-- body_eof //-->
			<!-- footer //-->
				<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
			<!-- footer_eof //-->
		</body>
	</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php');?>
