<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
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 . 'split_page_results_report.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  require(DIR_WS_CLASSES . 'pdfTable.php');
  require(DIR_WS_FUNCTIONS . 'services_tree.php');
  require(DIR_WS_FUNCTIONS . 'events_tree.php');
  require(DIR_WS_FUNCTIONS . 'subscription_tree.php');
  //require(DIR_WS_LANGUAGES . $language . "/reports_general_callcenter.php");
  $currencies = new currencies();
  define(BOX_WIDTH1,'125');
  tep_get_last_access_file();
  
  $btype=(isset($HTTP_GET_VARS["btype"])?$HTTP_GET_VARS["btype"]:'P');
  $date_offset=(defined('EVENTS_SERVER_DATE_OFFSET')?EVENTS_SERVER_DATE_OFFSET:0);
		
		// get initial parameters
	if (isset($HTTP_GET_VARS["return"]) && isset($HTTP_SESSION_VARS["rep_params"])){
		$input_params=&$HTTP_SESSION_VARS["rep_params"];
	} else {
	 $input_params=&$HTTP_GET_VARS; 
	 if (isset($input_params["post_action"])){
		tep_set_session_value("rep_params",$HTTP_POST_VARS);
	 } else {
		tep_set_session_value("rep_params",array());
	 } 
	}
	if(isset($input_params["type"])) {
		$type=$input_params["type"];
	}else {
		if(HIDE_FROM_BACKEND_MENU_PRODUCTS=='false')
			$type='P';
		else if(HIDE_FROM_BACKEND_MENU_EVENTS=='false')
			$type='E';
		else if(HIDE_FROM_BACKEND_MENU_SUBSCRIPTIONS=='false')
			$type='S';	
		else if(HIDE_FROM_BACKEND_MENU_SERVICES=='false')
			$type='V';	
	}
	
		$command=isset($HTTP_GET_VARS['command'])?$HTTP_GET_VARS['command']:'';
		$start_date = (isset($input_params['start_date'])?tep_convert_date_raw($input_params['start_date']):'');
		$end_date = (isset($input_params['end_date'])?tep_convert_date_raw($input_params['end_date']):getServerDate());
		$product_id = (isset($input_params['sel_product'])?$input_params['sel_product']:'-1');
		$event_id=(isset($input_params['sel_event'])?$input_params['sel_event']:'-1');
		$status_id=(isset($input_params['sel_status'])?$input_params['sel_status']:'-1');
		$staff=(isset($input_params['sel_staff'])?$input_params['sel_staff']:'All');
		$instructor=isset($input_params['sel_instructor'])?$input_params['sel_instructor']:-1;
		$location=isset($input_params['sel_location'])?$input_params['sel_location']:-1;
		$subscription_id=(isset($input_params['sel_subscription'])?$input_params['sel_subscription']:'-1');
		$service_id=(isset($input_params['sel_service'])?$input_params['sel_service']:'-1');
		$resource=isset($input_params['sel_resource'])?$input_params['sel_resource']:-1;
		$slocation=isset($input_params['sel_slocation'])?$input_params['sel_slocation']:-1;
		$post_action = isset($input_params['post_action'])?$input_params['post_action']:'';
		$page = isset($input_params['page'])?$input_params['page']:1;
		$summary = (isset($input_params['summary'])?true:false);
		
		$type_prd=$type;		
		$currencies=new currencies();
		
		$hour_array=array();
		for($icnt=1;$icnt<=12;$icnt++){
	 	 if ($icnt<10) $hour_array[]=array('id'=>$icnt,'text'=>'0' . $icnt);
		   else $hour_array[]=array('id'=>$icnt,'text'=>$icnt);
		  }
	
		$minute_array=array();
		for($icnt=0;$icnt<=59;$icnt=$icnt+1){
		  if ($icnt<10) $minute_array[]=array('id'=>$icnt,'text'=>'0' . $icnt);
		   else $minute_array[]=array('id'=>$icnt,'text'=>$icnt);
		  }
		    $s_hours=(int)$HTTP_GET_VARS['start_time_hours'];
			$s_minute=(int)$HTTP_GET_VARS['start_time_minutes'];
			$s_day_session=$HTTP_GET_VARS['start_time_session'];
			if ($s_day_session=='PM' && $s_hours<=12) $s_hours=$s_hours+12;
					
			$start_time=sprintf("%02d",$s_hours) . ":" .sprintf("%02d", $s_minute);
			//print_r ($HTTP_GET_VARS);
			$e_hours=(int)$HTTP_GET_VARS['end_time_hours'];
			$e_minute=(int)$HTTP_GET_VARS['end_time_minutes'];
			$e_day_session=$HTTP_GET_VARS['end_time_session'];
			if ($e_day_session=='PM' && $e_hours<=12) $e_hours=$e_hours+12;
				
			$end_time=sprintf("%02d",$e_hours) . ":" .sprintf("%02d", $e_minute);
			$day_session_array[]=array('id'=>'AM','text'=>'AM');
			$day_session_array[]=array('id'=>'PM','text'=>'PM');
			
		 	if($start_date=="") {
			$res = tep_db_query("SELECT '".$end_date."' - INTERVAL 1 MONTH");
	  		 $row = mysql_fetch_array($res);
	  		 $start_date = $row[0];
   			}
  	 	$display_header="";
		$status="";
		$display_header.=TEXT_START_DATE .  ":&nbsp;&nbsp;" . format_date($start_date) . "&nbsp;&nbsp;&nbsp;&nbsp;";
		$display_header.=TEXT_END_DATE . ":&nbsp;&nbsp;" . format_date($end_date) . "\t";
		
		
		//if($type=='P' && $type=='E' && $type=='S') {
		if ($start_date!='') $where .= " and date_format(o.date_purchased,'%Y-%m-%d')>='". $start_date ."'";
		if ($end_date!='')	$where .=  " and date_format(o.date_purchased,'%Y-%m-%d')<='" . $end_date . "'";
		if ($start_time!='') $swhere .= " and time_format(ose.start_time,'%h:%i')>='". $start_time . "' ";
		if ($end_time!='') $swhere .=   " and time_format(ose.end_time,'%H:%i')<='". $end_time ."' ";
		
		if($status_id>0)
			$status.= " and o.orders_status='".$status_id ."'";
			
		if($staff!='All')
			$status.=" and os.user_added='".tep_db_prepare_input($staff) ."'";
		//and time_format(ose.start_time,'%h:%i')>='01.00' and time_format(ose.end_time,'%H:%i')<='24.00' "
		//}
		
		if (($type=='P' ) && $product_id>0) {
			$prd_where .= " and op.products_id='" . $product_id . "' "; 
			$display_header.=TEXT_PRODUCT . ":&nbsp;" . tep_get_products_name($product_id, $languages_id) . "&nbsp;&nbsp;&nbsp;";
		} else if($type=='P')
			$display_header.=TEXT_PRODUCT . ":&nbsp;" . TEXT_ALL_PRODUCTS . "&nbsp;&nbsp;&nbsp;";
		
		if(($type=='V')&& $service_id>0) {
			$prd_where .= " and op.products_id='" . $service_id . "' ";
			$display_header.= TEXT_SERVICES . ":&nbsp;" . tep_get_service_name($service_id, $languages_id) . "&nbsp;&nbsp;&nbsp;";
		}	 else if($type=='V')
			$display_header.=TEXT_SERVICES . ":&nbsp;" . TEXT_ALL_SERVICES . "&nbsp;&nbsp;&nbsp;";
		
		if(($type=='S')&& $subscription_id>0) {
		$prd_where .= " and op.products_id='" . $subscription_id . "' ";
		$display_header.= TEXT_SUBSCRIPTION . ":&nbsp;" . tep_get_subscription_name($subscription_id, $languages_id) . "&nbsp;&nbsp;&nbsp;";
		}	 else if($type=='S')
			$display_header.=TEXT_SUBSCRIPTION . ":&nbsp;" . TEXT_ALL_SUBSCRIPTIONS . "&nbsp;&nbsp;&nbsp;";
		
		if(($type=='E') && $event_id>0) {		 
			$prd_where .= " and es.events_id='" . $event_id . "' ";
			$display_header.= TEXT_EVENT . ":&nbsp;" . tep_get_events_name($event_id, $languages_id) . "&nbsp;&nbsp;&nbsp;";
		} else if($type=='E')
			$display_header.=TEXT_EVENT . ":&nbsp;" . TEXT_ALL_EVENTS . "&nbsp;&nbsp;&nbsp;";
		
		$sql = "select a.admin_id admin_id, admin_firstname, admin_lastname  from events_instructors ei, admin a where ei.admin_id=a.admin_id order by admin_firstname,admin_lastname";
		$sql_result = tep_db_query($sql);
		while($row=tep_db_fetch_array($sql_result)) {
			$einstructors[$row["admin_id"]]=$row["admin_firstname"]." ".$row["admin_lastname"];
		}
		if($type=='E'){
			if($instructor>0){
				$ins_where.= "and e.events_instructor='".$instructor."' ";
				 	$display_header.=TEXT_INSTRUCTOR . ":&nbsp;" . $einstructors[$instructor] . "&nbsp;&nbsp;&nbsp;";
				} else 
				 	$display_header.=TEXT_INSTRUCTOR . ":&nbsp;" . TEXT_ALL_INSTRUCTORS . "&nbsp;&nbsp;&nbsp;";
			if($location>0){
				$loc_where.= "and e.events_location='".$location."' ";
			}else
				$display_header.=TEXT_LOCATION . ":&nbsp;" . TEXT_ALL_LOCATIONS . "&nbsp;&nbsp;&nbsp;";
		} 
		
		
	  /* if($type=='V') {
	   		if($service_id>0){
				$prd_where.= " and se.service_id='".$service_id."' ";
				$display_header.=TEXT_SER . ":&nbsp;" . $location[$location] . "&nbsp;&nbsp;&nbsp;";
			}*/
		//if(($type=='V') && $service_id>0) {		 
		//	$prd_where .= " and op.products_id='" . $service_id . "' ";
		//	$display_header.= TEXT_SERVICE . ":&nbsp;&nbsp;" . tep_get_service_name($service_id, $languages_id) . " ";
		//}
		if($type=='V') {
			if($resource!="-1"){
				$res_where.= " and ose.resource_id='".$resource."' ";
			}else
				$display_header.=TEXT_RESOURCE . ":&nbsp;" . TEXT_ALL_RESOURCES . "&nbsp;&nbsp;&nbsp;";	
			 
			
		if($slocation!="-1") {
				$sloc_where.= " and se.service_location='".$slocation."' ";
		} else
			$display_header.=TEXT_LOCATION . ":&nbsp;" . TEXT_ALL_LOCATIONS . "&nbsp;&nbsp;&nbsp;";
		}
		$type_where .=" and op.products_type='".$type ."'";
		
		$details=array();
		$found_results=false;
		
		if($type=='P'){
		
		$products_sql="select o.orders_id, concat(LTRIM(c.customers_lastname),' ',LTRIM(c.customers_firstname)) as customers_name,os.user_added,op.products_id as item_id, o.customers_email_address customers_email_address,op.products_name as item_name,events_type, waitlist_type, orders_status from orders_products op, orders o, customers c, orders_status_history os where o.customers_id =c.customers_id and op.orders_id=o.orders_id and o.orders_id=os.orders_id 
		 " . $prd_where . $where . $type_where . $status. " group by o.orders_id,op.products_id order by item_id,customers_name";
		}
		elseif($type=='E'){
		$products_sql="select o.orders_id, concat(LTRIM(c.customers_lastname),' ',LTRIM(c.customers_firstname)) as customers_name, os.user_added, o.customers_email_address customers_email_address, ed.events_name item_name,e.events_id as item_id, events_type, waitlist_type, orders_status,e.events_group_bookings,op.products_quantity from events_sessions es, orders_products op, orders o, customers c,events e, events_description ed, orders_status_history os where o.customers_id=c.customers_id 
		and sessions_id = op.products_id and op.orders_id=o.orders_id and o.orders_id=os.orders_id and e.events_id=es.events_id and ed.language_id='1' and ed.events_id=e.events_id  "
		. $prd_where . $where . $type_where . $ins_where . $loc_where .$status. " group by o.orders_id,e.events_id order by item_id,customers_name";
		}
		elseif($type=='S'){
		$products_sql="select o.orders_id, o.customers_name customers_name,os.user_added,op.products_id as item_id, o.customers_email_address customers_email_address,op.products_name as item_name, orders_status from orders_products op, orders o, orders_status_history os where op.orders_id=o.orders_id and o.orders_id=os.orders_id  "
		. $prd_where . $where . $type_where .$status." group by o.orders_id,op.products_id order by item_id,customers_name";
		}
		elseif($type=='V'){
		$products_sql = "select time_format(ose.start_time,'%h:%i') as start_time,time_format(ose.end_time,'%H:%i') as end_time,o.orders_id, o.customers_name customers_name, os.user_added,
		o.customers_email_address customers_email_address, sed.service_name item_name,se.service_id as item_id,
		waitlist_type from " . TABLE_ORDERS_SERVICES . " ose, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed, " .
		TABLE_ORDERS_STATUS_HISTORY . " os where  op.orders_id=o.orders_id and ose.orders_id=o.orders_id and o.orders_id=os.orders_id  and sed.language_id='" . $languages_id . "'
		and sed.service_id=se.service_id and op.products_id=ose.products_id and op.products_id=se.service_id  " . $prd_where . $swhere . $type_where . $res_where . $sloc_where . $status. " group by o.orders_id,se.service_id order by os.user_added,item_id,customers_name";
		}
		
		$order_status_array=array();
		$status_array=array();
		//$status_array[]=array("id"=>"-1","text"=>TEXT_ALL);
		$status_array=tep_get_orders_status(true);
		// get the mysql results;
		$sql="SELECT orders_status_id,orders_status_name from " . TABLE_ORDERS_STATUS . " where language_id='" . $languages_id . "'";
		$sql_result=tep_db_query($sql);
		while($row=tep_db_fetch_array($sql_result)){
		//$status_array[]=array('id' =>$row["orders_status_id"], 'text' =>$row["orders_status_name"] );
		$order_status_array[$row["orders_status_id"]]=$row["orders_status_name"];
		}
		
	// get all call centre orders
		$sql="SELECT concat(a.admin_firstname,' ',a.admin_lastname) as admin_name from " . TABLE_ADMIN . " a, " . TABLE_ADMIN_GROUPS . 
				" ag where ag.admin_groups_id=a.admin_groups_id  and ag.admin_groups_name='" . TEXT_CALLSTAFF_ENTRY . "' order by admin_firstname,admin_lastname";
		
		$sql_result=tep_db_query($sql);
		$call_staff_array[]=array("id"=>"All","text"=>TEXT_ALL_STAFFS);
		while($row=tep_db_fetch_array($sql_result)){
			$call_staff_array[]=array("id"=>$row["admin_name"],"text"=>$row["admin_name"]);
			$staff_array[$row['admin_name']]=$row['admin_name'];
		}
		mysql_free_result($sql_result);
		//echo $status_id;
		if($status_id >0){
			$display_header.= TEXT_STATUS . ":&nbsp;" . $order_status_array[$status_id] . "&nbsp;&nbsp;&nbsp;";
		} else
			$display_header.= TEXT_STATUS .":&nbsp;" . TEXT_ALL ."&nbsp;&nbsp;&nbsp;";
		
		if($staff!='All')
			$display_header.="\n". TEXT_CALL_CENTRE_STAFF .":&nbsp;" . $staff_array[$staff_id] .'&nbsp;&nbsp;&nbsp;';
		else	
			$display_header.="\n". TEXT_CALL_CENTRE_STAFF .":&nbsp;" . TEXT_ALL_STAFFS ."&nbsp;&nbsp;&nbsp;";
		if ($post_action=="screen") $query_split = new splitPageResultsReport($page, REPORT_MAX_ROWS_PAGE, $products_sql, $query_split_numrows);
		$products_query=tep_db_query($products_sql);
		//echo $products_sql;
		if (tep_db_num_rows($products_query)>0) $found_results=true;
		
	
		$output_array=array();
		$total=0;
		$gamount=0;
			$sub_total=0;
			$last_row=0;
			$i=1;
			$prev_user="";
			$prev_item=0;
			$net_total=0;
		while($products_result=tep_db_fetch_array($products_query)){
		//$id=$products_result["orders_products_id"];
		$pid=$products_result["orders_id"];	
		$status=$products_result['orders_status'];
		$item_id=$products_result['item_id'];
		$item_name=$products_result['item_name'];
		$user=$products_result["user_added"];
		//echo "hi";
		//echo " SELECT sum(op.final_price*op.products_quantity) as final_price,op.products_tax from orders_products op where op.orders_id=" . $pid .  " group by orders_id";
		$total_sql=tep_db_query("SELECT sum(op.final_price*op.products_quantity) as final_price,op.products_tax from orders_products op where op.orders_id=" . $pid .  " group by orders_id");
		$total_result=tep_db_fetch_array($total_sql);
		
		$amt=tep_add_tax($total_result['final_price'],$total_result["products_tax"]);
		$amount=tep_get_rounded_amount($amt);
		
		
		if($status=='1'){
		  $s="Pending";
		  }
		  elseif($status=='2'){
		  $s="Processing";
		  } 
		  else {
		  $s="Delivered";
		  }
		
		$key_id=$item_id;
		$name1='';
		$name=$products_result["item_name"];
		//echo $name;
		
		if ($prev_item!=$item_id){
					// output item name
					if ($total>0) {
						$output_array[$item_id][]=array('type'=>'total','content'=>$currencies->format($total));
						$total=0;
						$gamount=0;
					}
					$output_array[$item_id][]=array('type'=>'item','content1'=>$products_result['item_name']);
					$prev_item=$item_id;
				} 		
		$total+=$amount;
		// if needed to display summary or not
		if (!$summary_show) {
		if (!isset($details[$key_id])){
			$details[$key_id]=array("name1"=>$name1,"name"=>$name,"contents"=>array());
		}
	
		$details[$key_id]["contents"][]=array("orders_id"=>$products_result["orders_id"],"cname"=>$products_result["customers_name"],"status"=>$s,"customers_email_address"=>$products_result["customers_email_address"],"date"=>format_date($products_result["date_purchased"]),"orders_id"=>$products_result["orders_id"],"products_id"=>$pid,"item_id"=>$item_id,"user_added"=>$products_result["user_added"],"amount"=>$amount,"gamount"=>$total,'prt_total'=>0);
		}
		if($prod_id!=$products_result['item_id']) 
			$pids[]=array('prid'=>$products_result['item_id']);
		$prod_id=$products_result['item_id'];
		}
		for($jcnt=0;$jcnt<sizeof($pids);$jcnt++) {
			$prd_id=$pids[$jcnt]['prid'];
			$pp_id=$pids[$jcnt-1]['prid'];
			$tot_size=sizeof($details[$prd_id]['contents']);
			$size[$prd_id][]=array('size'=>$tot_size);		
			if($prd_id!=$details[$prd_id]['contents']['item_id'])
				$details[$prd_id]['contents']['prt_total']='1';
			
		}

		
	 if ($post_action!="screen"){
	  	 $report_filename=sprintf("callcenters_orders_%s_%s",$login_id,time());
		if (isset($HTTP_SESSION_VARS["report_filename"])){
			$old_file=DIR_FS_CATALOG . "images/" .$HTTP_SESSION_VARS["sess_report_filename"] . ".pdf";
			if (file_exists($old_file)) unlink($old_file);
			$old_file=DIR_FS_CATALOG . "images/" . $HTTP_SESSION_VARS["sess_report_filename"] . ".csv";
			if (file_exists($old_file)) unlink($old_file);
		}
		tep_set_session_value("sess_report_filename",$report_filename);
	}	
		if ($post_action=="pdf"){
			generate_pdf();
			echo $report_filename. ".pdf";
			return;
		}

		//print_r ($details);
		if($command=='fetch_report'){
		get_result();
		exit;  
		}
		tep_delete_temp_files("callcenter_orders_" . $login_id);
	
	?>

