<?php
/*
  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from Zac
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
  	require(DIR_WS_CLASSES . 'currencies.php');
  	$currencies = new currencies();
	include(DIR_WS_CLASSES . 'order.php');
	$server_date = getServerDate();
	$server_date1=getServerDate(true);
	$oID=(isset($HTTP_GET_VARS['oID'])?(int)$HTTP_GET_VARS['oID']:'');
	$preturn=(isset($HTTP_GET_VARS['preturn'])?$HTTP_GET_VARS['preturn']:'');
	$command=(isset($HTTP_GET_VARS['command'])?$HTTP_GET_VARS['command']:'');
	$order = new order($oID);
	tep_get_last_access_file();
	$chk_type=(isset($HTTP_POST_VARS['chk_type'])?$HTTP_POST_VARS['chk_type']:'F');
	$chk_choice=(isset($HTTP_POST_VARS['chk_choice'])?$HTTP_POST_VARS['chk_choice']:'A');
	$txt_amount=(isset($HTTP_POST_VARS['txt_amount'])?(float)$HTTP_POST_VARS['txt_amount']:0);
	$chk_advise=(isset($HTTP_POST_VARS['chk_advise'])?$HTTP_POST_VARS['chk_advise']:'N');
	$refund_comments=(isset($HTTP_POST_VARS['refund_comments'])?$HTTP_POST_VARS['refund_comments']:'N');
	$status_query=tep_db_query("select orders_status_id from " . TABLE_ORDERS_STATUS . " where lower(orders_status_name)='refunded'");
	$status_result=tep_db_fetch_array($status_query);
	$refund_query=tep_db_query("select sum(rf.refund_amount)  as refund_amount, o.orders_status from " . TABLE_ORDERS . " o, " . TABLE_REFUNDS . " rf where rf.orders_id=o.orders_id and o.orders_id='" . (int)$oID . "' group by rf.orders_id");
	$refund_result=tep_db_fetch_array($refund_query);
	$order_total_query=tep_db_query("select value from " . TABLE_ORDERS_TOTAL . " where orders_id='" . (int)$oID ."' and class='ot_total'");
	$order_total_result=tep_db_fetch_array($order_total_query);
	$order_total_amount=$order_total_result['value'];
	/*for ($i = 0, $n = sizeof($order->totals); $i < $n; $i++) {
			if(strtolower($order->totals[$i]['title']) ==strtolower('total:')){
				$order_total_amount=$order->totals[$i]['text'];
				break;
			}
	}
	$tamount=substr($order_total_amount,4);
	$order_total_amount=substr($tamount,0,-4);
	echo "select  thousands_point from " . TABLE_CURRENCIES . " where code='" . DEFAULT_CURRENCY . "'";
	$currencies_query = tep_db_query("select  thousands_point from " . TABLE_CURRENCIES . " where code='" . DEFAULT_CURRENCY . "'");
	$currencies_result=tep_db_fetch_array($currencies_query);
	$order_total_amount=str_replace($currencies_result['thousands_point'],'',$order_total_amount);*/
	$order_total_amount=$order_total_amount-$refund_result['refund_amount']	;
	if($command!=''){
		echo $command . '{}' . $oID . '||' . $preturn . '||';
		switch($command){
			case 'save':
				$notify='0';
				 for ($i = 0, $n = sizeof($order->totals); $i < $n; $i++) {
					if(strtolower($order->totals[$i]['title']) ==strtolower('total:')){
						$order_amount=$order->totals[$i]['text'];
						break;
					}
				}				
				if($chk_choice=='A')
					$amount=$currencies->format($txt_amount);
				else if($chk_choice=='%'){
					$amount=$currencies->format((($txt_amount) * ($order_total_amount))/100) . " (" . $txt_amount . $chk_choice . ") " ; 
					$txt_amount=(($txt_amount) * ($order_total_amount))/100;
				}
				if($chk_type=='F') { 
					$type=TEXT_FULLY;
					$amount=$order_amount;
					$txt_amount=$order_total_amount;
					$chk_choice='';
				}else $type=TEXT_PARTIALLY;
				if($chk_type=='F')
					$rcomments='Fully Refunded on ' . format_date($server_date) . ". Refund Amount: " . $amount . ". " . $refund_comments;
				else if($chk_type=='P')
					$rcomments='Partial Refund on ' . format_date($server_date) . ". Refund Amount: " . $amount . ". " . $refund_comments;			
				if($txt_amount=='') $txt_amount=0;
				$order_pid=(isset($HTTP_POST_VARS['opid'])?$HTTP_POST_VARS['opid']:'');
				$parray=split(",",$order_pid);
				if($order->info['total']>0) {
				$sql_array=array('orders_id' =>$oID,
									'customers_id' =>$order->customer['id'],
									'refund_type' =>$chk_type,
									'amount_type' =>$chk_choice,
									'refund_amount' => $txt_amount,
									'comments' => $refund_comments,
									'date_created' => $server_date1);
									tep_db_perform(TABLE_REFUNDS,$sql_array);
										
				if($chk_advise=='Y'){
					$notify='1';
					$details['to_name']=$order->customer['name'];
					$details['to_email']=$order->customer['email_address'];
					$details['from_name']=STORE_OWNER;
					$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
					$details['subject']='Order Amount Refund';
					$details["html_text"]='Order Amount Refunded'."<br>".TEXT_ORDER_AMOUNT. $order_amount ."<br>". TEXT_REFUND_TYPE .$type . '<br>' .  TEXT_REFUND_AMOUNT . $amount . '<br>' . $refund_comments;
					tep_send_email($details,true);
				}
			if($chk_type=='F'){
					tep_db_query("update " . TABLE_ORDERS . " set orders_status='" .(int)$status_result['orders_status_id'] . "' where orders_id ='" .(int)$oID . "'");
					if($HTTP_POST_VARS['is_restock']=='Y'){
					  for($jcnt=0;$jcnt<sizeof($parray);$jcnt++){
						if($HTTP_POST_VARS['chk_restock' . $parray[$jcnt]]=='Y'){
							$restock_id.=$parray[$jcnt] . ",";
							$events_query=tep_db_query("select products_type,orders_id ,products_quantity,products_id,orders_products_id from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id='" . $parray[$jcnt] . "'");
							$events_result=tep_db_fetch_array($events_query);
							if($events_result['products_type']=='E'){
								tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set events_type='' ,orders_products_status='" . $status_result['orders_status_id'] . "' where orders_id ='" . (int)$oID . "' and products_type='E'");
							} else {
								if($events_result['products_type']=='P')
									products_restock($events_result);
									tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status='" . (int)$status_result['orders_status_id'] . "' where orders_products_id ='" . (int)$parray[$jcnt] . "'");
							}
						}
					  }
				   }
			} else if($chk_type=='P') {
				if($HTTP_POST_VARS['is_restock']=='Y'){
				for($jcnt=0;$jcnt<sizeof($parray);$jcnt++){
					if($HTTP_POST_VARS['chk_restock' . $parray[$jcnt]]=='Y'){
						$restock_id.=$parray[$jcnt] . ",";
						$events_query=tep_db_query("select products_type,orders_id ,products_quantity,products_id,orders_products_id from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id='" . (int)$parray[$jcnt] . "'");
						$events_result=tep_db_fetch_array($events_query);
						if($events_result['products_type']=='E'){
							events_restock($events_result);
						} else {
							if($events_result['products_type']=='P')
								products_restock($events_result);
								tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status='" . (int)$status_result['orders_status_id'] . "' where orders_products_id ='" . (int)$parray[$jcnt] . "'");
						}
					}	
				}				
				$query=tep_db_query("select orders_products_id,products_name,products_id , products_type  from " . TABLE_ORDERS_PRODUCTS . " where orders_id='" . (int)$oID . "'  and orders_products_status!='5'");
				if(tep_db_num_rows($query)<=0)
					tep_db_query("update " . TABLE_ORDERS ." set orders_status='" . (int)$status_result['orders_status_id'] . "' where orders_id='" . (int)$oID . "'");
				}	
			}
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set events_type='F' where orders_id='" . (int)$oID ."'");
			tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY ." (orders_id,orders_status_id,date_added,customer_notified,comments,user_added) values('" . $oID . "','" . $status_result['orders_status_id'] . "','" .$server_date1 . "','" . $notify ."','" . $rcomments . "','') " );
			} else{
				 echo '<table cellpadding="3" cellspacing="5" border="0" width="80%" align="center"><tr><td class="main">Cannot Refund. Because the Order Amount is: ' . $order_amount . '<td><tr><tr><td>' . tep_draw_separator('pixel_trans.gif','10','10'). '</td></tr></table>';
			} 
			break;
		}
		exit;
	}						
		