<!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/date-picker.js"></script>
<script language="javascript" src="includes/http.js"></script>

<?php  include(DIR_WS_INCLUDES."date_format_js.php")?>


<script language="JavaScript">
var t = '<?php echo isset($HTTP_GET_VARS['btype'])?$HTTP_GET_VARS['btype']:'P'; ?>';
    
	var product=document.getElementById("fetch_report_product");
	var events=document.getElementById("fetch_report_event");
	var subscription=document.getElementById("fetch_report_subscription");
	var service=document.getElementById("fetch_report_service");
	 
	function set_display(obj,styles){
		if(!obj) return;
		if(obj && styles)  return obj.style.display='';	
		else if(obj && !styles) return obj.style.display='none';	
	}
	function get_divs(type,product,events,subscription,service){
		if(document.getElementById("load_details")) document.getElementById("load_details").style.visibility="";
		var product_display=document.getElementById("product");
		var events_display=document.getElementById("events");
		var instructor_display=document.getElementById("sel_instructor");
		var location_display=document.getElementById("sel_location");
		var resource_display=document.getElementById("sel_resource");
		var slocation_display=document.getElementById("sel_slocation");
		var subscription_display=document.getElementById("subscription");
		var service_display=document.getElementById("service");
		var service_date=document.getElementById("sdate");
		if(type=='P' ){
			set_display(product,true);
			set_display(product_display,true);
			set_display(subscription_display,false);
			set_display(service_date,false);
			set_display(events_display,false);
			set_display(instructor_display,false);
			set_display(resource_display,false);
			set_display(slocation_display,false);
			set_display(service_display,false);
			set_display(events,false);
			set_display(subscription,false);
			set_display(service,false);
			
		}else if(type=='E'){
			set_display(events,true);
			set_display(events_display,true);
			set_display(instructor_display,true);
			set_display(service_date,false);
			set_display(subscription_display,false);
			set_display(resource_display,false);
			set_display(slocation_display,false);
			set_display(product_display,false);
			set_display(service_display,false);
			set_display(product,false);
			set_display(subscription,false);
			set_display(service,false);
		
		}else if(type=='S'){
			set_display(subscription,true);
			set_display(subscription_display,true);
			set_display(events_display,false);
			set_display(service_date,false);
			set_display(instructor_display,false);
			set_display(resource_display,false);
			set_display(slocation_display,false);
			set_display(product_display,false);
			set_display(service_display,false);
			set_display(product,false);
			set_display(events,false);
			set_display(service,false);
			
		}else if(type=='V'){
			set_display(service,true);
			set_display(service_display,true);
			set_display(service_date,true);
			set_display(events_display,false);
			set_display(instructor_display,false);
			set_display(resource_display,true);
			set_display(slocation_display,true);
			set_display(product_display,false);
			set_display(subscription_display,false);
			set_display(product,false);
			set_display(events,false);
			set_display(subscription,false);	
			
		}
	}
function doChange(type) { 
	get_divs(type,product,events,subscription,service);
	if(type!="") { 
		where="";
		if(get_needed_details()!='') where=get_needed_details();
		where=where+"&post_action=screen&page=1&type="+type;
		command="<?php echo tep_href_link(FILENAME_REPORTS_GENERAL_CALL_CENTER_ORDERS);?>?command=fetch_report"+sel_node+where;
		do_get_command(command);
	}
}
function doReport(mode,page) { 
		var startDate=date_format(document.f.txt_start_date.value,'','y-m-d',true);
		var endDate=date_format(document.f.txt_end_date.value,'','y-m-d',true);
		var product = document.getElementById("fetch_report_product");
		var events=document.getElementById("fetch_report_event");
		var subscription=document.getElementById("fetch_report_subscription");
		var service=document.getElementById("fetch_report_service");
		if(!page) page=1;
		if(startDate>endDate) {
			alert("<?php echo REPORT_START_AFTER_END?>");
			return;
		}
		post_action="screen";
		if (mode==2)
			post_action="pdf";
		else if (mode==3)
			post_action="excel";
	type=t;
	if(product && product.style.display=='') type='P';
	else if(events &&  events.style.display=='' ) type='E';
	else if(subscription  && subscription.style.display=='') type='S';
	else if(service && service.style.display=='') type='V';
	get_divs(type,product,events,subscription,service);
	if(get_needed_details()!='') where=get_needed_details(); //alert (type);
	command="<?php echo tep_href_link(FILENAME_REPORTS_GENERAL_CALL_CENTER_ORDERS);?>?command=fetch_report"+sel_node+where+"&page="+page+"&post_action="+post_action+"&type="+type;
	
	do_get_command(command);
}
function get_needed_details(){
	sel_node="";
	tax=0;
	sort_manufact=0;
	sales_by_order=0;
	summary=0;
	where=""; 
	startDate=document.f.txt_start_date.value;
	endDate=document.f.txt_end_date.value;
	
	summary=document.getElementById("summary");
	var product_display=document.getElementById("product");
	var events_display=document.getElementById("events");
	var instructor_display=document.getElementById("sel_instructor");
	var resource_display=document.getElementById("sel_resource");
	var slocation_display=document.getElementById("sel_slocation");
	var location_display=document.getElementById("sel_location");
	var subscription_display=document.getElementById("subscription");
	var service_display=document.getElementById("service");
	var service_date=document.getElementById("sdate");
	
	if(document.getElementById("sel_product") && product_display && product_display.style.display!='none'){
		document.getElementById('dd').style.display='';
		pro_object=document.getElementById("sel_product");
		sel_node="&sel_product="+pro_object.options[pro_object.selectedIndex].value;
	}else if(document.getElementById("sel_event") && events_display && events_display.style.display!='none'){
		document.getElementById('dd').style.display='';
		pro_object=document.getElementById("sel_event");
		sel_node="&sel_event="+pro_object.options[pro_object.selectedIndex].value;
		 if(document.getElementById("sel_instructor")){
				pro_object=document.getElementById("sel_instructor");
				sel_node=sel_node+"&sel_instructor="+pro_object.options[pro_object.selectedIndex].value;
			}	
		  if(document.getElementById("sel_location")){
				pro_object=document.getElementById("sel_location");
				sel_node=sel_node+"&sel_location="+pro_object.options[pro_object.selectedIndex].value;
			}		
	}
	else if(document.getElementById("sel_subscription") && subscription_display && subscription_display.style.display!='none'){
		document.getElementById('dd').style.display='';
		pro_object=document.getElementById("sel_subscription");
		sel_node="&sel_subscription="+pro_object.options[pro_object.selectedIndex].value;
	}else if(document.getElementById("sel_service") && service_display && service_display.style.display!='none'){
	    document.getElementById('dd').style.display='none';
		pro_object=document.getElementById("sel_service");
		sel_node="&sel_service="+pro_object.options[pro_object.selectedIndex].value;
		
		if(document.getElementById("sel_resource")){
				pro_object=document.getElementById("sel_resource");
				sel_node=sel_node+"&sel_resource="+pro_object.options[pro_object.selectedIndex].value;
			}	
		  if(document.getElementById("sel_slocation")){
				pro_object=document.getElementById("sel_slocation");
				sel_node=sel_node+"&sel_slocation="+pro_object.options[pro_object.selectedIndex].value;
			}
		
		if(document.getElementById("sdate")){
		var stime=document.forms["f"].start_time_hours.options[document.forms["f"].start_time_hours.selectedIndex].value;
		//stime+=':';
		var smin=document.forms["f"].start_time_minutes.options[document.forms["f"].start_time_minutes.selectedIndex].value;
		//stime+=':';
		var ss=document.forms["f"].start_time_session.options[document.forms["f"].start_time_session.selectedIndex].value;
		
		var etime=document.forms["f"].end_time_hours.options[document.forms["f"].end_time_hours.selectedIndex].value;
		//etime+=':';
		var emin=document.forms["f"].end_time_minutes.options[document.forms["f"].end_time_minutes.selectedIndex].value;
		//etime+=':';
		var ee=document.forms["f"].end_time_session.options[document.forms["f"].end_time_session.selectedIndex].value;
		
		where="&start_time_hours="+stime+"&start_time_minutes="+smin+"&start_time_session="+ss+"&end_time_hours="+etime+"&end_time_minutes="+emin+"&end_time_session="+ee;

			}
		}
	 if(document.getElementById("sel_status")){
		pro_object=document.getElementById("sel_status");
		where=where+"&sel_status="+pro_object.options[pro_object.selectedIndex].value;
	}
	 if(document.getElementById("sel_staff")){
		pro_object=document.getElementById("sel_staff");
		where=where+"&sel_staff="+pro_object.options[pro_object.selectedIndex].value;
	}

	
	where=where+"&start_date="+startDate+"&end_date="+endDate;
	if(summary && summary.checked)
		where=where+"&summary=1";
	return where;
}

function disable_products(){
 if(document.getElementById("view_all_products")){
		set_display(document.getElementById("view_all_products"),true);
		if(document.getElementById("product").style.display=='')
		//set_display(document.getElementById("view_sort_manu"),true);
		set_display(document.getElementById("view_all_products_space"),false);
	}
}

function do_result(result){
		if(result.substr(result.indexOf('.'),4)=='.pdf' || result.substr(result.indexOf('.'),4)=='.csv'){
			if(result.substr(0,10)!='callcenter')return;
			window.open("<?php echo DIR_WS_CATALOG . "images/";?>"+result);
			doReport(1);
			return;
	  }else if(result!='') {
		element=document.getElementById("get_all_results");
		if(document.getElementById("load_details")) document.getElementById("load_details").style.visibility="hidden";
		if(element) element.innerHTML=result;
		}
	}