?>
<!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/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script language="javascript" src="includes/http.js"></script>
<script>
var oid='<?php echo $HTTP_GET_VARS['oID'];?>';
var preturn='<?php echo $HTTP_GET_VARS['preturn'];?>';
var page='<?php echo $HTTP_GET_VARS['page'];?>';

var total_amount='<?php echo $order_total_amount;?>';

var status='<?php echo $order->info['orders_status'];?>';
    var img_src="<?php echo HTTP_SERVER.DIR_WS_ADMIN.'images/';?>";
	function do_action(){ 
		var frm=document.refund;
		for(i=0;i<frm.chk_type.length;i++){
			if(frm.chk_type[i].checked){
				if(frm.chk_type[i].value=='P')
					document.getElementById('choice').style.display="";
				else{
					document.refund.txt_amount.value='';
				    document.getElementById('choice').style.display="none"	;
				 }
			}
		}		
	}
	
	function do_page_fetch(id,action){ 
		var command='';
		var element=document.getElementById('img_edit');
		var head=document.getElementById('head_' + id);
		var data=document.getElementById('data_' + id);
		command='<?php echo tep_href_link(FILENAME_ORDERS_REFUND);?>' + '?command=' + action + '&oID=' + oid + '&preturn=' + preturn;
			
		switch(action){
			case 'close':
				document.getElementById('img_save').style.display="none";
				document.getElementById('close_refund').style.display="";
				document.getElementById('head_'+id).style.display="";
				document.getElementById('data_'+id).style.display="none";
				document.getElementById('data_'+id).innerHTML="";
				element.childNodes[0].src=img_src+'template/img_edit.gif';
				return;
			break;
			case 'close_refund':
				if(preturn=='co') {
					location.href="<?php echo FILENAME_ORDERS . '?expand=expand_orders'; ?>" + '&orders_page=' +page + '&orders_id=' + oid;
				} else if(preturn=='sr') {
					document.refund.action="<?php echo FILENAME_SEARCH_RESERVATIONS . '?expand=page_navigation'; ?>" ;
					document.refund.submit();
				}	
				return;
			break;
		}
		do_get_command(command);
	}
	
	function do_result(result){		
		var splt=Array(); 
		splt=result.split("{}");
		var spl_arr=Array();
		var sp1=splt[1]; 
		spl_arr=sp1.split("||");
		switch(splt[0]){
			case 'save':  //return;
				if(spl_arr[1]=='co') {
					document.refund.action="<?php echo FILENAME_ORDERS . '?expand=expand_orders'; ?>" + '&orders_page=' +page + '&orders_id=' + oid;
					document.refund.submit();
				} else if(spl_arr[1]=='sr') {
					document.refund.action="<?php echo FILENAME_SEARCH_RESERVATIONS . '?expand=page_navigation'; ?>" ;
					document.refund.submit();
				}	
			break;
		}
	}
	
	function ValidateForm(){ 
		var frm=document.refund;
		var value='';
		var value_choice='';
		var error_message='';
		if(status<=1)
			error_message+='* <?php echo 'Refund is not available for Pending orders';?>\n';
		else {	
		command='<?php echo tep_href_link(FILENAME_ORDERS_REFUND);?>' + '?command=save&oID=' + oid + '&preturn=' + preturn;
		for(i=0;i<frm.chk_type.length;i++){
			if(frm.chk_type[i].checked){
				value=frm.chk_type[i].value;
				}
		}  
		
		if(value=='')error_message+='* <?php echo ERR_CHOICE_EMPTY;?>\n';
		else if(value!='F'){
			for(i=0;i<frm.chk_choice.length;i++){
				if(frm.chk_choice[i].checked){
					choice_value=frm.chk_choice[i].value;
				}	
			}
			if(frm.txt_amount.value=='' || isNaN(frm.txt_amount.value) || (frm.txt_amount.value<=0))
				error_message+='* <?php echo ERR_AMOUNT_EMPTY;?>\n'	;
			else{
				 if(choice_value=='A'){ 
					if(parseFloat(frm.txt_amount.value)>=parseFloat(total_amount))
						error_message+='* <?php echo ERR_REFUND_AMOUNT;?>\n';
				} else {
					if(parseFloat(frm.txt_amount.value)>=parseFloat(100))
						error_message+='* <?php echo ERR_PERCENTAGE_VALUE;?>\n';
				}
				
			}	
		}
		if(document.getElementById('is_restock').checked){
			var sid=document.refund.opid.value;
			var sarray=Array();
			var sel_id=false;
			sarray=sid.split(',');
			for(i=0;i<sarray.length;i++){
				if(document.getElementById('chk_restock' + sarray[i]).checked)	
					sel_id=true;
			}
			if(!sel_id)
				error_message+='* Please select one of the restock item below. \n';
		}
	}
		
		if(error_message!='') {
			alert(error_message);
			return false;
		} else{
		 	do_post_command('refund',command);
			}
		return false;	
	}
     var display_flag=1;
	 function do_hover_change(element,eve){ 
		 var data=document.getElementById("data_" + oid); 
		 var head=document.getElementById("head_" + oid);
	  	 if(element){		   		    		    
		    var img_get_src=element.childNodes[0];
			if(img_get_src){
			    if(img_get_src.src==img_src+'template/img_edit.gif') {
					if(head && head.style.display=="" && eve==1 || eve==2){
					 	img_get_src.src=img_src+'template/img_edit_hover.gif';
					}  		   		 	 			 	 			
			    }else if(eve==3 && img_get_src.src==img_src+'template/img_edit_hover.gif' && data && data.style.display=="none") img_get_src.src=img_src+'template/img_edit.gif';
		  }
		 }		 
	 }  	
	 
	 function do_active() { 
	 	var stock_id=document.refund.opid.value;
		var sarray=Array();
	 	if(document.getElementById('is_restock').checked){ 
			sarray=stock_id.split(',');
			for(i=0;i<sarray.length;i++){
				//document.refund.elements['chk_restock'. sarray[i]].checked=false;
				document.getElementById('chk_restock'+ sarray[i]).disabled=false;
			}
		} else {
			sarray=stock_id.split(',');
			for(i=0;i<sarray.length;i++){
				document.getElementById('chk_restock'+ sarray[i]).checked=false;
				document.getElementById('chk_restock'+ sarray[i]).disabled=true;
			}
		}
	 }
	 
	 function change_amount_type(amount_type){
	   var amount_type_span=document.getElementById("amount_type");
	   if(amount_type_span){
	   	 if(amount_type=='A')
	  	    amount_type_span.innerHTML="&nbsp;$";
	     else
	     	amount_type_span.innerHTML="&nbsp;%";
	   }
	 }