</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<div id="spiffycalendar" class="text"></div>
	<!-- header //-->
	<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
	<!-- header_eof //-->
	<!-- body //-->
	<table border="0" width="100%" cellspacing="2" cellpadding="2">
	<tr> 
		<!-- body_text //-->	  
		<td width=100% align=left valign="top">
		<table border="0" width="100%" cellspacing="0" cellpadding="2">
			<tr>
				<td class="pageHeading"><?php echo HEADING_REPORT_CALL_CENTER;?></td>
			</tr>
			<tr>
				<TD>
					<?php echo tep_draw_form("f",FILENAME_REPORTS_GENERAL_CALL_CENTER_ORDERS);?>
					<input type="hidden" name="page" value="1">
					<input type="hidden" name="type" value="P">
					<input type="hidden" name="post_action" value="1">
			  <table cellspacing="3" cellpadding="2" class="searchArea" width="100%" border="0">
			  <tbody>
				<?php 
				$_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
				<tr class="main"> 
				<td  nowrap valign="top" id="dd"><?php echo REPORT_START_DATE . "&nbsp;&nbsp;" . tep_draw_input_field('txt_start_date',format_date($start_date),' size="10"');?>
					<a href="javascript:show_calendar('f.txt_start_date',null,null,'<?php echo $date_format;?>');"
					   onmouseover="window.status='Date Picker';return true;"
					   onmouseout="window.status='';return true;"><img border="none" src="images/icon_calendar.gif"/>  
					 </a>
				  <?php echo '&nbsp;'.REPORT_END_DATE . "&nbsp;&nbsp;" . tep_draw_input_field('txt_end_date',format_date($end_date),' size="10"');?>
					<a href="javascript:show_calendar('f.txt_end_date',null,null,'<?php echo $date_format;?>');"
					   onmouseover="window.status='Date Picker';return true;"
					   onmouseout="window.status='';return true;"><img border="none" src="images/icon_calendar.gif"/>  
					 </a>
					 <?php echo tep_draw_separator('pixel_trans.gif', '20', '10').tep_draw_checkbox_field('summary',1,$summary) .'  ' . REPORT_SUMMARY_ONLY;?>
				  </td>
				  <td id="sdate" style="display:none" nowrap="nowrap">
				  	<?php $time_split=explode(":",$suInfo->service_start_time); 
							if ($time_split[2]=='PM' && $time_split[0]>12) $time_split[0]=$time_split[0]-12;
					?>
					<?php echo TEXT_START_TIME . '&nbsp;' . tep_draw_pull_down_menu('start_time_hours',$hour_array,$time_split[0]) . ' : ' . tep_draw_pull_down_menu('start_time_minutes',$minute_array,$time_split[1]) . ' ' . tep_draw_pull_down_menu('start_time_session',$day_session_array,$time_split[2]);?>
					<?php $time_split=explode(":",$suInfo->service_end_time); 
							if ($time_split[2]=='PM' && $time_split[0]>12) $time_split[0]=$time_split[0]-12;
					?>
					<?php echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . TEXT_END_TIME . '&nbsp;' .  tep_draw_pull_down_menu('end_time_hours',$hour_array,$time_split[0]) . ' : ' . tep_draw_pull_down_menu('end_time_minutes',$minute_array,$time_split[1]) . ' ' . tep_draw_pull_down_menu('end_time_session',$day_session_array,$time_split[2]);?>
					<?php echo tep_draw_separator('pixel_trans.gif', '20', '10').tep_draw_checkbox_field('summary',1,$summary) .'  ' . REPORT_SUMMARY_ONLY;?>
					</td>	
					
				<td  align="right" nowrap valign="top">
					<?php echo '<a href="javascript:doReport(1);">' . tep_image_button('button_report_search.gif', IMAGE_SEARCH_DETAILS) . '</a>'; ?>
				</td>
				</tr>
				
				
				<tr class="main">
				
				<td id="view_all_products_space" align="left"></td>
				<td  id="view_all_products" align="left">
					<?php 
					// get instructor names			
						$sql = "select a.admin_id admin_id, admin_firstname, admin_lastname  from events_instructors ei, admin a where ei.admin_id=a.admin_id order by admin_firstname,admin_lastname";
						$sql_result = tep_db_query($sql);
						$num_rows = tep_db_num_rows($sql_result);
						$instructors_array[]=array("id"=>-1,"text"=>TEXT_ALL_INSTRUCTORS);
						while($row=tep_db_fetch_array($sql_result)) {
							$instructors_array[]=array("id"=>$row["admin_id"],"text"=>$row["admin_firstname"]." ".$row["admin_lastname"]);
							if ($row["admin_id"]==$instructor){
								$display_header.=TEXT_INSTRUCTOR  . ":&nbsp;&nbsp;" . $row["admin_firstname"]." ".$row["admin_lastname"] . "\t";
							}
						}
						mysql_free_result($sql_result);
						
						// get event location names
						$sql = "select distinct location_id, location_name from events,events_locations where location_id=events_location order by location_name";
						$sql_result = tep_db_query($sql);
						$locations_array[]=array("id"=>-1,"text"=>TEXT_ALL_LOCATIONS);
						while($row=tep_db_fetch_array($sql_result)) {
							$locations_array[]=array("id"=>$row["location_id"],"text"=>$row["location_name"]);
							if ($row["location_id"]==$location){
								$display_header.=TEXT_LOCATION  . ":&nbsp;&nbsp;" . $row["location_name"] . "\t";
							}
						}
						mysql_free_result($sql_result);
						
						//get resource names
						
						$sql = "select  r.resource_id, rd.resource_name as resource_name from ".TABLE_RESOURCES." r," .TABLE_RESOURCES_DESCRIPTION. " rd where r.resource_id=rd.resource_id order by resource_id";
						$sql_result = tep_db_query($sql);
						$num_rows = tep_db_num_rows($sql_result);
						$resources_array[]=array("id"=>-1,"text"=>TEXT_ALL_RESOURCE);
						while($row=tep_db_fetch_array($sql_result)) {
							$resources_array[]=array("id"=>$row["resource_id"],"text"=>$row["resource_name"]);
						}
						mysql_free_result($sql_result);
	
						// get service location names
						
						$sql = "select distinct se.service_location as service_location ,l.service_location_name as location_name from ". TABLE_SERVICES . " se," . TABLE_SERVICES_LOCATIONS ." l where l.service_location_id=se.service_location order by l.service_location_name";
						$sql_result = tep_db_query($sql);
						$slocations_array[]=array("id"=>-1,"text"=>TEXT_ALL_LOCATIONS);
						while($row=tep_db_fetch_array($sql_result)) {
							$slocations_array[]=array("id"=>$row["service_location"],"text"=>$row["location_name"]);
							if ($row["service_location"]==$location){
								$display_header.=TEXT_LOCATION  . ":&nbsp;&nbsp;" . $row["location_name"] . "\t";
							}
						}
						mysql_free_result($sql_result);
						echo '<div id="product">';
						
						$all_products_array = array();
						$all_products_array = tep_get_products_array_single();
						if(sizeof($all_products_array)>0) echo TEXT_PRODUCTS . '  ' ;
						if(sizeof($all_products_array)<=0) echo 'Products Are Not Available';
						else echo tep_draw_separator('pixel_trans.gif','10','10').tep_draw_products_select_menu('sel_product',$all_products_array,$product_id,' id="sel_product"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_CALL_CENTRE_STAFF . '&nbsp;' . tep_draw_pull_down_menu("sel_staff",$call_staff_array,$staff,'id="sel_staff"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_STATUS . '  ' ;
						echo tep_draw_pull_down_menu('sel_status',$status_array,$status_id,'id=sel_status');
					echo '</div><div id="subscription" style="display:none">';
					echo TEXT_SUBSCRIPTIONS . '  ';
						$all_subscriptions_array=array();
						$all_subscriptions_array = tep_get_subscription_array_single();
						if(sizeof($all_subscriptions_array)<=0) echo 'Subscriptions are not Available';
						else echo tep_draw_subscription_select_menu('sel_subscription',$all_subscriptions_array,$subscription_id,' id="sel_subscription"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_CALL_CENTRE_STAFF . '&nbsp;' . tep_draw_pull_down_menu("sel_staff",$call_staff_array,$staff,'id="sel_staff"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_STATUS . '  ' ;
						echo tep_draw_pull_down_menu('sel_status',$status_array,$status_id,'id=sel_status');
					echo '</div><div id="events" style="display:none">';
						
						$all_events_array=array();
						$all_events_array = tep_get_events_array_single();
						echo  TEXT_LOCATION . '&nbsp;'  . tep_draw_pull_down_menu("sel_location",$locations_array,$location,'id="sel_location"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_EVENTS . '  ';
						if(sizeof($all_events_array)<=0) echo 'Events are not Available';
						else echo tep_draw_event_select_menu('sel_event',$all_events_array,$event_id,' id="sel_event"');
					//	echo '<table border="0"> <tr><td><tr> <td class=main>';
						echo  tep_draw_separator('pixel_trans.gif','20','10'). TEXT_INSTRUCTOR . '&nbsp;' . tep_draw_pull_down_menu("sel_instructor",$instructors_array,$instructor,'id="sel_instructor"') ;
						//echo '</td></tr></td></tr></table>';
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_CALL_CENTRE_STAFF . '&nbsp;' . tep_draw_pull_down_menu("sel_staff",$call_staff_array,$staff,'id="sel_staff"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_STATUS . '  ' ;
						echo tep_draw_pull_down_menu('sel_status',$status_array,$status_id,'id=sel_status');
						
					echo '</div><div id="service" style="display:none">';
					    echo  TEXT_LOCATION . '&nbsp;'  . tep_draw_pull_down_menu("sel_slocation",$slocations_array,$slocation,'id="sel_slocation"');
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_SERVICES . '  ';
						$all_service_array=array();
						$all_service_array = tep_get_service_array_single();
						if(sizeof($all_service_array)<=0) echo 'Services are not Available';
						else echo tep_draw_service_select_menu('sel_service',$all_service_array,$service_id,' id="sel_service"');
					//	echo '<table border="0"> <tr><td><tr> <td class=main>';
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_CALL_CENTRE_STAFF . '&nbsp;' . tep_draw_pull_down_menu("sel_staff",$call_staff_array,$staff,'id="sel_staff"');
						echo  tep_draw_separator('pixel_trans.gif','20','10').TEXT_RESOURCE . '&nbsp;' . tep_draw_pull_down_menu("sel_resource",$resources_array,$resource,'id="sel_resource"') ;
						
					//	echo '</td></tr></td></tr></table>';
						echo tep_draw_separator('pixel_trans.gif','20','10').TEXT_STATUS . '  ' ;
						echo tep_draw_pull_down_menu('sel_status',$status_array,$status_id,'id=sel_status');
					echo '</div>';
					
					?>
				</td>
				<td align="right" >
					<?php echo '&nbsp;'. '<a href="javascript:doReport(2);">' . tep_image_button('button_export_pdf.gif', IMG_EXPORT_PDF) . '</a>'; ?>
				</td>
			</tr>
			<tr>				
				<td colspan="4" align="right">
					<?php echo '<a href="javascript:doReport(3);">' . tep_image_button('button_export_excel.gif', IMG_EXPORT_EXCEL) . '</a>'; ?>
				</td>
			</tr>
			
		</table>
		</form>
		</td>
		
		</tr>
		<tr ><td class="smalltext" id="load_details">load...</td></tr>
		<tr>
			<td id="get_all_results"></td>
		</tr>  
		<script language="javascript">
				disable_products();
				doReport(1);
		</script>
	
</table>
</td>
</tr>
</table>
	<!-- footer //-->
	<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
	<!-- footer_eof //-->
/body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); 

 function getDetails($type="", $detailed_view=false) {
	global $display_header,$output_array,$size,$found_results,$details,$payment_count,$currencies,$report_filename,$payment_list,$summary,$payment_col_count,$tax,$sales_by_order;
?>		  
		   	<?php 
				if(!$detailed_view) {
					display_total(true,$type);
					
				}else if($detailed_view) {
				 echo '<tr ><td class="smalltext" colspan=13><b>'.get_heading($type).'</b></td></tr>';	
		  		 //display_total(false,$type);
				
				if ($found_results) {
					reset($details);
					$prev_product_id=-1;
					$prev_products_name = "";
					$prev_attribute_id='-1';
					$row_cnt=1;
					$unit_subtotal=0;
					$unit_total=0;
					$all_subtotal=0;
					$all_subtax=0;
					$all_total=0;
					$cat_name="";
					$pre_id="";
					$prd_unit_subtotal=0;
					$prd_unit_all_subtotal=0;
					$prd_quan_subtotal=0;
					$sub=0;
						
					//print_r($details);
					while(list($key,)=each($details)){
						$row=&$details[$key];
						$splt_key=split("-",$key);
						$cat_id=get_categories_name($content['products_id'],'cat_id');
						if($pre_id!=$cat_id){
								$cat_name=get_categories_name($content['products_id']);													
								$pre_id=get_categories_name($content['products_id'],'cat_id');
								
						}
					   if (count($splt_key)>1 && $sales_by_order==0){
						//		if ($splt_key[1]!=$prev_attribute_id && $sales_by_order==0){
							if ($key!=$prev_attribute_id && $sales_by_order==0){/*
								if ($unit_subtotal>0) 
								{
									print_total_row($unit_subtotal,$all_subtotal,$all_subtax,$quan_subtotal);
									$unit_subtotal=0;
									$all_subtotal=0;
									$all_subtax=0;
									$quan_subtotal=0;
								}
									echo '<tr class="dataTableHeadingRow" height="20"><td class="dataTableHeadingContent" colspan="' . (12) . '">' . tep_draw_separator('pixel_trans.gif',10,1) .$row["name"] . '</td></tr>';
									//$prev_attribute_id=$splt_key[1];
									$prev_attribute_id=$key;
							*/}
						} else {	
							if (($splt_key[0]!=$prev_product_id ) ){
								
								if ($splt_key[0]!=$prev_product_id && $row["name"]!=$prev_products_name) {
								?>
								
								<?php	
								
								echo '<tr class="dataTableHeadingRow" height="20"><td class="dataTableHeadingContent" colspan="' . (13) . '">' . $row["name"] . '</td></tr>';
								}	
								$prev_product_id=$splt_key[0];
								$prev_products_name = $row["name"];
								$prev_attribute_id=-1;
							}
						}
						$contents=&$row["contents"];
						
								$total=0;
								$sub_total=0;
								$prev_user="";
								$prev_item=0;
								$net_total=0;
								$prev=0;
								$gtot=0;
						for ($icnt=0,$n=count($contents);$icnt<$n-1;$icnt++){
								$row=&$contents[$icnt];
								$item_id=$row['item_id'];
								
							$content=&$contents[$icnt];
							if($row_cnt%2==0)
								$class='class="dataTableRow"';
							else
								$class='';	
						if(!$summary) {
						?>
							
									<tr <?php echo $class; ?> valign="top" height="20" style="cursor:pointer;cursor:hand" onMouseOver="rowOverEffect(this)" onMouseOut="rowOutEffect(this)" onClick="javascript:location.href='<?php echo tep_href_link(FILENAME_ORDERS,'oID=' .$content["orders_id"] . '&action=edit&return=cl&type='.$type);?>';">
									<td class="dataTableContent"><?php echo $row_cnt;?></td>
									<td  class="dataTableContent"><?php echo $content["cname"];?></td>
									<td  class="dataTableContent" align="left"><?php //echo $content["orders_id"];?></td>
									<td   class="dataTableContent" align="center"><a href="mailto:<?php echo $content["customers_email_address"];?>"><img src="images/icons/mail.gif" border="0"></a></td>
									<td class="dataTableContent" align="left"><?php //echo $content["user_added"];?></td>
									<td class="dataTableContent" align="left"><?php //echo $content["user_added"];?></td>
									<td  class="dataTableContent" align="right" colspan="4"><?php echo $content["status"];?></td>
									<td  class="dataTableContent"  colspan="4" align="right"><?php echo $currencies->format($content["amount"]);?></td>
					   	            </tr>
						
						<?php 
							} 	
							$sub+=$content["amount"];						
							$prod_size=$size[$item_id][0]['size'];
							if($icnt==($prod_size-1)) {
						?>
								<tr height="20">
								<td class="dataTableContent" colspan="12" align="right" valign="middle">
								<b><?php echo TEXT_TOTAL;?></b></td>
								<td  align="right" class='dataTableContent'>
									<?php  //echo $output_array[$item_id][$icnt]['content'];
									
									echo $currencies->format($details[$item_id]['contents'][$prod_size-1]['gamount']);?>
								</td>
								
							</tr>
							<tr> <td colspan="15"><?php echo tep_draw_separator();?></td> </tr>
						<?php } ?>
						<?php
						
						$row_cnt++;
					} // $icnt
					} //$key?>
					<tr>
					<td  class="dataTableContent" align="right" colspan="12"><b><?php echo TEXT_TOTAL;?></b></td>
					<td align="right" class="dataTableContent"> <?php echo $currencies->format($sub); ?></td>
					</tr>
					
					
			<?php	} else { //$found_results
					echo '<tr><td colspan="' . (9+$tax+$payment_col_count) . '" class="main" align="center">' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
				}
			}
				?>
<?php		
}

function display_total($show_total=false,$prd_type) { 
	global $products_id, $type, $where, $prd_where, $payment_col_count, $currencies, $payment_list, $grand_total,$grand_total_tax,$grand_payment_array,$grand_pay_array,$tax,$summary,$tax,$sales_by_order,$page,$grand_quan,$grand_unit_price;
	$heading=get_heading($prd_type);
	$payment=array();
	$session_table="";
	if($prd_type=='E') 	{
		$session_table = " ,events_sessions es ";
		$event_where .= " and es.sessions_id=op.products_id ";
	}	
	
	//echo "SELECT sum(op.final_price*op.products_quantity) as final_price,op.products_tax from " . 
									//	TABLE_ORDERS_PRODUCTS . " op where op.orders_id=2 group by orders_id";
		//$total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity) as quan,sum(op.final_price) as pro_total,sum(op.products_quantity*op.final_price) as total,((op.final_price*op.products_tax)/100)*op.products_quantity as total_tax,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_PRODUCTS . " p where o.orders_id=op.orders_id and p.products_id=op.products_id  " . $where . $prd_where . $type_where . " and op.products_type='" . $prd_type . "' and o.orders_status>1 group by payment_method  order by op.products_name ";
		//echo $prd_type;
			if($type==$prd_type) 
			$total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity) as quan,sum(op.final_price) as pro_total,sum(op.products_quantity*op.final_price) as total,sum(((op.final_price*op.products_tax)/100)*op.products_quantity) as total_tax,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id from " . TABLE_ORDERS . " o, " .TABLE_ORDERS_STATUS_HISTORY." os, ".  TABLE_ORDERS_PRODUCTS . " op where os.orders_id=o.orders_id and o.orders_id=op.orders_id   " . $where . $prd_where . $type_where . $status." and op.products_type='" . $prd_type . "' group by payment_method  order by op.products_name ";
		else
			$total_sql=	"SELECT sum(op.final_price) as pro_total,sum(op.products_quantity) as quan,op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity*op.final_price) as total,sum(((op.final_price*op.products_tax)/100)*op.products_quantity) as total_tax,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id from " . TABLE_ORDERS . " o, " .TABLE_ORDERS_STATUS_HISTORY . " os, ". TABLE_ORDERS_PRODUCTS . " op " . $session_table . " where os.orders_id=o.orders_id and o.orders_id=op.orders_id  " . $where . $event_where .$status. " and op.products_type='" . $prd_type . "'  group by payment_method order by op.products_name";
			
		//if($prd_type=='H')$total_sql="select sum(ot.value) as shipping_total from " . TABLE_ORDERS . " o," . TABLE_ORDERS_TOTAL . "  ot where ot.orders_id=o.orders_id and ot.value!=0 " . $where . " and ot.class='ot_shipping' and o.orders_status>1 group by o.orders_status>1";
		//echo $total_sql;
		$total_shipping = '';
		$total_query=tep_db_query($total_sql);
		$prd_total_array=array('product_type'=>$prd_type,'title'=>$heading,'total'=>0,'total_tax'=>0,'payment'=>array()); 
		while($total_result=tep_db_fetch_array($total_query)) {
			if($total_result['shipping_total']){
				$total_shipping = $total_result['shipping_total'];
			}
			//$prd_total_array['payment'][get_payment_col($total_result['payment_method'],$total_result['order_status'])]+=$total_result['total'];
			$prd_total+=$total_result['total']; 
			$prd_total_tax+=$total_result['total_tax'];
			$quan+=$total_result["quan"];
			$pro_total+=$total_result["pro_total"]; 	  
		} 
		$prd_total_array['total']=$prd_total; 
		$prd_total_array['total_tax']=$prd_total_tax;
		$prd_total_array['quan']=$quan;
		$prd_total_array['pro_total']=$pro_total;
		$payment=$prd_total_array['payment'];
		if(count($payment)>0)
			ksort($payment); 
		$grand_unit_price+=$pro_total;
		$grand_quan+=$quan;
		$grand_total+=$prd_total;
		if($tax==1)$grand_total_tax+=$prd_total_tax;
		$grand_payment_array=array();
		for($icnt=0;$icnt<count($payment_list);$icnt++) { 
			if($payment_list[$icnt]['on']>0) { 
				$grand_payment_array[$icnt]=$payment[$icnt];
				$grand_pay_array[$icnt][]=$payment[$icnt];
			}
		}

	if($show_total) {
		if($type!=$prd_type) { 
		?>
			 <tr class="dataTableHeadingTitleRow" style="cursor:pointer;cursor:hand" onClick="javascript:doChange('<?php echo $prd_type; ?>');">
				<?php
				$span=($sales_by_order==0)?3:4;
				echo '<td colspan=' . $span . '><b>' . $prd_total_array['title'] . '</b></Td>';
			?>
			<?php 
		} else if($type==$prd_type){
			 ?> 
			<tr class="dataTableHeadingTotal">
			<td class="smallText" colspan=<?php $span=($sales_by_order==0)?2:3;echo $span;?> align="right"></td>
			<td class="smallText"  nowrap align="right"><b>
			<?php echo $prd_total_array['title'] . '&nbsp;Total';?> 
				</b></Td>
			<?php 
		}
			 ?>
			
			<td class="dataTableContent" align="right" >
			
			</td>
			<td class="dataTableContent" align="right" >
			
			</td>
			
			<td class="dataTableContent" align="right" colspan="12" >
			<?php 
				//if($prd_total)echo $currencies->format($prd_total);
				//if($total_shipping)echo $currencies->format($total_shipping);
			?>
			</td>
			
			<?php 
				
				for($icnt=0;$icnt<count($payment_list);$icnt++) { 
					if($payment_list[$icnt]['on']>0) { 	?>
				<Td class="dataTableContent" align="right" >
				<?php 
					if($payment[$icnt]>0) echo $currencies->format($payment[$icnt]); 
				?>
				</Td>
				<?php 
					}
				} //display the Total
			 }
			 ?>	
		</tr>	
<?php 		
 } 
function get_grand_total($grand_total,$grand_total_tax,$grand_pay_array,$grand_unit_price,$grand_quan) {/*
	global $where, $prd_where, $payment_list, $payment_count, $currencies, $grand_total,$grand_total_tax,$grand_pay_array,$tax,$summary,$sales_by_order,$grand_unit_price,$grand_quan;
	echo '<tr  class="dataTableHeadingTotal">';
	$span=($sales_by_order==0)?2:3;
	echo '<td align="right" class="dataTableHeadingContent" colspan=' .$span . '></td>';
	echo '<td  class="dataTableHeadingContent"align=right ></td>';
	//echo '<td  class="dataTableHeadingContent"align=right ><b>Grand Total</b></td>';
	if($sales_by_order==0)
	{
	echo '<td  class="dataTableHeadingContent"  align="right">' . (($grand_unit_price)?$currencies->format($grand_unit_price):'') . '</td>' ;
	echo '<td  class="dataTableHeadingContent" align="right">' . (($grand_quan)?$grand_quan:'') . '</td>' ;
	}
	echo '<td  class="dataTableHeadingContent"  align="right">' . (($grand_total)?$currencies->format($grand_total):'') . '</td>' ;
	if($tax==1)	echo '<td class="dataTableHeadingContent"  align="right">' . (($grand_total_tax)?$currencies->format($grand_total_tax):'') . '</td>';
	for($icnt=0;$icnt<count($payment_list);$icnt++) {
		if($payment_list[$icnt]['on']==1) {
			$pay_total=0;
			for($jcnt=0;$jcnt<count($grand_pay_array[$icnt]);$jcnt++) {
				$pay_total+=$grand_pay_array[$icnt][$jcnt];
			}
			echo '<td class="dataTableHeadingContent"  align="right">' . (($pay_total)?$currencies->format($pay_total):'') . '</td>';
		}
	}
	echo '</tr>';
*/} 

function get_heading($prd_type) { 
 	if($prd_type=='P') $heading=TEXT_HEADING_PRODUCTS;
	else if($prd_type=='S') $heading=TEXT_HEADING_SUBSCRIPTIONS;
	else if($prd_type=='E') $heading=TEXT_HEADING_EVENTS;
	else if($prd_type=='V') $heading=TEXT_HEADING_SERVICES;
	
	return $heading;
}	 
function print_total_row($unit_subtotal,$all_subtotal,$all_subtax,$quan_subtotal,$prt=''){/*
	global $payment_list,$payment_count,$currencies,$prd_sub_total,$type,$tax,$summary,$sales_by_order,$sort_manufact,$payment_col_count;
		echo "<tr>";
		
		if( $summary!=1){
		 	echo '<td class="smallText" align="right" colspan=3></td><td align=right class=smalltext><b>'. TEXT_SUBTOTAL .'</b></td>';
		}else if($sales_by_order==1 && $summary==1) echo '<td colspan=3 class="smallText" align="right"</td><td  class=smalltext><b>'. TEXT_SUBTOTAL .'</b></td>';
		else if($sales_by_order==0 && $summary!=1) echo "<td  colspan=2 >&nbsp;</td><td align=right  class='smalltext'><b>". TEXT_SUBTOTAL ."</b></td>";
		else if($sales_by_order==0 && $summary==1 && $sort_manufact==1){ 
			echo '<td  colspan=2>&nbsp;</td><td  class="smallText" align="right"><b>'. TEXT_SUBTOTAL .'</b></td>'; 
		}else if(($sales_by_order==0 && $summary==1 && $sort_manufact==0)) {
			 echo '<td colspan=2>&nbsp;</td><td  class="smallText" align="right"><b>'. TEXT_SUBTOTAL .'</b></td>'; 
		} 
		
			if($summary==1){   
				echo '<td  class="smallText" align="right">' . $currencies->format($unit_subtotal) .'</td>';
				echo '<td  class="smallText"  align="right">'. $quan_subtotal .'</td>';
			}else {
				echo '<td  class="smallText" align="right">' . $currencies->format($unit_subtotal) .'</td>';
				echo '<td  class="smallText"  align="right">'. $quan_subtotal .'</td>';
			}
		
		echo '<td  class="smallText"  align="right">'. $currencies->format($all_subtotal) .'</td>';
		if($tax==1){
			echo '<td  class="smallText"  align="right">'. $currencies->format($all_subtax) .'</td>';
		} 
		//echo '<tr height="20"><td><td><td class="smallText" align="right"><b>' . TEXT_SUBTOTAL . '<b></td><td class="smallText" align="right">'  . $currencies->format($unit_subtotal) . '</td><td class="smallText" align="right">' . $quan_subtotal . '</td><td class="smallText" align="right">' . $currencies->format($all_subtotal) . '</td>';
		
		$pay_count =1;  
		for ($jcnt=0;$jcnt<$payment_count;$jcnt++){
		 if ($payment_list[$jcnt]["on"]==0) continue;
			if ($payment_list[$jcnt]['subtotal']>0){
				$prd_sub_total+=$payment_list[$jcnt]['subtotal'];
				$cnt_payment++;
				echo '<td class="dataTableContent" align="right" >' .  $currencies->format($payment_list[$jcnt]['subtotal']) .'</td>';
				$pay_count++;
			} else {
				echo '<td class="dataTableContent" align="right" >&nbsp;</td>';
			}
			$payment_list[$jcnt]['subtotal']=0;
		}
	echo '</tr>';
	if($prt!="") {
		display_total(true,$type);
	} 
*/}


function print_total_row_excel($unit_subtotal,$all_subtotal,$quan_subtotal,$prt="",&$unit_tax,$all_tax=""){
	global $payment_list,$payment_count,$currencies,$where,$prd_where,$type,$tax,$sales_by_order;
	$payment=array();
	if($type=='H')
	{
			$result=sprintf(",,,,\"%s\",\"%s\",\"%s\"," , TEXT_SUBTOTAL ,number_format($quan_subtotal,2),$currencies->format($unit_subtotal));
			return $result;
	}
	if($sales_by_order==1){
		if($tax==1){
			$result=sprintf(",,,\"%s\",\"%s\",\"%s\"," , TEXT_SUBTOTAL ,$currencies->format($all_subtotal),$currencies->format($unit_tax));
		}else{
			$result=sprintf(",,,\"%s\",\"%s\"," , TEXT_SUBTOTAL ,$currencies->format($all_subtotal));
		}
	}else{
		if($tax==1){
			$result=sprintf(",,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"," , TEXT_SUBTOTAL , $currencies->format($unit_subtotal), $quan_subtotal ,$currencies->format($all_subtotal),$currencies->format($unit_tax));
		}else{
			$result=sprintf(",,\"%s\",\"%s\",\"%s\",\"%s\"," , TEXT_SUBTOTAL , $currencies->format($unit_subtotal), $quan_subtotal ,$currencies->format($all_subtotal));
		}
	}
	for ($jcnt=0;$jcnt<$payment_count;$jcnt++){
		if ($payment_list[$jcnt]["on"]==0) continue;
		if ($payment_list[$jcnt]['subtotal']>0){
			$result.=sprintf("\"%s\",",$currencies->format($payment_list[$jcnt]['subtotal']));
		} else {
			$result.=',';
		}
		$payment_list[$jcnt]['subtotal']=0;
	}
	$result.="\n";
	if($prt!="") {
		$result.="\n";
			if($sales_by_order==1)$total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity*op.final_price) as total,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id,sum(op.products_quantity) as total_quan,sum(op.final_price) as unit_subtotal from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY ." os, ". TABLE_ORDERS_PRODUCTS . " op where os.orders_id=o.orders_id and o.orders_id=op.orders_id  " . $where . $status."  group by payment_method order by op.products_name";
			else $total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity*op.final_price) as total,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id,sum(op.products_quantity) as total_quan,sum(op.final_price) as unit_subtotal from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY ." os, ". TABLE_ORDERS_PRODUCTS . " op where os.orders_id=o.orders_id and o.orders_id=op.orders_id  " . $where . $prd_where .$status. " and op.products_type='" . $type . "' group by payment_method order by op.products_name";
			$total_query=tep_db_query($total_sql);
			while($total_result=tep_db_fetch_array($total_query)) {
				$prd_unit_price+=$total_result['unit_subtotal']; 
				$prd_quan+=$total_result['total_quan'];
				$prd_total+=$total_result['total'];
				//$payment[get_payment_col($total_result['payment_method'],$total_result['order_status'])]=$total_result['total'];
			}
			
		if(count($payment)>0)	
			ksort($payment);
		$heading=get_heading($type);
		if($sales_by_order==1){
			if($tax==1){
				$result.=sprintf("\"%s\",,,,\"%s\",\"%s\",", TEXT_TOTAL ,$currencies->format($prd_total),$currencies->format($all_tax)); 
			}else{
				$result.=sprintf("\"%s\",,,,\"%s\",", TEXT_TOTAL ,$currencies->format($prd_total)); 
			}
		}else{
			if($tax==1){
				$result.=sprintf("\"%s\",,,,,\"%s\",\"%s\",",$heading . ' ' . TEXT_TOTAL ,$currencies->format($prd_total),$currencies->format($all_tax)); 
			}else{
				$result.=sprintf("\"%s\",,,\"%s\",\"%s\",\"%s\",",$heading . ' ' . TEXT_TOTAL ,$currencies->format($prd_unit_price),$prd_quan,$currencies->format($prd_total)); 
			}
		}
		 for($icnt=0;$icnt<count($payment_list);$icnt++) { 
			if($payment_list[$icnt]['on']>0) {
				$result.=sprintf("\"%s\",", $currencies->format($payment[$icnt]));
			} 
		}	
	}
	
	$unit_subtotal=0;
	$all_subtotal=0;
	$quan_subtotal=0;
	$unit_tax=0;
	$all_tax=0;
	return $result;
}
function print_total_row_pdf($unit_subtotal,$all_subtotal,$quan_subtotal,$table,$widths,$prt="",$unit_tax,$all_tax=""){ 
	global $payment_list,$payment_count,$currencies, $type, $where, $prd_where,$tax,$sales_by_order,$type; 
	$payment=array();
	if($type=='H')
	{
		$cols[]=array("text"=>TEXT_SUBTOTAL,"width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3]+$widths[4],"align"=>"R","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>number_format($quan_subtotal,2),"width"=>$widths[5],"align"=>"R","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>$currencies->format($unit_subtotal),"width"=>$widths[6],"align"=>"R","style"=>"headrow","valign"=>"M");
		$table->OutputRow($cols,20);
	unset($cols);
		return;
	}
	if($sales_by_order==1){
		$cols[]=array("text"=>'',"width"=>$widths[3],"align"=>"R","style"=>"subrow","valign"=>"M");
	}
	$cols[]=array("text"=>TEXT_SUBTOTAL,"width"=>$widths[0]+$widths[1]+$widths[2],"align"=>"R","style"=>"subrow","valign"=>"M");
	if(!$sales_by_order){
		$cols[]=array("text"=>$currencies->format($unit_subtotal),"width"=>$widths[3],"align"=>"R","style"=>"subrow","valign"=>"M");
		$cols[]=array("text"=>$quan_subtotal,"width"=>$widths[4],"align"=>"R","style"=>"subrow","valign"=>"M");
	}else {
		$cols[]=array("text"=>'',"width"=>$widths[4],"align"=>"R","style"=>"subrow","valign"=>"M");
	}
	$cols[]=array("text"=>$currencies->format($all_subtotal),"width"=>$widths[5],"align"=>"R","style"=>"subrow","valign"=>"M");
	if($tax)$cols[]=array("text"=>$currencies->format($unit_tax),"width"=>$widths[6],"align"=>"R","style"=>"subrow","valign"=>"M");
	for ($jcnt=0;$jcnt<$payment_count;$jcnt++){
		if ($payment_list[$jcnt]["on"]==0) continue;  
		if ($payment_list[$jcnt]['subtotal']>0){
			$all_sub_total+=$payment_list[$jcnt]['subtotal'];
			if($payment_list[$jcnt]['name']=='Bank Transfer Payment')
				$all_pdf_bank_total+=$payment_list[$jcnt]['subtotal'];
			if($payment_list[$jcnt]['name']=='WestPac Payment')
				$all_pdf_west_total+=$payment_list[$jcnt]['subtotal'];	
				$cols[]=array("text"=>$currencies->format($payment_list[$jcnt]['subtotal']),"width"=>60,"align"=>"R","style"=>"subrow","valign"=>"M");
		} else {
			$cols[]=array("text"=>'',"width"=>60,"align"=>"R","style"=>"subrow","valign"=>"M");
		}
		if(!$sales_by_order)
			$payment_list[$jcnt]['subtotal']=0;
	} 
	$table->OutputRow($cols,20);
	unset($cols);
	if($prt!="") {
		unset($cols);
			if($sales_by_order==1) 	$total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity*op.final_price) as total,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id,op.products_tax,sum(op.final_price) as unit_price,sum(op.products_quantity) as quan from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY ." os, ". TABLE_ORDERS_PRODUCTS . " op where os.orders_id=o.orders_id and o.orders_id=op.orders_id  " . $where .$status. " group by payment_method order by op.products_name";
			else $total_sql="SELECT op.orders_id,op.products_id,op.products_name,o.date_purchased,date_format(o.date_purchased, '%H:%i%s') as time, sum(op.products_quantity*op.final_price) as total,o.payment_method,o.customers_id,o.customers_name,o.orders_status,op.orders_products_id,op.products_tax,sum(op.final_price) as unit_price,sum(op.products_quantity) as quan from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY ." os, " . TABLE_ORDERS_PRODUCTS . " op where os.orders_id=o.orders_id and o.orders_id=op.orders_id  " . $where . $prd_where .$status. " and op.products_type='" . $type . "'  group by payment_method order by op.products_name";
				$total_query=tep_db_query($total_sql);
				while($total_result=tep_db_fetch_array($total_query)) {
					$prd_unit_subtotal+=$total_result['unit_price'];
					$prd_quan_subtotal+=$total_result['quan'];
					$prd_total+=$total_result['total'];
					
					//$payment[get_payment_col($total_result['payment_method'],$total_result['order_status'])]=$total_result['total'];
				}
				$heading=get_heading($type);
				
		if($sales_by_order==1){
			$cols[]=array("text"=>' Total',"width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3]+$widths[4],"align"=>"L","style"=>"headrow");
		}else{ 
			$cols[]=array("text"=>$heading . ' Total',"width"=>$widths[0]+$widths[1]+$widths[2],"align"=>"L","style"=>"headrow");
			$cols[]=array("text"=>$currencies->format($prd_unit_subtotal),"width"=>$widths[3],"align"=>"R","style"=>"headrow");
			$cols[]=array("text"=>$prd_quan_subtotal,"width"=>$widths[4],"align"=>"R","style"=>"headrow");
		}
		 		
			$cols[]=array("text"=>$currencies->format($prd_total),"width"=>$widths[5],"align"=>"R","style"=>"headrow");
			if($tax)$cols[]=array("text"=>$currencies->format($all_tax),"width"=>$widths[6],"align"=>"R","style"=>"headrow");
			 for($icnt=0;$icnt<count($payment_list);$icnt++) { 
				if($payment_list[$icnt]['on']>0) {
					$cols[]=array("text"=>($payment[$icnt])?$currencies->format($payment[$icnt]):'',"width"=>60,"align"=>"R","style"=>"headrow");
				} 
			}	
			
			$table->OutputRow($cols,20);
	}
	$cols[]=array("text"=>'',"width"=>$table->width,"align"=>"R","style"=>"subrow","valign"=>"M");
	unset($cols);
	$cols[]=array("text"=>'',"width"=>$table->width,"align"=>"R","style"=>"subrow","valign"=>"M");
	$table->OutputRow($cols,20);
	unset($cols);
	$unit_subtotal=0;
	$all_subtotal=0;
	$quan_subtotal=0;
	$unit_tax=0;
	$all_tax=0;
	 
}

	// function to generate pdf content
	function generate_pdf(){
		global $display_header,$type,$found_results,$prd_total_array,$details,$payment_count,$currencies,$report_filename,$payment_list,$summary,$payment_col_count,$tax,$sales_by_order;
		//create pdf table class
		
		$table=new pdfTable("A4","l");
		//set margins
		$table->left_margin=20;
		$table->top_margin=20;
		$table->right_margin=5;
		$table->bottom_margin=20;
		$table->pdfInit();
		if(!$tax) $tax=0;
		// create styles for output content
		$table->AddStyle("heading","color:#727272;bgcolor:#ffffff;font:Arial;size:18;style:B");
		$table->AddStyle("user","color:#000000;bgcolor:#f1f9fe;font:Arial;size:14;style:B;border-color:#7b9ebd");
		$table->AddStyle("subhead","color:#000000;bgcolor:#7b9ebd;font:Arial;size:10;style:B");
		$table->AddStyle("headrow","color:#000000;bgcolor:#C9C9C9;font:Arial;size:10;style:B");
		$table->AddStyle("headrow1","color:#000000;bgcolor:#C9C9C9;font:Arial;size:9;style:B");
		$table->AddStyle("row","color:#000000;bgcolor:#F0F1F1;font:Arial;size:10");
		$table->AddStyle("query","color:#000000;bgcolor:#FFFFFF;font:Arial;size:11");
		$table->AddStyle("subrow","color:#000000;bgcolor:#FFFFFF;font:Arial;size:10");
		$table->AddStyle("subrowhead","color:#000000;bgcolor:#FFFFFF;font:Arial;size:10;style:B");

		// add headers
		$table->headers["text"]=$display_header;
		$table->headers["style"]="query";
		$table->headers["height"]=12;
		$table->headers["width"]="100%";
		$table->headers["cols"]=3;

		// generate coloumn widths
		
		// generate table header columns
			$cols=array();

			$widths[0]=40;
			$widths[2]=80;
			$widths[3]=80;
			$temp_width=$table->width-($widths[0]+$widths[2]+$widths[3]);
			$widths[1]=$temp_width;
			$cols=array();

			$cols[]=array("text"=>TEXT_INDEX,"width"=>$widths[0],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>TEXT_CLIENT,"width"=>$widths[1],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>TEXT_STATUS,"width"=>$widths[2],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>TEXT_AMOUNT,"width"=>$widths[3],"align"=>"L","style"=>"headrow","valign"=>"M");
		$table->tableheaders["text"]=$cols;
		unset($cols);
		if ($found_results) {
		reset($details);
		$prev_product_id=-1;
		$prev_products_name="";
		$prev_attribute_id='-1';
		$row_cnt=1;
		$all_tax=0;
		$orders_id=0;
		$display_orders=0;
		while(list($key,)=each($details)){
			$row=&$details[$key];
			$cols[]=array("text"=>$row['name'],"width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3],"align"=>"L","style"=>"headrow","valign"=>"M");
			$table->OutputRow($cols,20);
			unset($cols);
			$sub_total=0;
			$contents=&$row["contents"];
			//print_r($contents);
			for ($icnt=0,$n=count($contents);$icnt<$n;$icnt++){
				$content=&$contents[$icnt];
				if (!$summary){
						$cols[]=array("text"=>$row_cnt,"width"=>$widths[0],"align"=>"L","style"=>"row","valign"=>"M");
						$cols[]=array("text"=>$content["cname"],"width"=>$widths[1],"align"=>"L","style"=>"row","valign"=>"M");
						$cols[]=array("text"=>$content["status"],"width"=>$widths[2],"align"=>"L","style"=>"row","valign"=>"M");
						$cols[]=array("text"=>$currencies->format($content["amount"]),"width"=>$widths[3],"align"=>"R","style"=>"row","valign"=>"M");
					$sub_total+=$content['amount'];
					$table->OutputRow($cols,20);
					unset($cols);
				}  //not summary
			} // for 	
			$cols[]=array("text"=>TEXT_TOTAL,"width"=>$widths[0]+$widths[1]+$widths[2],"align"=>"L","style"=>"subrow","valign"=>"M");
			$cols[]=array("text"=>$currencies->format($sub_total),"width"=>$widths[3],"align"=>"R","style"=>"subrow","valign"=>"M");
			$table->OutputRow($cols,20);
			unset($cols);
		}  // while  
	} else {
		$cols[]=array("text"=>REPORT_NO_RESULTS,"width"=>"100%","align"=>"C","style"=>"subrow","valign"=>"M");
		$table->OutputRow($cols,15);
		unset($cols);
	}
	// output pdf file
	$table->Render($report_filename .".pdf");
}

//function to get excel format csv datas
function generate_excel(){
	global $type,$details,$filename,$payment_list,$payment_count,$found_results,$report_filename,$currencies,$summary,$payment_col_count,$tax,$sales_by_order;
	if($type!='H')
	{
		if($sales_by_order==1){
			if($tax){
				$res=sprintf("%s,%s,%s,%s,%s,%s",TEXT_INDEX,TEXT_CLIENT,TEXT_ORDER_ID,TEXT_SALE_DATE,TEXT_TOTAL,TEXT_TAX);	
			}else if(!$tax) {
				$res=sprintf("%s,%s,%s,%s,%s",TEXT_INDEX,TEXT_CLIENT,TEXT_ORDER_ID,TEXT_SALE_DATE,TEXT_TOTAL);
			}
		}else{
			if($tax){
				$res=sprintf("%s,%s,%s,%s,%s,%s,%s",TEXT_INDEX,TEXT_CLIENT,TEXT_SALE_DATE,TEXT_UNIT_PRICE,TEXT_SOLD,TEXT_TOTAL,TEXT_TAX);	
			}else if(!$tax) {
				$res=sprintf("%s,%s,%s,%s,%s,%s",TEXT_INDEX,TEXT_CLIENT,TEXT_SALE_DATE,TEXT_UNIT_PRICE,TEXT_SOLD,TEXT_TOTAL);
			}
		}
		$result.=$res;
		for ($icnt=0;$icnt<$payment_count;$icnt++){
			if ($payment_list[$icnt]["on"]==0) continue;
			$name=(strlen($payment_list[$icnt]["name"])>6?substr($payment_list[$icnt]["name"],0,6):$payment_list[$icnt]["name"]);
			$result.=',' .  $name;
		}
	}
	else
	{
		$res=sprintf("%s,%s,%s,%s,%s,%s,%s",TEXT_INDEX,TEXT_CUSTOMER_NAME,TEXT_ORDER_ID,TEXT_LOCATION,TEXT_SHIPPING_METHOD,TEXT_WEIGHT,TEXT_COST);	
		$result.=$res;
	}
	$result.="\n";

	if ($found_results) {
		reset($details);
		$prev_product_id=-1;
		$prev_products_name = "";
		$prev_attribute_id='-1';
		$row_cnt=1;
		//$unit_subtotal=0;
		$unit_total=0;
	//	$all_subtotal=0;
		$all_total=0;
	//	$unit_tax=0;
		$all_tax=0;
		
		while(list($key,)=each($details)){
			$row=&$details[$key];
			$splt_key=split("-",$key);
			if (count($splt_key)>1){   
				if ($splt_key[0]!=$prev_product_id && $sales_by_order==0){
					if ($unit_subtotal>0) $result.=print_total_row_excel($unit_subtotal,$all_subtotal,$quan_subtotal,'',$unit_tax,'');
					$result.= '"' . $row["name1"] . "\"\n";    
					$prev_attribute_id=-1;      
					$prev_product_id=$splt_key[0]; 
					$unit_subtotal=0;
					$all_subtotal=0;
					$unit_tax=0;
					$quan_subtotal=0;
				}  
				if ($key!=$prev_attribute_id && $sales_by_order==0){  
					if ($unit_subtotal>0) $result.=print_total_row_excel($unit_subtotal,$all_subtotal,$quan_subtotal,'',$unit_tax,'');
					$result.='"  ' . $row["name"] . "\"\n"; 
					$prev_attribute_id=$key; 
					$unit_subtotal=0;
					$all_subtotal=0;
					$unit_tax=0;
					$quan_subtotal=0;
				} 
			} else { 
				if (($splt_key[0]!=$prev_product_id || $prev_attribute_id!=-1) && $sales_by_order==0){
					if ($unit_subtotal>0 && $row["name"]!=$prev_products_name) $result.=print_total_row_excel($unit_subtotal,$all_subtotal,$quan_subtotal,'',$unit_tax,'');
					if ($splt_key[0]!=$prev_product_id && $row["name"]!=$prev_products_name){
					 $result.='"' . $row["name"] . "\"\n";
					 $quan_subtotal=0;
					$unit_subtotal=0;
					$all_subtotal=0;
					$unit_tax=0;
					 }
					$prev_product_id=$splt_key[0];
					$prev_products_name = $row["name"];
					$prev_attribute_id=-1;
				//	$quan_subtotal=0;
				}
			}

			$contents=&$row["contents"];	
			for ($icnt=0,$n=count($contents);$icnt<$n;$icnt++){
				$content=&$contents[$icnt];
				if($type!='H')
				{
					  if($sales_by_order==1 && !$summary){
						if($tax){
							$result.=sprintf("%s,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",$row_cnt,$content["cname"],$content["orders_id"],$content["date"],$currencies->format($content["tprice"]),$currencies->format($content["ptax"]));
						}else if(!$tax){
							$result.=sprintf("%s,\"%s\",\"%s\",\"%s\",\"%s\"",$row_cnt,$content["cname"],$content["orders_id"],$content["date"],$currencies->format($content["tprice"]));	
						}
					}else if(!$summary){
						if($tax){
							$result.=sprintf("%s,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",$row_cnt,$content["cname"],$content["date"],$currencies->format($content["uprice"]),$content["quan"],$currencies->format($content["tprice"]),$currencies->format($content["ptax"]));
						}else if(!$tax){
							$result.=sprintf("%s,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",$row_cnt,$content["cname"],$content["date"],$currencies->format($content["uprice"]),$content["quan"],$currencies->format($content["tprice"]));	
						}
					}
					if (!$summary){
						
						for ($jcnt=0;$jcnt<$payment_count;$jcnt++){
							if ($payment_list[$jcnt]["on"]==0) continue;
							if ($jcnt==$content["col_pos"]){
								$result.=',"' . $currencies->format($content["tprice"]).'"';
								$payment_list[$content["col_pos"]]["subtotal"]+=$content["tprice"];
							} else {
								$result.=",";
							}
						}
						$row_cnt++;
					$result.="\n";
				} else { // $summary
					for ($jcnt=0;$jcnt<$payment_count;$jcnt++){
						if ($payment_list[$jcnt]["on"]==0) continue;
						if ($jcnt==$content["col_pos"]){
							$payment_list[$content["col_pos"]]["subtotal"]+=$content["tprice"];
						}
					}
					//$result.=',"'.$currencies->format($content["amount_received"]).'","'.$currencies->format($content["amount_due"]).'","'.$currencies->format($content["site_margin"]).'"';
				} 
			}
			else
			{
				$ship_method=split('-',$content["shipping_method"]);
				$result.=sprintf("%s,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",$row_cnt,$content["cname"],$content["orders_id"],$content["location"],$ship_method[0],$content["weight"],$currencies->format($content["cost"]));
				$result.="\n";
				$row_cnt++;
			}
				$unit_subtotal+=$content["uprice"];
				$all_subtotal+=$content["tprice"];
				if($type!='H')
					$quan_subtotal+=$content["quan"];
				else
					$quan_subtotal+=$content["weight"];
				$unit_tax+=$content["ptax"];
				$all_tax+=$content["ptax"];
			 } // $jcnt
		} // $icnt
		if ($unit_subtotal>0) $result.=print_total_row_excel($unit_subtotal,$all_subtotal,$quan_subtotal,'prt',$unit_tax,$all_tax);
	} else {
		$result.=REPORT_NO_RESULTS . "\n";
	}
	tep_write_text_file($report_filename . ".csv",$result);
}

function cmp($a, $b) 
{
	global $details;
	$atext=$details[$a]["name"] . $details[$a]["name1"];
	$btext=$details[$b]["name"] . $details[$b]["name1"];
   if ( $atext== $btext) {
       return 0;
   }
   return ($atext < $btext) ? 1 : -1;
}
function get_categories_name($product_id,$display=''){
	if(!$product_id) return;
	
	$categories_desc=tep_db_query("select c.categories_id,categories_name from ".TABLE_CATEGORIES." c LEFT JOIN ".TABLE_CATEGORIES_DESCRIPTION." cd ON(c.categories_id=cd.categories_id) LEFT JOIN ".TABLE_PRODUCTS_TO_CATEGORIES." pTc ON(cd.categories_id=pTc.categories_id) where pTc.products_id=$product_id group by c.categories_id");
	if(tep_db_num_rows($categories_desc)>0){
		$categories=tep_db_fetch_array($categories_desc);
		if($display=='cat_id')
			return $categories['categories_id'];
		else if($display=='')
			return $categories['categories_name'];
		
	} 
}
?>

<?php  function get_result(){
global $query_split,$type,$HTTP_GET_VARS,$details,$page,$payment_count,$payment_list,$tax,$query_split_numrows,$summary,$sales_by_order;
?> 
	<table border="0" width="100%" cellspacing="0" cellpadding="2">
	<?php if(REPORT_MAX_ROWS_PAGE<$query_split_numrows){?>
			<tr>
			<td>
				<table border="0" width="100%" cellspacing="0" cellpadding="2">
					<tr> 
						<td class="smallText" align="left">
							<?php //echo tep_get_report_params();
							echo $query_split->display_links($query_split_numrows, REPORT_MAX_ROWS_PAGE, REPORT_MAX_LINKS_PAGE, $page,tep_get_report_params()); ?>
						</td>
					</tr>
				</table>
			</td>
		</tr>
	<?php } ?>
	<tr>
		<td>
			<table border="0" width="100%" cellpadding="3" cellspacing="0">
			<tr class="dataTableHeadingTitleRow">
					<td  class="dataTableHeadingTitleContent" width="3%"><?php echo TEXT_INDEX;?></td>
					<td class="dataTableHeadingTitleContent" align="left" ><?php echo "&nbsp;&nbsp;&nbsp;&nbsp;".TEXT_CLIENT;?></td>
					<td class="dataTableHeadingTitleContent"  align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  width="15%" align="center"><?php  echo "Email";?></td>
					<td class="dataTableHeadingTitleContent"  align="center">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  align="center">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  width="10%" align="right"><?php echo "Status";?></td>
					<td class="dataTableHeadingTitleContent"  width="10%" align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  width="10%" align="right">&nbsp;</td>
					<td class="dataTableHeadingTitleContent"  align="right" width="15%"><?php echo "Amount";?></td>
					
					
				</tr>
				<tr><td colspan="15" height="5"></td></tr>
				<?php 
				if(HIDE_FROM_BACKEND_MENU_PRODUCTS=='false') { ?>
				<?php if($type!="P") 
						getDetails('P',false);
					 else if($type=='P'){
					 	 getDetails($type,true);
					 	 echo '<div id="fetch_report_product"></div>';
					}
					
				?>
				<?php } 
				if(HIDE_FROM_BACKEND_MENU_EVENTS=='false') { ?>
					<?php 
						if($type!='E')
							getDetails('E',false);
						else if($type=='E'){
							getDetails($type,true);
							echo '<div id="fetch_report_event"></div>';
						}
					 ?>
				<?php } 
				if(HIDE_FROM_BACKEND_MENU_SUBSCRIPTIONS=='false') { ?>
					<?php 
						if($type!='S') 
							getDetails('S',false);
						else if($type=='S') {
							getDetails($type,true);
							echo '<div id="fetch_report_subscription"></div>';
						}
					 ?>
				<?php } 
				if(HIDE_FROM_BACKEND_MENU_SERVICES=='false') { ?>
					<?php  
						if($type!='V') 
							getDetails('V',false);
						else if($type=='V'){ 
							getDetails($type,true);
							echo '<div id="fetch_report_service"></div>';
						}
					 ?>
				<?php } 
				if(HIDE_FROM_BACKEND_MENU_PRODUCTS=='false' && HIDE_FROM_BACKEND_MENU_EVENTS=='false' && HIDE_FROM_BACKEND_MENU_SUBSCRIPTIONS=='false' && HIDE_FROM_BACKEND_MENU_SERVICES=='false') { ?>
						<?php 	//get_grand_total($grand_total,$grand_total_tax,$grand_pay_array,$grand_unit_price,$grand_quan);  ?>
			</table> </td></tr></table>
<?php 	}
 }
 ?>
 
 <script language="javascript">
	function nav_page(page){
		doReport(1,page);
	}
	</script>

  <script language="javascript">
  doChange('<?php echo $btype;?>');
  </script>

<input type="hidden" name="products_type">