</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onLoad="SetFocus();">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="5" cellpadding="4">
	<tr>
	<!-- body_text //-->
		<td>
			<table cellpadding="0" cellspacing="0" border="0" width="100%">
				<tr >
					<td> <?php echo tep_draw_form('refund',FILENAME_ORDERS_REFUND,'action=update&oID=' . $oID,'post',' onSubmit="return ValidateForm();"'); 
								/*if($preturn=='sr') { 
									$params=array("tx_fname","tx_lname","page","tx_words","tx_code",
															"tx_from","tx_until","tx_event","tx_reserve","tx_waitlist","tx_rtype","tx_session","tx_current","orders_id","events_id","tx_pending");
									$search_params=tep_prepare_hidden_params($params,"post","post");
									echo '<input type="hidden" name="booking_page" value="' . $HTTP_POST_VARS['page_1'] . '">';
								}	*/
					?>
						<table cellpadding="0" cellspacing="0" border="0" width="100%" class="openContent">
								<tr class="openContent_top">
									<td>
										<Table cellpadding="0" cellspacing="0" border="0" width="100%">
											<tr>
												<td class="pageHeading" width="300" ><?php echo tep_draw_separator('pixel_trans.gif','10','10'). ' Order Refund';?></td>
												<td align="right"><span  id="img_save" ><input type="image" id="save" src="images/template/img_savel.gif" alt="save" title="save" border="0">&nbsp;&nbsp;<a href="javascript:do_page_fetch('<?php echo $oID;?>','close_refund');"><img src="images/template/img_closel.gif"  id="close" alt="close" title="close" border="0"></a></span>
															<span id="close_refund" style="display:none"><a href="javascript:do_page_fetch('<?php echo $oID;?>','close_refund');"><img src="images/template/img_closel.gif"   alt="close" title="close" border="0"></a></span>&nbsp;&nbsp;</td>
											</tr>
										</Table>
									</td>
								</tr>			
								<tr>
									<td  class="dataTableContent">
										<table cellpadding="3" cellspacing="5" border="0" width="100%">
											<tr>
												<td width="150" valign="top" class="main"><?php echo TEXT_CUSTOMERS ;?></td>
												<td class="main" width="300"><?php echo $order->customer['name'];?></td>
												<td width="150" class="main" valign="top"><?php echo TEXT_ORDERID;?></td>
												<td class="main" valign="top"><?php echo $oID;?></td>
											</tr>
											<tr>
												<td width="150" class="main" valign="top"><?php echo TEXT_EMAIL;?></td>
												<td class="main" valign="top"><?php echo $order->customer['email_address'];?></td>
												<td class="main"><?php echo TEXT_ORDER_DATE_TIME;?></td>
												<td class="main"><?php echo date(EVENTS_DATE_FORMAT . ' h:i:s A',strtotime($order->info['date_purchased']));?></td>
											</tr>
											<tr>
												<td width="150" class="main"><?php echo TEXT_PAYMENT;?></td>
												<td class="main" width="300"><?php echo $order->info['payment_method'];?></td>
												<?php 
												 for ($i = 0, $n = sizeof($order->totals); $i < $n; $i++) {
													if(strtolower($order->totals[$i]['title']) ==strtolower('total:')){
												?>
													<td class="main"><?php echo $order->totals[$i]['title'];?></td>
													<td class="main"><?php echo $order->totals[$i]['text'];?></td>
												<?php  }
												} ?>
											</tr>
											<tr>
												<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','10','10');?></td>
												<td class="main"><?php echo 'Refundable Amount:'?></td>
												<td class="main"><?php echo $currencies->format($order_total_amount);?></td>
											</tr>
										</table>
									</td>	
								</tr>
								<tr>
									<td>
										<table cellpadding="2" cellspacing="5" border="0" width="80%" >
											<tr>	<td class="info_heading" colspan="2"><?php echo 'Details ' ;?></td></tr>
												<tr>
													<td>
														<table cellpadding="2" cellspacing="3" border="0" width="100%" style="padding-left:40px;">
											
								
									<?php		$dis_time_format="";
											if(defined('EVENTS_TIME_FORMAT'))
												$dis_time_format=EVENTS_TIME_FORMAT;
								
/*											$cart = new shoppingCart;
											$cart->load_products($oID);
																						
											$order = new order;
											$products=$cart->get_products();											
*/										
											
		    $products_ordered="";
		    $product_type="";
			$products_name="";
			$products = "";
			$products_names_p="";
			$pre_qty="";
			$pre_name="";
			$qty_p = "";
			$pre_sign="";
			$first_event = true;
			$first_event_id = 0;
			$jj=0;
			$attendees_name="";
			$sku="";
						
			for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
				$products_names_p="";
				$qty_p = "";
				$sign_p="";
				$model="";
			    $products_ordered_attributes="";
				if (isset($order->products[$i]['attributes']) && (sizeof($order->products[$i]['attributes']) > 0)) {
					for ($j = 0, $k = sizeof($order->products[$i]['attributes']); $j < $k; $j++) {
					  if($order->products[$i]['attributes'][$j]['option'] && $order->products[$i]['attributes'][$j]['value'])
					    $products_ordered_attributes .= "<br>&nbsp;&nbsp;&nbsp;&nbsp;- " .  $order->products[$i]['attributes'][$j]['option'] . ': &nbsp;' . $order->products[$i]['attributes'][$j]['value'];
					  if ($order->products[$i]['attributes'][$j]['price'] != '0') 
						  $products_ordered_attributes .= ' (' . $order->products[$i]['attributes'][$j]['prefix'] . $currencies->format($order->products[$i]['attributes'][$j]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')';
					}
				 }	 
				 
				 if (isset($order->products[$i]['others']) && (sizeof($order->products[$i]['others']) > 0)) {
					$disp_date=$order->products[$i]['others']['end_date'];
					$disp_time=$order->products[$i]['others']['end_time'];
					if($disp_date && $disp_time){
						$date_time=strtotime($disp_date.' '.$disp_time)+60;
						$disp_date=date('Y-m-d',$date_time); 
						$disp_time=date('h:i A',$date_time); 
					}
				 }
				 if($order->products[$i]['others']['start_time'] || $order->products[$i]['others']['end_time']) {
					 $disp_stime=date('h:i A',strtotime($order->products[$i]['others']['start_time']));
					if($dis_time_format!="") {
						if($dis_time_format=='24') {
							$disp_time=date('H:i',$date_time); 
							$disp_stime=date('H:i',strtotime($order->products[$i]['others']['start_time']));
						}	
					}
				}
				$products_ordered_attributes1="";
				if($order->products[$i]['others']['start_date'])
					$products_ordered_attributes1 .= "<br>&nbsp;&nbsp;&nbsp;&nbsp;- " . TEXT_START_DATE . ': &nbsp;&nbsp;' .  format_date($order->products[$i]['others']['start_date']) . '&nbsp;&nbsp;' . $disp_stime;
				if($order->products[$i]['others']['end_date'])
					$products_ordered_attributes1 .= "<br>&nbsp;&nbsp;&nbsp;&nbsp;- " . TEXT_END_DATE . ': &nbsp;&nbsp;&nbsp;&nbsp;' .  format_date($disp_date) . '&nbsp;&nbsp;' . $disp_time;
				if($order->products[$i]['others']['resource_name'])
					$products_ordered_attributes1 .= "<br>&nbsp;&nbsp;&nbsp;&nbsp;- " . TEXT_RESOURCE . ': &nbsp;&nbsp;&nbsp;&nbsp;' . $order->products[$i]['others']['resource_name'];

				if($order->products[$i]['products_type']=="E"){
				 $model="";
					if($order->products[$i]['model'])
					{
					  if($order->products[$i]['model']!=""){
					 	 $model.=$order->products[$i]['model'] . ",";
					  }
					}
				}	

				if(($pre_name!=$order->products[$i]['name']) && ($order->products[$i]['products_type']=="E")){
						$products_names_p = $order->products[$i]['name'] . "<br>" . tep_draw_separator('pixel_trans.gif','20','10');
						$pre_name=$order->products[$i]['name'];	
						$qty_p=$order->products[$i]['qty'];
						$pre_qty=$order->products[$i]['qty']; 
						$sign_p="X";
						$pre_sign="X";
				 }else if($order->products[$i]['products_type']=="V"){
				  $products_names_p = $order->products[$i]['name'];
				  $qty_p=$order->products[$i]['qty'];
				  $sign_p="X";
				  	  if($order->products[$i]['model'])
					  	$model= " , " . $order->products[$i]['model'];
				  }else if($order->products[$i]['products_type']=="S"){ 
				  $products_names_p = $order->products[$i]['name'];
				  $qty_p=$order->products[$i]['qty'];  
				  $sign_p="X"; 
					  if($order->products[$i]['model'])
					  	$model= " , " . $order->products[$i]['model'];
				  }else if($order->products[$i]['products_type']=="P"){ 
				  $products_names_p = $order->products[$i]['name'];
				  $qty_p=$order->products[$i]['qty'];
				  $sign_p="X";
				  	  if($order->products[$i]['model'])
					  	$model= " , " . $order->products[$i]['model'];
				  }
				
				$rax_total=tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'];
				$sku = $order->products[$i]['products_sku'];
				$event_id = 0;
				if($order->products[$i]['products_type']=='E'){
					$event_id = $order->products[$i]['event_id'];
					if($first_event){ 
						$first_event_id = $order->products[$i]['event_id'];
						$first_event = false;
					}
				} 
				$products[] = array( "qty" => $qty_p,
							   		 "sign"  => $sign_p,
									 "id" => $order->products[$i]['id'],
							  		 "products_type" => $order->products[$i]['products_type'],
							  		 "p_name"	 => $products_names_p,
							  		 "event_id" => $event_id,
							  		 "p_attributes1" => $products_ordered_attributes1, 
							  		 "p_attributes" => $products_ordered_attributes,
							  		 "model" => $model,
							  		 "sku" => $sku,
							 	     "row_total"=>$rax_total
								   ); 
		   }
		$session_dates = "";
		$event_id = $first_event_id;
		$date = array(); 
		
		$events_row_total = array();
		for ($i = 0, $n = sizeof($products); $i < $n; $i++) { 
			if(($products[$i]['products_type']=="E")){
				if($event_id!=$products[$i]['event_id']){
					$event_id=$products[$i]['event_id'];
					$session_dates = "";
				}
				$session_dates .= $products[$i]['model'];
				$date[$products[$i]['event_id']] = substr($session_dates,0,-1); 
				$events_row_total[$products[$i]['event_id']] += $products[$i]['row_total'];	
			} 
		} 
		$date_keys = array_keys($date);
		$date_keys_length = count($date_keys);
		for($i=0;$i<$date_keys_length;$i++){
			$final_date='';
			$var_date = $date[$date_keys[$i]];
			$date_split = split(',',$var_date);
			$date_split_count = count($date_split);
			
			for($j=0;$j<$date_split_count;$j++){
				$final_date.= format_date($date_split[$j]) .',';
				$m=$j+1;
			   if($m%4==0)	$final_date = substr($final_date,0,-1) . '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			}
			$date[$date_keys[$i]] = substr($final_date,0,-1);
		} 
		$event_id = 0;
		for ($i = 0, $n = sizeof($products); $i < $n; $i++) {
	   		 if($products[$i]['products_type']=="P"){
				$row_total= $products[$i]['row_total'];			
				$date=$products[$i]['model'];
			}else if($products[$i]['products_type']=="S"){
			    $row_total= $products[$i]['row_total'];
				   if($products[$i]['model']!="")
				    $date=$products[$i]['model'];	
			}else if($products[$i]['products_type']=="V"){
			    $row_total= $products[$i]['row_total'];
				   if($products[$i]['model']!="")
				   $date=$products[$i]['model'];
			}
			if($event_id!=$products[$i]['event_id'] || $products[$i]['products_type']!='E'){
				if($products[$i]['products_type']=='E'){ 
					$row_total = $events_row_total[$products[$i]['event_id']];
					$attendees_name="";
					if( ($products[$i]['qty'])>1 ){ 
						
						$attendee_query=tep_db_query("select distinct customers_firstname,customers_lastname from ".TABLE_CUSTOMERS ." c, ".TABLE_CUSTOMERS_TO_CUSTOMERS ." ctc where ctc.customer_id=c.customers_id and ctc.orders_id='".(int)$HTTP_GET_VARS['oID']."'");
						while($attendee_result=tep_db_fetch_array($attendee_query)){
							$attendees_name.=$attendee_result['customers_firstname'].' '.$attendee_result['customers_lastname'].',';
						}
				   }
			}
			 
			$model = "";
			if(($products[$i]['products_type']=="S")){
			   if($products[$i]['model']!="")
			     $model = "<br>&nbsp;&nbsp;&nbsp;&nbsp;Model:".substr($products[$i]['model'],2);
				 $sku="";
				 $attendees_name="";
		    }if(($products[$i]['products_type']=="P")){
			     if($products[$i]['model']!="")
			       $model = "<br>&nbsp;&nbsp;&nbsp;&nbsp;Model:".substr($products[$i]['model'],2)."<br>";	
				 if($products[$i]['sku']!="")
			       $sku = "&nbsp;&nbsp;&nbsp;&nbsp;SKU:&nbsp;&nbsp;".$products[$i]['sku']."";	
				   $attendees_name=""; 
			}
		    if( ($products[$i]['products_type']=="E") && ($products[$i]['qty'])>1 ) {
						if ($attendees_name!=""){
								$attendees_name='<br>' .'<small>' . '<b>Multiple Attendees</b>' . '</small>' . '<br>'.tep_draw_separator('pixel_trans.gif',35,1) .'-'.substr($attendees_name,0,-1);
						}
			}
			if(get_discount_details($oID,$products[$i]['id'])){
				$discount=  '<br>' . '<b>'. get_discount_details($oID,$products[$i]['id']); 
			}
			
			$event_id = $products[$i]['event_id'];
			$products_ordered.='<tr height="30">';
			$products_ordered.=' <td class="main" valign="top" width="30">' . "&nbsp;" . $products[$i]['qty'] . "&nbsp;&nbsp;" .'</td>' . "\n" ;
			if(($products[$i]['products_type']!="P")){
			$products_ordered.='<td class="main" width="80%"  valign="top">' . $products[$i]['p_name'] .  $products[$i]['p_attributes1'] . $products[$i]['p_attributes'] . $date[$event_id]  . $model . $sku . $attendees_name .  "</td>";
			} else {
			$products_ordered.='<td class="main" width="80%"  valign="top">' . $products[$i]['p_name'] .  $products[$i]['p_attributes1'] . $products[$i]['p_attributes'] . $model . $sku . $discount . "</td>";

			}
			$products_ordered.='<td class="main" align="right" valign="top">' . $currencies->format($row_total, true, $order->info['currency'], $order->info['currency_value']) . '</td>';
			$products_ordered.='</tr>';
		  }
	  } 												
											
/*										  for ($i=0, $n=count($order->products); $i<$n; $i++) {
											 
											echo '          <tr>' . "\n" .
												 '            <td class="main" align="right" valign="top" width="30">' . $order->products[$i]['qty'] . '&nbsp;</td>' . "\n" .
												 '            <td class="main" width="80%"  valign="top">' . $order->products[$i]['name'] ;
											 if ($order->products[$i]['element_type']=="V"){
												if($order->products[$i]['others']['end_date'] && $order->products[$i]['others']['end_time']){	
													$str_time=strtotime($order->products[$i]['others']['end_date'] .' '.$order->products[$i]['others']['end_time'])+60;
													$order->products[$i]['others']['end_date']=date('Y-m-d',$str_time);
													$order->products[$i]['others']['end_time']=date('H:i:s',$str_time); 
												} 
														$stime="";
														$etime="";
														if($order->products[$i]['others']['start_time']) {
															$stime=date("h:i A",strtotime($order->products[$i]['others']['start_time']));
															if($dis_time_format!="") {
																if($dis_time_format=='24') 
																$stime=date("H:i",strtotime($order->products[$i]['others']['start_time']));
															}
														}
														if($order->products[$i]['others']['end_time']) {
															$etime=date("h:i A",strtotime($order->products[$i]['others']['end_time']));
															if($dis_time_format!="") {
																if($dis_time_format=='24') 
																$etime=date("H:i",strtotime($order->products[$i]['others']['end_time']));
															}
														}
										
												echo '<br><small>&nbsp;	- '.TEXT_START_DATE.' : '. format_date($order->products[$i]['others']['start_date']) . '&nbsp;' . $stime . ' <br>&nbsp; - ' . TEXT_END_DATE .' : ' . format_date($order->products[$i]['others']['end_date']). '&nbsp;' . $etime . ' '.(($order->products[$i]['others']['resource_id'])? '<br>&nbsp; - '.tep_get_resource_name($order->products[$i]['others']['resource_id'],'resource_name').'('.$currencies->format($order->products[$i]['others']['resource_costs']).')':'').'</small>';
											 } 
										
										   if (isset($order->products[$i]['attributes']) && is_array($order->products[$i]['attributes'])) {
													reset($order->products[$i]['attributes']);
													$attribute_id="";
													for($k=0,$att_max=sizeof($order->products[$i]['attributes']);$k<$att_max;$k++) {
														$att_row=$order->products[$i]['attributes'][$k];
														if($attribute_id!="")
															$attribute_id.="-";
														$attribute_id.=$att_row['option_id'] . "{" . $att_row['value_id'] . "}";
													}
												  for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
													if($order->products[$i]['attributes'][$j]['option'] && $order->products[$i]['attributes'][$j]['value'])  echo '<br><nobr><small>&nbsp;<i> - ' . $order->products[$i]['attributes'][$j]['option'] . ': ' . $order->products[$i]['attributes'][$j]['value'] . '('.$currencies->format($order->products[$i]['attributes'][$j]['price']).')</i></small></nobr>';
												   }
												  if (STOCK_CHECK == 'true' && $order->products[$i]['element_type']=="P") {
													 echo tep_check_attribute_stock($order->products[$i]['id'],$attribute_id,$order->products[$i]['quantity']);
												  }
											}
											if ($order->products[$i]['element_type']=='E'){
												$sessions=&$order->products[$i]['sessions']; 
												$dates='';
												reset($sessions); 
												while(list($id,$session)=each($sessions)){
													if ($dates!="") $dates.=", ";
													$dates .=date(EVENTS_DATE_FORMAT,strtotime($sessions[$id]['date']));
												}

												echo '<br><small>' . $dates . '</small></br>';
										
											 }
											if($order->products[$i]['sku']!="")echo "<br>" . HEADING_SKU . $order->products[$i]['sku']; 
											echo '</td>' . "\n";
											echo '            <td class="main" align="right" valign="top">' . $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']) . '</td>' . "\n" .
												 '          </tr>' . "\n";
										  }
											
*/																		
										?>		
											 <tr> <?php echo $products_ordered; ?> </tr>
											</table>
										   </td>
										</tr>
										</table>
									</td>
								</tr>		
								<tr>
									<td>	
											<table cellpadding="2" cellspacing="5" border="0" width="100%" align="center">
												<tr><td class="info_heading" colspan="2"><?php echo 'Refund ';?></td></tr>
												<tr>
													<td width="50"></td>
													<td>
														<table cellpadding="2" cellspacing="3" border="0" width="100%">
															<tr>
																<td colspan="2">
																	<table cellpadding="0" cellspacing="0" border="0" width="100%">
																		<tr>
																			<td class="main" width="15%" align="left"><?php echo tep_draw_radio_field('chk_type','F','','','onClick=javascript:do_action()') . '&nbsp;' . TEXT_FULLY;?></td>
																			<td class="main" width="50%" align="left"><?php echo tep_draw_radio_field('chk_type','P','',(($chk_type=='P')?true:false),'onClick=javascript:do_action()') . '&nbsp;' . TEXT_PARTIALLY;?></td>
																		</tr>
																	</table>
																</td>			
															</tr>
															<tr id="choice" style="display:none">
																<td colspan="2">
																	<table cellpadding="0" cellspacing="0" border="0" width="100%">
																		<tr>
																			<td class="main" width="23%"><?php echo tep_draw_radio_field('chk_choice','A',($chk_choice=='A')?true:false,'','onclick="javascript:change_amount_type(\'A\')"') . '&nbsp;' . TEXT_AMOUNT;?></td>
																			<td class="main" width="15%"><?php echo tep_draw_radio_field('chk_choice','%','','','onclick="javascript:change_amount_type()"') . '&nbsp;' . TEXT_PERCENTAGE;?></td>
																			<td class="main"><?php echo tep_draw_input_field('txt_amount').'<span id="amount_type"></span>';?></td>
																		</tr>
																	</table>
																</td>			
															</tr>	
															<tr>
																<td colspan="2" class="main"><?php echo tep_draw_checkbox_field('chk_advise','Y') . '&nbsp;' . TEXT_ADVISE_CUSTOMERS ; ?></td>
															</tr>	
															<tr>
																<td colspan="2">
																<table cellpadding="0" cellspacing="0" border="0" width="100%">
																	<tr>
																		<td class="main" width="11%" valign="top"><?php echo TEXT_COMMENTS;?></td>
																		<td colspan="2" align="left"><textarea name="refund_comments" rows="5" cols="40"></textarea></td>
																	</tr>
																</table>
																</td>
															</tr>	
															<tr>
																<td align="right" colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','10','10');?></td>
															</tr>	
														</table>
													</td>
												</tr>		
											</table>
									</td>
							  </tr>
							  <tr>
							  	<td>
									<table cellpadding="2" cellspacing="3" border="0" width="100%">
										<tr><td class="info_heading"><?php echo ' Restock ';?></td></tr>
										<tr><td class="main"><?php echo '&nbsp;' .tep_draw_checkbox_field('is_restock','Y','','',' onClick="javascript:do_active();"') . '&nbsp;' .TEXT_RESTOCK?></td></tr>
										<tr><td class="main"><?php echo tep_draw_separator('pixel_trans.gif','1','1') ;?></td></tr>
										<tr>
											<td align="left"><table cellpadding="0" cellspacing="0" border="0" width="100%">
											<?php $opid='';
												$query=tep_db_query("select orders_products_id,products_name,products_id , products_type  from " . TABLE_ORDERS_PRODUCTS . " where orders_id='" . $oID . "' and products_type!='E' and orders_products_status!='5' group by products_id,products_type ");
												while($result=tep_db_fetch_array($query)){
													 $opid.=$result['orders_products_id'] . ",";
													echo '          <tr>' . "\n" .
														 '			  <td width="15">'  . '</td>'.
														 '            <td class="main" align="left" valign="top" width="15">' . tep_draw_checkbox_field('chk_restock' . $result['orders_products_id'] ,'Y') . '&nbsp;</td>' . "\n" .
														 '            <td class="main"  valign="top">' . $result['products_name'] ;
													echo '</td>' . "\n";
														 '          </tr>' . "\n";
														
												}
												$query=tep_db_query("select op.orders_products_id,op.products_name,op.products_id , products_type  from " . TABLE_ORDERS_PRODUCTS . " op , " . TABLE_EVENTS_SESSIONS . " s  where op.orders_id='" . $oID . "' and op.products_type='E' and s.sessions_id=op.products_id and op.orders_products_status!='5' group by s.events_id,op.products_type ");
												while($result=tep_db_fetch_array($query)){
													 $opid.=$result['orders_products_id'] . ",";
													echo '          <tr>' . "\n" .
													     '			  <td width="15">' . '</td>'.
														 '            <td class="main" align="right" valign="top" width="15">' .tep_draw_checkbox_field('chk_restock' . $result['orders_products_id'] ,'Y') . '&nbsp;</td>' . "\n" .
														 '            <td class="main"  valign="top">' . $result['products_name'] ;
													echo '</td>' . "\n";
														 '          </tr>' . "\n";
												}
												?>	
											</table></td>
										</tr>
									</table>
								</td>
							</tr>				
								<div id="loading" style="display:none"><div style="height:30px;margin-left:30px"><img src="images/24-1.gif"></div></div>
							  <tr><td colspan="4"><?php echo tep_draw_separator('pixel_trans.gif','10','10');?></td></tr>
							</table>	
						 <input type="hidden" id="opid"  name="opid" value="<?php echo substr($opid,0,-1); ?>">
						</form>	
					</td>
				</tr>
			</table>
		</td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<script>
document.getElementById('is_restock').checked=false;
do_active();
do_action();
change_amount_type('A');
</script>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); 

function get_order_details(){ global $order; ?>
	<table cellpadding="2" cellspacing="5" border="0" width="90%" align="center">
		<tr><td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','10','10');?></td></tr>
		<tr>
		<?php 
		 for ($i = 0, $n = sizeof($order->totals); $i < $n; $i++) {
			if(strtolower($order->totals[$i]['title']) ==strtolower('total:')){
		?>
			<td class="main" colspan="2"><?php echo $order->totals[$i]['title'] . '&nbsp' .  $order->totals[$i]['text'];?></td>
		<?php  }
		} ?>
		</tr>
		<tr>
			<td width="150" class="main"> <?php echo tep_draw_radio_field('chk_type','F','','',' onClick=javascript:do_action()') . '&nbsp;' . TEXT_FULLY;?></td>
			<td class="main"><?php echo tep_draw_radio_field('chk_type','P','','',' onClick=javascript:do_action()') . '&nbsp;' . TEXT_PARTIALLY;?></td>
		</tr>
		<tr id="choice" style="display:none">
			<td colspan="2">
				<table cellpadding="0" cellspacing="0" border="0" width="100%">
					<tr>
						<td class="main" width="120"><?php echo tep_draw_radio_field('chk_choice','A',($chk_choice=='A')?true:false) . '&nbsp;' . TEXT_AMOUNT;?></td>
						<td class="main" width="120"><?php echo tep_draw_radio_field('chk_choice','%') . '&nbsp;' . TEXT_PERCENTAGE;?></td>
						<td class="main"><?php echo tep_draw_input_field('txt_amount');?></td>
					</tr>
				</table>
			</td>			
		</tr>	
		<tr>
			<td colspan="2" class="main"><?php echo tep_draw_checkbox_field('chk_advise','Y') . '&nbsp;' . TEXT_ADVISE_CUSTOMERS ; ?></td>
		</tr>	
		<tr>
			<td class="main" valign="top"><?php echo TEXT_COMMENTS;?></td>
			<td colspan="3"><textarea name="refund_comments" rows="5" cols="40"></textarea></td>
		</tr>	
		<tr>
			<td align="right" colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','10','10');?></td>
		</tr>	
	</table>
<?php }
function products_restock($events_result){
	global $order;
		tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity=products_quantity+" . $events_result['products_quantity'] . ", products_ordered=products_ordered - " . $events_result['products_quantity'] . " where products_id='" . (int)$events_result['products_id'] . "'");
		$attrb_query=tep_db_query("select pa.products_options_id,pa.products_options_values_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.orders_products_id=pa.orders_products_id and op.orders_id=pa.orders_id and op.orders_id ='" . (int)$events_result['orders_id'] . "' and op.orders_products_id='" . (int)$events_result['orders_products_id'] . "' and op.products_type=pa.products_type and pa.products_type='P'"  );
		if(tep_db_num_rows($attrb_query)>0){
		while($attrb_result=tep_db_fetch_array($attrb_query)){
			$array[$attrb_result['products_options_id']]=$attrb_result['products_options_values_id'];
		}
		$attrb=tep_get_attbid($array);
		tep_db_query("update " . TABLE_PRODUCTS_STOCK . " set products_quantity=products_quantity + " . $events_result['products_quantity'] . " , products_ordered=products_ordered - " . $events_result['products_quantity'] . " , attribute_status='1' where products_id='" . (int)$events_result['products_id'] . "' and attributes_id='" . $attrb . "'");
	}
	
}
function events_restock($events_result){
	global $status_result;
		$session_query= tep_db_query("select s.events_id,op.orders_products_id from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.products_id=s.sessions_id and op.products_type='E' and op.orders_id ='" . (int)$events_result['orders_id'] . "'");
		while($session_result=tep_db_fetch_array($session_query)){
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status='" . (int)$status_result['orders_status_id'] . "', events_type='' where orders_products_id ='" . (int)$session_result['orders_products_id'] . "'");
		}
		

}
function tep_get_attbid($params) { 
    if ( (is_array($params))) {
      while (list($option, $value) = each($params)) {
        $uprid .= $option . '{' . $value . '}-' ;
      }
    }
	
    return substr($uprid,0,-1);
  }

?>			
