<?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('includes/classes/pdfTable.php');  
  define(BOX_WIDTH1,'125');
  tep_delete_temp_files("reports_pickpack_" . $login_id);
  tep_delete_temp_files("reports_invoice_" . $login_id);
  tep_delete_temp_files("reports_packslip_" . $login_id);
  tep_delete_temp_files("reports_backorder_" . $login_id);  
  $date_offset=(defined('EVENTS_SERVER_DATE_OFFSET')?EVENTS_SERVER_DATE_OFFSET:0);
  // pdf related
  	$col_width=Array();
  	$page_height=0;
 	$page_width=0;
	$row_height=11;
	$font_name="Arial";
	$font_size=10;
	$pdf="";
	$header_color=array(201,201,201);
	$row_color=array(240,241,241);
	// 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_POST_VARS;
		if (isset($input_params["post_action"])){
			tep_set_session_value("rep_params",$HTTP_POST_VARS);
		} else {
			tep_set_session_value("rep_params",array());
		}
	}
	$start_date = (isset($input_params['txt_start_date'])?tep_convert_date_raw($input_params['txt_start_date']):'');
	$end_date = (isset($input_params['txt_end_date'])?tep_convert_date_raw($input_params['txt_end_date']):getServerDate());
	$category_id = (isset($input_params['sel_category'])?$input_params['sel_category']:0);
	$detailed_view = (isset($input_params['chk_detailed_view'])?true:false);
	$hide_backorders = (isset($input_params['chk_hide_backorders'])?true:false);
	$exp_product_id=(isset($input_params['exp_product_id'])?$input_params['exp_product_id']:0);
	$formaction=(isset($input_params['formaction'])?$input_params['formaction']:'');
	$flag=(isset($HTTP_GET_VARS['flag'])?$HTTP_GET_VARS['flag']:'');
	$check_products=(isset($input_params['check_products'])?$input_params['check_products']:'');
	$params=(isset($HTTP_GET_VARS['params'])?$HTTP_GET_VARS['params']:'');
	$cat_id=(isset($HTTP_GET_VARS['cat_id'])?$HTTP_GET_VARS['cat_id']:'');
   $expand_all=(isset($input_params['expand_all'])?$input_params['expand_all']:'0');
   if($expand_all) $category_id='-1'; 
	$params_array=split("_",$params);
	$sel_pids=$params_array[2];
	if($start_date=="") {
		$res = tep_db_query("SELECT '".getServerDate()."' - INTERVAL 1 MONTH");
		$row = mysql_fetch_array($res);
		$start_date = $row[0]; 
	}
	// date_format(o.date_purchased,'%Y-%m-%d')>='" . $date_begin . "'" . " and date_format(o.date_purchased,'%Y-%m-%d')<='" . $date_end . "'
	$date_clause = " and (date_format(o.date_purchased,'%Y-%m-%d')>='". $start_date ."' and date_format(o.date_purchased,'%Y-%m-%d')<='" . $end_date . "')";
	if($hide_backorders)
		$where_clause=" and ord.orders_products_status!=4";
	$product_ids="";
	$order_ids="";
	$category_arrays = tep_get_category_tree();
  	$sql = "select cd.categories_id ,cd.categories_name from ". TABLE_CATEGORIES_DESCRIPTION . " cd where cd.language_id='" . $languages_id . "' order by  cd.categories_name";
  	$cate_sql=$sql;
  	//$category_rec = tep_db_query($sql);
  	
	//while($row=tep_db_fetch_array($category_rec))
	for($i=1;$i<sizeof($category_arrays);$i++)
		$category_array[$row[categories_id]]=$category_arrays[$i]['text']; 
	$set_all_delivered=true;
	switch($formaction)
	{
		case 'backorder': 
		 
	//		$customer_ids="";
	//		echo $product_ids;
		/*	if ($product_ids!="")
			{
				$cus_sql1="select distinct(o.customers_id) from " . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and ord.orders_products_status=4 and ord.products_id in(" . $product_ids . ") ";
    	        $customer_rec = tep_db_query($cus_sql1);
				while($rec = mysql_fetch_assoc($customer_rec)) {
					$customer_ids.=$rec["customers_id"] . ",";
				}
				if ($customer_ids!=""){
					$customer_ids=substr($customer_ids,0,-1);
					$cus_where=" and o.customer_id not in (" . $customer_ids . ")";
				}
			} */
			
			//echo $customer_ids . 'ok';
			break;
		case 'delivered':
			$set_all_delivered=false;
			set_orders_products_status('3');
			break;
		case 'available':
			$sflag=$input_params['sflag'];
			$avail_id=$input_params['available_id'];
			$asql="";
			//echo $avail_id;
			if($sflag=='p')  //product is made available
				{
					tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=2 where products_id in(" . $avail_id . ") and orders_products_status=4");
					$asql="select ord.orders_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,o.orders_id,ord.products_name,o.date_purchased as date_purchased from " . TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " c," .TABLE_ORDERS_PRODUCTS . " ord where " .
					"o.customers_id=c.customers_id and ord.products_type='P' and ord.orders_id=o.orders_id and ord.products_id in (" .$avail_id . ") " . $date_clause . ' order by ord.orders_id';	
				}else  //particular Customer order is made available 
				{
					tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=2 where orders_products_id in(" . $avail_id . ")");
		 			$asql="select ord.orders_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,o.orders_id,ord.products_name,o.date_purchased as date_purchased from " . TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " c," .TABLE_ORDERS_PRODUCTS . " ord where " .
					"o.customers_id=c.customers_id and ord.products_type='P' and ord.orders_id=o.orders_id and ord.orders_products_id in (" . $avail_id . ") " . $date_clause . ' order by ord.orders_id';	
				}
			//send mail to all customers-------
			if($asql!="")
			{
    	        $mail_query = tep_db_query($asql);
				$mail=tep_db_fetch_array($mail_query);
				//Let's build a message object using the email class
				$mimemessage = new email(array('X-Mailer: osCommerce'));
				// add the message to the object
				tep_set_time_limit(1000);
				$from_email=$HTTP_SESSION_VARS["login_email"];
				$subject="Backordered Products are Avaliable Now!!";
				$message_text="You have ordered the Product " . $mail['products_name'] . " on the date " . $mail['date_purchased'] . ".Due to unavoidable circumstances we are unable to deliver the product " .
								"for some duration.And the product is available now.Please kindly make a note on it.";
				$mimemessage->add_text($message_text);
				$mimemessage->build_message();
				$mimemessage->send($mail['customers_firstname'] . ' ' . $mail['customers_lastname'], $mail['customers_email_address'], '', $from_email, $subject);
					//============status history=========
				  $sql_res=tep_db_query($asql);
				  $prev_ord_id=0;
				  $product_names="";
				  while($row=tep_db_fetch_array($sql_res))
				  {
					if($prev_ord_id!=$row['orders_id'])
					{
						if($product_names!="")
						{
							$insert_array=array("orders_id"=>$prev_ord_id,
											"orders_status_id"=>2,
											"date_added"=>date("Y-m-d h:i:s"),
											"customer_notified"=>1,
											"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_AVAILABLE_COMMENTS,substr($product_names,0,-1)),
											"user_added"=> TEXT_ADMIN);
							tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
						}
						$product_names="";
						$prev_ord_id=$row['orders_id'];
					}
					$product_names.=$row['products_name'] . ",";
				  }
					if($product_names!="")
					{
						$insert_array=array("orders_id"=>$prev_ord_id,
										"orders_status_id"=>2,
										"date_added"=>date("Y-m-d h:i:s"),
										"customer_notified"=>1,
										"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_AVAILABLE_COMMENTS,substr($product_names,0,-1)),
										"user_added"=> TEXT_ADMIN);
						tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
					}
			}
			//====================================
			break;
		case 'backorder_pdf':
		case 'pickpack_pdf':
			$display_header="";
			if($category_id=="0")
			{
				$cat_name=TEXT_ALL_CATEGORIES;
			}
			else
			{
				$res = tep_db_query("SELECT categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_id=" . $category_id . " and language_id=" . $languages_id);
				$row = mysql_fetch_array($res);
				$cat_name = $row[0]; 
			}
			if($category_id >0)
				$products_sql="select count(ord.orders_id) as ord_count,cat.categories_id,o.customers_email_address,ord.orders_products_status as status,pd.products_name,p.products_id ,p.is_attributes,(p.products_quantity-p.products_ordered) as products_remaining,cd.categories_name from " . TABLE_ORDERS . " o," . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd," . TABLE_PRODUCTS_TO_CATEGORIES . " cat," . TABLE_ORDERS_PRODUCTS . " ord,". TABLE_CATEGORIES_DESCRIPTION . " cd where o.orders_id=ord.orders_id and ord.products_type='P' and ord.products_id=p.products_id and cat.products_id=p.products_id and pd.products_id=p.products_id and ord.orders_products_status=4  and o.orders_status=2 and cd.language_id='" . $languages_id . "' and pd.language_id='" . $languages_id . "' and cd.categories_id=cat.categories_id and cat.categories_id=" . $category_id .  $date_clause
					 . " Group by p.products_id order by cat.categories_id";
			else
				$products_sql="select count(ord.orders_id) as ord_count,cat.categories_id,o.customers_email_address,ord.orders_products_status as status,pd.products_name,p.products_id ,p.is_attributes,(p.products_quantity-p.products_ordered) as products_remaining,cd.categories_name from " . TABLE_ORDERS . " o," . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd," . TABLE_PRODUCTS_TO_CATEGORIES . " cat," . TABLE_ORDERS_PRODUCTS . " ord,". TABLE_CATEGORIES_DESCRIPTION . " cd where o.orders_id=ord.orders_id and ord.products_type='P' and ord.products_id=p.products_id and cat.products_id=p.products_id and pd.products_id=p.products_id and ord.orders_products_status=4  and o.orders_status=2 and cd.language_id='" . $languages_id . "' and pd.language_id='" . $languages_id . "' and cd.categories_id=cat.categories_id " .  $date_clause
					 . " Group by p.products_id order by cat.categories_id";
			$products_query=tep_db_query($products_sql);
			// generate the output array with product details and category headings
			$prd_array=array();
			while($products_result=tep_db_fetch_array($products_query)){
				$add_result=true;
				if($orders_products_id!="")
				  	 	$orders_products_id.=",";
				$orders_products_id.=$products_result['orders_products_id'];
				if($products_result['is_attributes']!="Y")
					$order_sql="select concat_ws(' ',cus.customers_firstname,cus.customers_lastname) as cus_name,cus.customers_id,o.orders_id,ord.products_id,o.customers_email_address,ord.products_quantity,ord.products_name,ord.products_model,ord.orders_products_id,ord.orders_products_status as status,ord.products_sku from " .  TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " cus," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and o.customers_id=cus.customers_id and ord.products_type='P' and ord.orders_products_status=4  and o.orders_status=2 and ord.products_id=" . $products_result['products_id'] . $date_clause . " order by cus.customers_firstname";
				else
					$order_sql="select concat_ws(' ',cus.customers_firstname,cus.customers_lastname) as cus_name,cus.customers_id,o.orders_id,ord.products_id,o.customers_email_address,ord.products_quantity,ord.products_name,ord.products_model,ord.orders_products_id,ord.orders_products_status as status,ord.invoice_printed,ord.packing_slip_printed,ord.products_sku,opa.* from " .  TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " cus," . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " opa where ord.orders_products_status=4  and o.orders_status=2 and opa.orders_id=o.orders_id and opa.orders_products_id=ord.orders_products_id  and ord.orders_id=o.orders_id and o.customers_id=cus.customers_id and ord.products_type='P' and ord.orders_products_status<>3 and ord.products_id=" .$products_result['products_id'] . $where_clause . $date_clause . ' order by opa.orders_products_id,opa.products_options_id';
				$order_rec = tep_db_query($order_sql);
				if(tep_db_num_rows($order_rec)>0)
					$add_result=true;
				if ($add_result){
				   if($products_result['is_attributes']!="Y"){
						while($row_p=tep_db_fetch_array($order_rec)){
							$prd_array[]=array("cus_name"=>$row_p["cus_name"],
											"orders_id"=>$row_p["orders_id"],
											"product_id"=>$row_p["products_id"],
											"products_name"=>$row_p["products_name"],
											"quantity"=>$row_p["products_quantity"],
											"orderid"=>$row_p["orders_id"],
											"model"=>tep_get_sku_ids($row_p["products_id"]),
											"sku"=>$row_p["products_sku"],
											"att_name"=>"",
											"cat_name"=>$category_array[$products_result['categories_id']]
											);
						}
					}else{
					$prev_pid=0;
					$key="";
					$row_count=tep_db_num_rows($order_rec);
					$cus_array=array();
					while($cus_row=mysql_fetch_assoc($order_rec)) {
						$p_id=$cus_row["orders_products_id"];
						if($p_id!=$prev_pid && $key!="" )
						{
							$key=substr($key,0,-1);
							$cus_array[$key][]=array("products_name"=>$prd_name,
									 "products_quantity"=>$prd_qty,
									 "cus_name"=>$cus_name,
									 "products_id"=>$prd_id,
									 "orders_products_id"=>$prev_pid,
 									 "orderid"=>$porderid,
									 "model"=>tep_get_sku_ids($prd_id,$key),
									 "sku"=>$cus_row['products_sku'],
									 "cat_name"=>$category_array[$products_result['categories_id']],
									 "att_name"=>$att_name);
									$att_name="";
									$key="";
									$prev_pid=$cus_row['orders_products_id'];
									$key=$cus_row['products_options_id'] . '{' . $cus_row['products_options_values_id'] . '}-';
									$att_name=$cus_row['products_options'] . " : " . $cus_row['products_options_values'] . chr(10).chr(13);
								}else{
									$prev_pid=$cus_row['orders_products_id'];
									$cus_name=$cus_row['cus_name'];
									$prd_name=$cus_row['products_name'];
									$prd_qty=$cus_row['products_quantity'];
									$porderid=$cus_row['orders_id'];
									$pmodel=tep_get_sku_ids($cus_row['products_id']);
									$psku=$cus_row['products_sku'];
									$prd_id=$cus_row['products_id'];
									$key.=$cus_row['products_options_id'] . '{' . $cus_row['products_options_values_id'] . '}-';
									$att_name.=$cus_row['products_options'] . " : " . $cus_row['products_options_values'] . chr(10).chr(13);
								}
							}
							if($key!="")
							{
								$key=substr($key,0,-1);
								$cus_array[$key][]=array("products_name"=>$prd_name,
														 "products_quantity"=>$prd_qty,
														 "cus_name"=>$cus_name,
														 "products_id"=>$prd_id,
 														 "orderid"=>$porderid,
														 "model"=>$pmodel,
														 "sku"=>$psku,
														 "cat_name"=>$category_array[$products_result['categories_id']],
														 "orders_products_id"=>$prev_pid,
														 "att_name"=>$att_name);
								$att_name="";
								$key="";
							}
							$prev_product_name='';
							$ord_total=0;
							
							if(isset($cus_array))
							{
								foreach($cus_array as $row1)
								{
									$prev_att_name="";
									foreach($row1 as $col1)
									{
									
										if ($prev_product_name!=$col1['products_name']){
											$prev_product_name=$col1['products_name']; 
											$disp_cusname=$prev_product_name;
										}
										else{
											$disp_cusname="";
											$td_tag="";
										}
										if ($prev_att_name!=$col1['att_name']){
											$prev_att_name=$col1['att_name']; 
											$disp_attname=$prev_att_name;
										}
										else{
											$disp_attname="";
										}
										$ord_total+=$col1['products_quantity'];
										$prd_array[]=array(	"cus_name"=> $col1['cus_name'],
											"product_id"=>$col1["products_id"],
											"products_name"=>$disp_cusname,
											"quantity"=>$col1['products_quantity'],
											"orderid"=>$col1["orderid"],
											"model"=>$col1["model"],
											"sku"=>$col1['sku'],
											"att_name"=>$disp_attname,
											"cat_name"=>$category_array[$products_result['categories_id']]);
								  }	
						      }
						  }
						//=========
					}
			  }							
		   }
		   //print_r($prd_array);
		  // exit;
			$display_header=TEXT_CATEGORY . " : " . $cat_name . "\t";
			$display_header.=TEXT_DATE . " : " . format_date($start_date) . '  ' . TEXT_TO . '  ' . format_date($end_date) . "\t";
			$display_header.=TEXT_TYPE . " : " . TEXT_BACKORDERED_ORDERS;
			generate_backorderpdf($prd_array);
			tep_redirect(DIR_WS_CATALOG . "images/reports_backorder_".$login_id ."_".time().".pdf");
		   break;
}
function set_orders_products_status($status_flag)
{
	global $input_params,$product_ids,$order_ids,$set_all_delivered,$date_clause;
	//---Products--------
	if($status_flag==3)
	{
		$include_where=" and ord.invoice_printed='1' and ord.packing_slip_printed='1' and date_add(ord.invoice_printed_time,INTERVAL 24 HOUR)>='".getServerDate()."' and date_add(ord.packslip_printed_time,INTERVAL 24 HOUR)>='".getServerDate()."'";
		$update_where=" and invoice_printed='1' and packing_slip_printed='1' and date_add(invoice_printed_time,INTERVAL 24 HOUR)>='".getServerDate()."' and date_add(packslip_printed_time,INTERVAL 24 HOUR)>='".getServerDate()."'";
	}
	else
		$include_where="";	
	$prd_ids=$input_params['chk_products'];
	$orders_products_id="";
	$update_orders_id="";
	for ($icnt=0;$icnt<sizeof($prd_ids);$icnt++)
		$product_ids.=$prd_ids[$icnt] . ",";
	if ($product_ids!=""){
		$product_ids=substr($product_ids,0,-1);
		//echo "select ord.orders_products_id from  " . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS . " o  where o.orders_id=ord.orders_id and ord.products_id in(" . $product_ids . ") and ord.products_type='P' and ord.orders_products_status<3 " . $date_clause;
		//exit;
		$temp=tep_db_query("select ord.orders_products_id from  " . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS . " o  where o.orders_id=ord.orders_id and ord.products_id in(" . $product_ids . ") and ord.products_type='P' and ord.orders_products_status<3  and o.orders_status=2 " . $date_clause);
		$total_count=tep_db_num_rows($temp);
		$temp=tep_db_query("select ord.orders_id,ord.orders_products_id from  " . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS . " o  where o.orders_id=ord.orders_id and ord.products_id in(" . $product_ids . ") and ord.products_type='P' and ord.orders_products_status<3  and o.orders_status=2 " . $date_clause . $include_where);
		tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=" . $status_flag . " where products_id in(" . $product_ids . ") and products_type='P' and orders_products_status<3 " . $update_where);
		$updated_count=tep_db_num_rows($temp);
		while($row=tep_db_fetch_array($temp))
		{
			$orders_products_id.=$row['orders_products_id'] . ",";
			if(strpos("," . $update_orders_id . ",",",".$row['orders_id'] . ",")===false)
				$update_orders_id.=$row['orders_id'] . ",";
		}
	}
	//--customer----------
	$ord_ids=$input_params['chk_orders'];
	for ($icnt=0;$icnt<sizeof($ord_ids);$icnt++)
		$order_ids.=$ord_ids[$icnt] . ",";
	if ($order_ids!=""){
		$order_ids=substr($order_ids,0,-1);
		$temp=tep_db_query("select ord.orders_products_id from  " . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS . " o  where o.orders_id=ord.orders_id and ord.orders_products_id in(" . $order_ids . ") and ord.products_type='P' and ord.orders_products_status<3  and o.orders_status=2 " .$date_clause);
		$total_count+=tep_db_num_rows($temp);
		//echo "UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=" . $status_flag . " where products_type='P' and orders_products_id in(" . $order_ids . ")" . $update_where;
		//exit;
		tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=" . $status_flag . " where products_type='P' and orders_products_id in(" . $order_ids . ")" . $update_where);
		$temp=tep_db_query("select ord.orders_id,ord.orders_products_id from  " . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS . " o  where o.orders_id=ord.orders_id and ord.orders_products_id in(" . $order_ids . ") and ord.products_type='P' and ord.orders_products_status=3  and o.orders_status=2 " .$date_clause . $include_where);
		$updated_count+=tep_db_num_rows($temp);
		while($row=tep_db_fetch_array($temp))
		{
			$orders_products_id.=$row['orders_products_id'] . ",";
			if(strpos("," . $update_orders_id . ",",",".$row['orders_id'] . ",")===false)
				$update_orders_id.=$row['orders_id'] . ",";
		}
	} 
	//echo  $total_count . ', ' . $updated_count;
	//exit;
	if($status_flag==3 && $orders_products_id!="")
	{
		$orders_products_id=substr($orders_products_id,0,-1);
		$update_orders_id=substr($update_orders_id,0,-1);
		send_email_customers($orders_products_id);
		update_order_status($update_orders_id,$orders_products_id);
	}
	if($total_count==$updated_count)
		$set_all_delivered=true;
}

function send_email_customers($orders_products_id)
{
	$sql="select o.customers_name,o.customers_email_address,o.orders_id,o.date_purchased,op.orders_products_id,op.products_name from " . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.orders_products_status=3  and o.orders_status=2 and op.orders_products_id in(" . $orders_products_id . ")";
	$sql_query=tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_query))
	{		
    	 tep_send_products_status_change_email($row['orders_id'],'3',$row['orders_products_id']);
		 //$subject=sprintf(EMAIL_TEXT_SUBJECT, $row['products_name']);	
	     //$email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_PRODUCT_NAME . '  ' . $row['products_name'] . "\n\n" . EMAIL_TEXT_DATE_ORDERED . '   ' . $row['date_purchased'] . "\n\n" . sprintf(EMAIL_TEXT_DELIVERED, $row['customers_name'],$row['products_name'],date("Y-m-d"),STORE_OWNER_EMAIL_ADDRESS);
         //tep_mail($row['customers_name'] , $row['customers_email_address'], $subject, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
		 //echo  $email . "<br>";
	}
}
function update_order_status($ord_ids,$orders_products_id)
{
  global $login_first_name;
  $updated_order_ids="";
  $ord_array=split(",",$ord_ids);
  for($icnt=0;$icnt<count($ord_array);$icnt++)
  {
  	$sql="select count(*) as cnt from " . TABLE_ORDERS_PRODUCTS . " where orders_id=" . $ord_array[$icnt];
	$sql_query=tep_db_query($sql);
	$col=tep_db_fetch_array($sql_query);
	$count_ordered=$col['cnt'];
	
  	$sql="select count(*) as cnt from " . TABLE_ORDERS_PRODUCTS . " where orders_products_status=3 and orders_id=" . $ord_array[$icnt];
	$sql_query=tep_db_query($sql);
	$col=tep_db_fetch_array($sql_query);
	$count_delivered=$col['cnt'];
	
	if($count_ordered==$count_delivered)
	{
		$updated_order_ids=$ord_array[$icnt] .",";
		tep_db_query("UPDATE " . TABLE_ORDERS . " set orders_status=3 where orders_id=" . $ord_array[$icnt]);
		//echo "update " . TABLE_ORDERS_PRODUCTS . " set item_orders_status=3 where orders_id = '" . $ord_array[$icnt] . "'"; 
		//tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set item_orders_status=3 where orders_id = '" . $ord_array[$icnt] . "'"); 
		$insert_array=array("orders_id"=>$ord_array[$icnt],
							"orders_status_id"=>3,
							"date_added"=>date("Y-m-d h:i:s"),
							"customer_notified"=>1,
							"comments"=>TEXT_STATUS_HISTORY_DELIVERED_COMMENTS,
							"user_added"=> TEXT_ADMIN);
		tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
	}
  }
  //=======update all products=================
  if($updated_order_ids!="")
  {
  	$updated_order_ids=substr($updated_order_ids,0,-1);
	$sql="select products_name,orders_id from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id in (" . $orders_products_id .") and orders_id not in(" . $updated_order_ids .") order by orders_id";
  }
  else
	$sql="select products_name,orders_id from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id in (" . $orders_products_id .")  order by orders_id";
  $sql_res=tep_db_query($sql);
  $prev_ord_id=0;
  $product_names="";
  while($row=tep_db_fetch_array($sql_res))
  {
    if($prev_ord_id!=$row['orders_id'])
	{
		if($product_names!="")
		{
			$insert_array=array("orders_id"=>$prev_ord_id,
							"orders_status_id"=>3,
							"date_added"=>date("Y-m-d h:i:s"),
							"customer_notified"=>1,
							"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_DELIVERED_COMMENTS,substr($product_names,0,-1)),
							"user_added"=> TEXT_ADMIN);
			tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
		}
		$product_names="";
		$prev_ord_id=$row['orders_id'];
	}
	$product_names.=$row['products_name'] . ",";
  }
	if($product_names!="")
	{
		$insert_array=array("orders_id"=>$prev_ord_id,
						"orders_status_id"=>3,
						"date_added"=>date("Y-m-d h:i:s"),
						"customer_notified"=>1,
						"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_DELIVERED_COMMENTS,substr($product_names,0,-1)),
						"user_added"=> TEXT_ADMIN);
		tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
	}
}
?>
<!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>
<style>
	.backorderstyle { 
	background-color: #ffb3b5;
    }
	.datatotal{padding:0px;}
</style>
<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">
function doReport(mode) {
		startDate=date_format(document.f.txt_start_date.value,'','',true);
		endDate=date_format(document.f.txt_end_date.value,'','',true);	
		if(startDate.getTime()>endDate.getTime()) {
			alert("<?php echo REPORT_START_AFTER_END?>");
			return;
		}
		document.f.exp_product_id.value='';
		document.f.submit();
	}
	function date_format(sourceDate,srcFormat,resultFormat,bolConvertObject){
			var dt;
			if (srcFormat=="")	srcFormat="<?php echo EVENTS_DATE_FORMAT;?>";
			if (resultFormat=="")	resultFormat="<?php echo EVENTS_DATE_FORMAT;?>";
			if (typeof(sourceDate)=="string"){
				if (sourceDate=="") return false;
				if (!bolConvertObject && srcFormat!="" && resultFormat==srcFormat) return sourceDate;
				var splt=sourceDate.split("-");
				if (splt.length!=3) return false;
				switch(srcFormat){
					case "d-m-Y":
						sourceDate=new Date(parseInt(splt[2],10),parseInt(splt[1],10)-1,parseInt(splt[0],10));
						break;
					case "m-d-Y":
						sourceDate=new Date(parseInt(splt[2],10),parseInt(splt[0],10)-1,parseInt(splt[1],10));
						break;

					default:
						sourceDate=new Date(parseInt(splt[0],10),parseInt(splt[1],10)-1,parseInt(splt[2],10));
				}
			}
			if (!sourceDate) return false;
			if (bolConvertObject) return sourceDate;
			var day=sourceDate.getDate();
			var month=sourceDate.getMonth()+1;
			if (day<10) day="0"+day;
			var year=sourceDate.getFullYear();
			if (month<10) month="0"+month;
			switch(resultFormat){
				case "d-m-Y":
					var textdate=day+"-"+month+"-"+year;
					break;
				case "m-d-Y":
					var textdate=month+"-"+day+"-"+year;
					break;
				default:
					var textdate=year+"-"+month+"-"+day;
					break;
			}
			return textdate;
		}
function do_expand(cat_id)
{
	if(cat_id!='-1'){
		for(icnt=0;icnt<document.f.sel_category.options.length;icnt++)
		{
			if(document.f.sel_category.options[icnt].value==cat_id)
			{
				document.f.sel_category.options[icnt].selected=true;
				document.f.submit();
				break;
			}
		}
	}
}		
/*function do_productexpand(sel_pids)
{
	alert(sel_pids);
//	if(document.f.exp_product_id.value=="") {
	document.f.chk_detailed_view.checked=true;
	document.f.exp_product_id.value=sel_pids;
//	}
	document.f.submit();
	
}  */
function doexpand(cat_id)
{

	document.f.exp_product_id.value="";
	document.f.chk_detailed_view.checked=false;
	for(icnt=1;icnt<document.f.sel_category.options.length;icnt++)
	{
		if(document.f.sel_category.options[icnt].value==cat_id)
		{
			document.f.sel_category.options[icnt].selected=true;
			document.f.submit();
			break;
		}
	}
}
function dounexpand(cat_id)
{

	document.f.exp_product_id.value="";
	document.f.chk_detailed_view.checked=false;
	document.f.sel_category.options[0].selected=true;
	document.f.submit();
}

function doproductexpand(prd_id)
{
	document.f.chk_detailed_view.checked=true;
	if(document.f.exp_product_id.value!='')
		document.f.exp_product_id.value+=',';
	document.f.exp_product_id.value+=prd_id;
	document.f.submit();
}
function doproductunexpand(prd_id)
{
	//alert(prd_id);
	p_ids=document.f.exp_product_id.value;
	p_ids="," + p_ids + ",";
	p_ids=p_ids.replace("," + prd_id + ",",",");
	p_len=p_ids.length;
	p_ids=p_ids.substr(1,p_len-2);
	if(p_ids=="")
	document.f.chk_detailed_view.checked=false;
	document.f.exp_product_id.value=p_ids;
	document.f.submit();
}
function get_pids(element)
{

var prod_ids=""
if(element.length>0) {
	for(i=0;i<element.length;i++)
	{
		if(element[i].checked)
		{
			prod_ids=prod_ids+ element[i].value + ',';
						
		}
	} 
	p_id=prod_ids.substr(0,prod_ids.length-1);
}
else
	p_id=element.value;	
	return p_id;
	
}
function dobackorder()
{
sel_pids=document.f.exp_product_id.value;
	var p_id="";
	var o_id="";
	var params="";
	if(check_selected(document.f.elements["chk_products[]"]) && check_selected(document.f.elements["chk_orders[]"])) {
		alert("<?php echo addslashes(stripslashes(ERR_SELECT_ANY_ONE));?>");
		return;
	} 
	else  {
		if(check_selected(document.f.elements["chk_products[]"])) {
			p_id=get_pids(document.f.elements["chk_products[]"]);
			document.f.check_products.value=p_id;
			params="pid_" + p_id + "_" + sel_pids;
		}
		else if(check_selected(document.f.elements["chk_orders[]"])) {
			o_id=get_pids(document.f.elements["chk_orders[]"]); 
			document.f.check_products.value=o_id;
			params="oid_" + o_id + "_" + sel_pids;
		}
	}
	

	if(validateForm(document.f))
	{
		if(confirm("<?php echo addslashes(stripslashes(TEXT_CONFIRM_BACKORDER));?>")){
			document.f.formaction.value='backorder';
		window.open('reports_products_fulfiller_mail_backorder.php?params=' + params , 'win_mail','location=no,height=500,width=700');
		}
	}
}

function mailto_backorder_customer_view(cus_id)
{
	window.open("<?php echo FILENAME_MAIL_BACKORDER;?>?swhere=<?php echo $date_clause;?>&customer_ids=" + cus_id ,"win_mail","location=no,height=550,width=735");
}
	
function mailto_backorder_customer(prd_id)
{
	window.open("<?php echo FILENAME_MAIL_BACKORDER;?>?swhere=<?php echo $date_clause;?>&product_id=" + prd_id ,"win_mail","location=no,height=500,width=735");
}
function dobackorder_pdf()
{
	document.f.formaction.value='backorder_pdf';
	document.f.target="_blank"
	document.f.submit();
	document.f.formaction.value="";
	document.f.target="_self";
}
function dopickpack_pdf1()
{
 //if(!check_selected(document.f.elements["chk_products[]"]))
	//alert("<?php echo addslashes(stripslashes(ERR_SELECT_PRODUCT));?>");
// else{
	document.f.formaction.value='pickpack_pdf';
	document.f.target="_blank"
	document.f.submit();
	document.f.formaction.value="";
	document.f.target="_self";
 // }
}
function dopickpack_pdf()
{
		prd_ids="";
		element=document.f.elements["chk_products[]"];
		if(element)
		{
			if(element.length)
			{
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked)
					{
						if(prd_ids!="") 
							prd_ids+=",";
						prd_ids+=element[icnt].value;
					}
				}
			}
			else
			{
				if (element.checked)
					prd_ids=element.value;
			}
		}
		
		if(prd_ids=="")
			prd_ids="-1";
		cat_id=document.f.sel_category.options[document.f.sel_category.selectedIndex].value;
		window.open("<?php echo FILENAME_REPORT_PICKPACK . '?start_date=' . $start_date . '&end_date='. $end_date. '&product_ids='?>" + prd_ids + '&cat_id=' + cat_id );

}
/*function dodeliver()
{
	var serr="";
	element=document.f.elements["chk_orders[]"];
		if(element.length)
		{
			for(icnt=0;icnt<element.length;icnt++)
			{
				if(element[icnt].checked){
					if(document.f.elements["pack" + element[icnt].value].value!="1" || document.f.elements["invoice" + element[icnt].value].value!="1"){
						serr="<?php echo addslashes(stripslashes(TEXT_DELIVER_ERR));?>";
						break;
					}
				}
			}
		}
		else
		{
			if(document.f.elements["pack" + element.value].value!="1" || document.f.elements["invoice" + element.value].value!="1")
				serr="<?php echo addslashes(stripslashes(TEXT_DELIVER_ERR));?>";
		}
		if(serr)
			alert(serr);
		else
		{	
			if(confirm("<?php echo addslashes(stripslashes(TEXT_CONFIRM_DELIVER));?>")){
				document.f.formaction.value='delivered';
				document.f.submit();
			}
		}
}*/
function dodeliver()
{
sel_pids=document.f.exp_product_id.value;
	var p_id="";
	var o_id="";
	var params="";
	if(check_selected(document.f.elements["chk_products[]"]) && check_selected(document.f.elements["chk_orders[]"])) {
		alert("<?php echo addslashes(stripslashes(ERR_SELECT_ANY_ONE));?>");
		return;
	} 
	else  {
		if(check_selected(document.f.elements["chk_products[]"])) {
			p_id=get_pids(document.f.elements["chk_products[]"]);
			document.f.check_products.value=p_id;
			params="pid_" + p_id + "_" + sel_pids;
		}
		else if(check_selected(document.f.elements["chk_orders[]"])) {
			o_id=get_pids(document.f.elements["chk_orders[]"]); 
			document.f.check_products.value=o_id;
			params="oid_" + o_id + "_" + sel_pids;
		}
	}
	
	if(validateForm(document.f))
	{
		if(confirm("<?php echo addslashes(stripslashes(TEXT_CONFIRM_DELIVER));?>")){
			document.f.formaction.value='delivered';
			document.f.submit();
		}
	}
}
function doavailable(flag,a_id)
{
	document.f.sflag.value=flag;
	document.f.available_id.value=a_id;
	document.f.formaction.value='available';
	document.f.submit();
}
function selectAll(sid){
	if(sid==1){
		var element=document.f.elements["chk_products[]"];
		var status=document.f.chk_selectall_prd.checked;
	}
	else{
		var element=document.f.elements["chk_orders[]"];
		var status=document.f.chk_selectall_cus.checked;
	}
	if(element)
	{
		if (element.length){
			for (icnt=0;icnt<element.length;icnt++){
				element[icnt].checked=status;
			}
		} else 
			element.checked=status;			
	}
}
function validateForm(frm){
		if(!check_selected(frm.elements["chk_products[]"]) && !check_selected(frm.elements["chk_orders[]"]))
		{
			alert("<?php echo addslashes(stripslashes(ERR_SELECT_ORDER));?>");
			return false;
		}
		return true;
	}
function check_selected(element)
{
		var err="";
		if(element){
			if (element.length){
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked) break;
				}
				if (icnt>=element.length)
					err="1";
			} else {
				if (!element.checked)
					err="1";
			}
			if (err!="") 
				return false;
		}
		else
			return false;
		return true;
}	
function doinvoice_pdf()
{
	prd_ids="";
	element=document.f.elements["chk_products[]"];
	if(element)
		{
			if(element.length)
			{
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked)
					{
						if(prd_ids!="") 
							prd_ids+=",";
						prd_ids+=element[icnt].value;
					}
				}
			}
			else
			{
				if (element.checked)
					prd_ids=element.value;
			}
		}
		ord_ids="";
		element=document.f.elements["chk_orders[]"];
		if(element)
		{
			if(element.length)
			{
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked)
					{
						if(ord_ids!="") 
							ord_ids+=",";
						ord_ids+=element[icnt].value;
					}
				}
			}
			else
			{
				if (element.checked)
					ord_ids=element.value;
			}
		}
		if(prd_ids=="")
			prd_ids="-1";
		if(ord_ids=="")
			ord_ids="-1";
		cat_id=document.f.sel_category.options[document.f.sel_category.selectedIndex].value;
		window.open("<?php echo FILENAME_REPORT_INVOICE . '?start_date=' . $start_date . '&end_date=' . $end_date . '&product_ids='?>" + prd_ids + '&cat_id=' + cat_id + '&order_ids=' + ord_ids);
}
function dopackslip_pdf()
{
		prd_ids="";
		element=document.f.elements["chk_products[]"];
		if(element)
		{
			if(element.length)
			{
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked)
					{
						if(prd_ids!="") 
							prd_ids+=",";
						prd_ids+=element[icnt].value;
					}
				}
			}
			else
			{
				if (element.checked)
					prd_ids=element.value;
			}
		}
		ord_ids="";
		element=document.f.elements["chk_orders[]"];
		if(element)
		{
			if(element.length)
			{
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked)
					{
						if(ord_ids!="") 
							ord_ids+=",";
						ord_ids+=element[icnt].value;
					}
				}
			}
			else
			{
				if (element.checked)
					ord_ids=element.value;
			}
		}
		if(prd_ids=="")
			prd_ids="-1";
		if(ord_ids=="")
			ord_ids="-1";
		cat_id=document.f.sel_category.options[document.f.sel_category.selectedIndex].value;
		window.open("<?php echo FILENAME_REPORT_PACKSLIP . '?start_date=' . $start_date . '&end_date=' . $end_date . '&product_ids='?>" + prd_ids + '&cat_id=' + cat_id + '&order_ids=' + ord_ids);
}
 
</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<div id="spiffycalendar" class="text"></div>
<?php require(DIR_WS_INCLUDES . 'header.php');?>
<table border="0" width="100%" cellspacing="2" cellpadding="2">
<tr> 
	<!-- body_text //-->	  
	<td align=left valign="top"  width="100%" >
		<table border="0" width="100%" cellspacing="0" cellpadding="2">
				<?php if($formaction=="delivered" && $set_all_delivered==false )
					{?><tr>
						<td class="messageStackWarning">
						<?php echo TEXT_DELIVER_ERR ;?>
						</td></tr>
					<?php }?>
			 <tr>
				<!--<td class="pageHeading"><?php //echo HEADING_PRODUCTS_FULFILMENT;?></td>!-->	
			</tr>
				<tr>
     		    <TD>
				<FORM action="<?php echo FILENAME_REPORTS_FULFILLER;?>" id="f" name="f" method="post">
				  <input type="hidden" name="page" value="1">
				  <input type="hidden" name="post_action" value="1">
				  <table cellspacing="3" cellpadding="2" class="searchArea" width="100%" border="0">
 					<?php $_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
 					   <tr> 
					   <td><?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>&nbsp;&nbsp;&nbsp;
							    <?php echo 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>
						</td> 
						
						<td><label><input type="checkbox" name="chk_hide_backorders" <?php echo ($hide_backorders==true?"checked":"") ?>><?php echo REPORT_HIDE_BACKORDERS?> </label></td>
						<td ><label><input type="checkbox" name="chk_detailed_view" <?php echo (($detailed_view==true)?"checked":"") ?>><?php echo REPORT_DETAILED_VIEW?> </label></td>
						<td><?php echo '<a href="javascript:doReport(1);">' . tep_image_button('button_report_search.gif', IMAGE_SEARCH_DETAILS) . '</a>'; ?></td>
					</tr>
					<tr>      
					<td><?php echo TEXT_ALL_CATEGORIES;?>&nbsp;<?php echo tep_draw_pull_down_menu("sel_category",tep_get_category_tree('','','','','',TEXT_ALL_CATEGORIES),$category_id);?><!--<select name="sel_category" style="width:300px">
						<!--<select name="sel_category" style="width:300px">
							<OPTION value="0"><?php echo TEXT_ALL_CATEGORIES?> </OPTION>-->
    				  <!--<td><select name="sel_category" style="width:300px">
							<OPTION value="0"><?php echo TEXT_ALL_CATEGORIES?> </OPTION>
						<?php 
						 // while($row = mysql_fetch_assoc($category_rec)) {
						 for($i=1;$i<sizeof($category_arrays);$i++){
						 ?>
							<OPTION value="<?php echo $category_arrays[$i]["id"]?>" <?php echo $category_arrays[$i]["id"]==abs($category_id)?"selected":"" ?> >
							  <?php echo $category_arrays[$i]["text"] ?>
							</OPTION>
						<?php  
						  }
						?>
						  </select>
    					</td>-->
    					<td colspan="3"><?php echo tep_draw_checkbox_field('expand_all',1).' '.TEXT_EXPAND_ALL;?>
					
   					 </tr>
					
 				</table>
				</td>	
			</tr>	
			<tr ><td class="cell_bg_report_header">&nbsp;</td></tr>
			<tr>
				<td>

				<!-- table -->
				  <table border="0" width="100%">
					<tr>
						
				<?php   
				// render page navigatione
				 $sql=$cate_sql;
				 $category_rec = tep_db_query($sql);
				  $pages_last_ids = array();
				  $pgcount = 1;
				  $i=0;
				  $nrrows = count($category_rec);
				 // while($row = mysql_fetch_assoc($category_rec)) {
				 for($i=1;$i<sizeof($category_arrays);$i++){
					if($i % 10 == 0) {
						$pages_last_ids[$pgcount] = $category_arrays[$i]['id'];
				?>
					<td><a href="javascript:gotoPage(<?php echo $pgcount ?>)">
						<?php //echo ($page == $pgcount)?"<b>":"";echo $pgcount;echo ($page == $pgcount)?"</b>":"";?>
					</a></td>
				<?php
						$pgcount++;
					}
					$i++;
				  }
				?>
					</tr>
				  </table>
			</td>
		</tr>		  
<?php  
  $i=1;
  $pcount = 0;
  $category_rec = tep_db_query($sql);
if($flag=="S" && $cat_id!=""  ) {  ?>
	<script language="javascript">
		do_expand('<?php echo $cat_id; ?>','<?php echo $sel_pids; ?>');
	</script>
<?php	} ?>
<tr><td width="100%">
<table width="100%"  cellspacing="0" cellpadding="3">
	<tr class="dataTableHeadingTitleRow" style="border:1">
		<td class="dataTableHeadingTitleContent" width="25%"><?php echo TEXT_PRODUCTS;?></td>
		<td class="dataTableHeadingTitleContent" width="15%"><?php echo TEXT_SKU;?></td>
		<td class="dataTableHeadingTitleContent" width="30%"><?php echo TEXT_ATTRIBUTES;?></td>
		<td class="dataTableHeadingTitleContent" width="25%"><?php if($detailed_view){echo TEXT_CUSTOMERS;}?>&nbsp;</td>
		<td class="dataTableHeadingTitleContent" width="5%"><?php echo TEXT_QUANTITY;?></td>
		<td class="dataTableHeadingTitleContent" width="25%" colspan="2">&nbsp;</td>
	</tr>
<tr><td colspan="6" height=5></td></tr>
<?php
  //while($row = mysql_fetch_assoc($category_rec)) {
  for($i=1;$i<sizeof($category_arrays);$i++){
  if($expand_all) $category_id=$category_arrays[$i]['id'];
?>
 <tr class='dataTableHeadingTotal' style="cursor:pointer;cursor:hand;">
 	<?php if($category_arrays[$i]['id']!=$category_id)
				{
				$java_fnc="doexpand";
				$img_tag='up';
			}
		  else
		  {
		  		$java_fnc="dounexpand";
				$img_tag='down';
			}
		  ?>
		  	<TD colspan="9" align="left" width=100% onclick='javascript:<?php echo $java_fnc;?>(<?php echo $category_arrays[$i]['id'] ?>);'>
		<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr height="20">
					<td class="contentTitle" valign="top"><span style="background:#FFFFFF;padding-right:5px"><?php write_category_name($category_arrays[$i]['id']);echo $category_arrays[$i]['text'];?></span></td><td width="15" align="right"><a onClick="'javascript:<?php echo $java_fnc;?>(<?php echo $category_arrays[$i]['id'] ?>);'"><img src="images/template/panel_<?php echo $img_tag;?>.gif" id="img_' . $title . '" border="0"></a></td>
				</tr>
				<tr height="10">
					<td></td>
			</tr>
		</table>
	<?php //echo write_category_name($category_arrays[$i]['id']);echo $category_arrays[$i]['text']; ?>
	</TD>
 </tr>
<?php 
	if($category_arrays[$i]['id']==$category_id)
	{
		$prd_sql="select count(ord.orders_id) as ord_count,o.customers_email_address,ord.orders_products_status as status,pd.products_name,p.products_id,p.is_attributes,ord.products_sku  from " . TABLE_ORDERS . " o," . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd," . TABLE_PRODUCTS_TO_CATEGORIES . " cat," . TABLE_ORDERS_PRODUCTS . " ord where o.orders_id=ord.orders_id and ord.products_type='P' and ord.products_id=p.products_id and cat.products_id=p.products_id and pd.products_id=p.products_id and ord.orders_products_status<>3  and o.orders_status=2 and pd.language_id='" . $languages_id . "' and cat.categories_id=" . $category_id . $where_clause . $date_clause
				 . " Group by p.products_id";
		$product_rec = tep_db_query($prd_sql);
		$net_total=0;
		if(tep_db_num_rows(tep_db_query($prd_sql))>0){
			while($p_row = mysql_fetch_assoc($product_rec)) {
					if(!$detailed_view || (strlen($exp_product_id)>0 && strpos("," . $exp_product_id . ",","," . $p_row['products_id'] . ",")===false)){?>
					<?php 
						if($p_row['is_attributes']!='Y')
						{
							if($p_row['status']!=4) 
								$class='dataTableRow';
							 else if($p_row['status']==4 )
								$class='backorderstyle';?>
						<tr class="<?php echo $class; ?>"  >
						<td class="dataTableContent" style="cursor:pointer;cursor:hand;" onclick='javascript:doproductexpand(<?php echo $p_row['products_id'] ?>);'><?php echo $p_row['products_name']; ?></td>
						<td class="dataTableContent" colspan="2"><?php echo $p_row['products_sku'];//tep_get_sku_ids($p_row['products_id']);?></td>
						<td class="dataTableContent"></td>
						<td class="dataTableContent" colspan="1" align="right">
						<?php $cur_qty=tep_get_order_count($p_row['products_id'],"1=1" . $where_clause . $date_clause);
						$net_total+=$cur_qty;
						echo $cur_qty;?></td>
						<?php 
							if($p_row['status']!=4) {  //not backorder ?>
								<td class="dataTableContent" align="center"><?php echo tep_draw_checkbox_field('chk_products[]',$p_row['products_id']);?></td>
								<td></td>
							<?php }else if($p_row['status']==4) {?>
								<td class="dataTableContent" align="center" ><a href="javascript:mailto_backorder_customer(<?php echo $p_row['products_id'];?>);"><img src="images/icons/mail.gif" border="0"></a></td>
								<td ><?php echo "<a href=javascript:doavailable('p',". $p_row['products_id'] .")>Available</a>";?></td>
							<?php }?>
					</tr>
			<?php  } 
					else
					{
						show_detailed_view_attributes($p_row['products_id'],'N');
					}
			}
			else{
						if($p_row['is_attributes']!='Y')
						  show_detailed_view($p_row['products_id']);
						else
						  show_detailed_view_attributes($p_row['products_id'],'Y');
					}
				}
			if($net_total>0){?>
				<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td class="datatotal"></Td></Tr>
				<Tr><td colspan=3 ></td><Td class="dataTableContent" ><b><?php echo TEXT_TOTAL;?></b></td><td class="dataTableContent" align="right"><b><?php echo $net_total;?></b></td></tr>
				<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td ></Td></Tr>
	<?php	}
			}
			else{
				echo '<tr><td class="main" align="center" colspan=4>' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
			}
		}
	?>
<tr><td colspan="6" height="3"></td></tr>
<?php
  }
?>
</table>
</td></tr>
<tr><td class="bottomLine" colspan="6">&nbsp;</td></tr>
<tr><td>
<table cellpadding="2" cellspacing="0"  width="100%">
	<tr><td class="main" width=30%>
		<table width=100% style="cellspacing:0;border:0;padding:10px">
		<tr >
			<td><label><?php echo TEXT_STATUS?></label></td>
			<td><?php echo tep_image_button('button_backorders.gif',IMAGE_BACKORDER,' style="cursor:pointer;cursor:hand" onclick=javascript:dobackorder()');?></td>
			<td><?php echo tep_image_button('button_delivered.gif',IMAGE_DELIVERED,' style="cursor:pointer;cursor:hand" onclick=javascript:dodeliver()');?></td>
		</tr>
		</table>
	</td>
	<td class=main width=40%>
		<table width=100% cellspacing=0 style="cellspacing:0;border:0;padding:10px">
		<tr >
			<td><label><?php echo TEXT_PRINT?></label></td>
			<td><?php echo tep_image_button('button_backorders.gif',IMAGE_BACKORDER,' style="cursor:pointer;cursor:hand" onclick=javascript:dobackorder_pdf()');?></td>
			<td><?php echo tep_image_button('button_invoices.gif',IMAGE_INVOCIES,' style="cursor:pointer;cursor:hand" onclick=javascript:doinvoice_pdf()');?></td>
			<td><?php echo tep_image_button('button_packing_slips.gif',IMAGE_PACKINGSLIPS,' style="cursor:pointer;cursor:hand" onclick=javascript:dopackslip_pdf()');?></td>
			<td><?php echo tep_image_button('button_pickpack.gif',IMAGE_PICKPACK,' style="cursor:pointer;cursor:hand" onclick=javascript:dopickpack_pdf()');?></td>
		</tr>
		</table>
	</td>
	<td class=main width=30%>
		<table width=100% cellspacing=0 style="cellspacing:0;border:0;padding:10px">
		<tr>
			<td><label><?php echo TEXT_SELECT?></label></td>
			<td class="smallText"><?php echo  tep_draw_checkbox_field('chk_selectall_prd','','','',' onclick=javascript:selectAll(1);') . '  ' . TEXT_ALL_PRODUCTS ;?></td>
			<td class="smallText" ><?php echo tep_draw_checkbox_field('chk_selectall_cus','','','',' onclick=javascript:selectAll(2);') . '   '. TEXT_ALL_CUSTOMER;?></td>
		</tr>
		</table>
	</td>
	</tr>
</table>
</td></tr>
<?php echo tep_draw_hidden_field('exp_product_id','');
echo tep_draw_hidden_field('formaction','');
echo tep_draw_hidden_field('sflag','');
echo tep_draw_hidden_field('available_id',''); 
echo tep_draw_hidden_field('check_products','');
?>
<?php //if($formaction=="backorder" && $formaction!=""){ ?>
	<script>
	//var prd_ids=do_change();
	<?php //echo "window.open('mail_backorder.php','win_mail','location=no,height=500,width=700');"; ?>
	</script>
<?php //}
//$formaction="";
?>
<script>
	document.f.formaction.value="";
</script>
</form>
<?php
function show_detailed_view($prd_id)
{
	global $where_clause,$date_clause;
		$order_sql="select concat_ws(' ',cus.customers_firstname,cus.customers_lastname) as cus_name,cus.customers_id,o.orders_id,ord.products_id,o.customers_email_address,ord.products_quantity,ord.products_name,ord.orders_products_id,ord.orders_products_status as status,ord.invoice_printed,ord.packing_slip_printed,ord.products_sku from " .  TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " cus," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and o.customers_id=cus.customers_id and ord.products_type='P' and ord.orders_products_status<>3  and o.orders_status=2 and ord.products_id=" .$prd_id . $where_clause . $date_clause . ' order by cus.customers_firstname';
		$order_rec = tep_db_query($order_sql);
		$prev_product_name='';
		$ord_total=0;
		while($cus_row=mysql_fetch_assoc($order_rec)) {
			if ($prev_product_name!=$cus_row['products_name']){
				$prev_product_name=$cus_row['products_name']; 
				$disp_cusname=$prev_product_name;
				$td_tag="style='cursor:pointer;cursor:hand' onclick='javascript:doproductunexpand(" . $cus_row['products_id'] .");'";
				$sku=$cus_row['products_sku'];//tep_get_sku_ids($cus_row['products_id']);
			}else{
				$disp_cusname="";
				$td_tag="";
				$sku="";
			}
			
			$ord_total+=$cus_row['products_quantity'];
			if($cus_row['status']!=4) {
			//not back ordered?>
				<tr class='dataTableRow'>
					<td class="dataTableContent"  <?php echo $td_tag;?>><?php echo $disp_cusname;?></td>
					<td class="dataTableContent"><?php echo $sku;?></td>
					<td class="dataTableContent"></td>
					<td class="dataTableContent"><?php echo $cus_row['cus_name'] ;?></td>
					<!--<td class="dataTableContent" align="center"><a href="javascript:mailto_backorder_customer_view(<?php //echo $cus_row['customers_id'];?>)"><img src="images/icons/mail.gif" border="0"></a></td>-->
					<td class="dataTableContent" align="right"><?php echo $cus_row['products_quantity'];?></td>
					<td class="dataTableContent" align="center"><?php echo tep_draw_checkbox_field('chk_orders[]',$cus_row['orders_products_id']) ;
										  echo tep_draw_hidden_field('pack' . $cus_row['orders_products_id'],$cus_row['packing_slip_printed']);
										  echo tep_draw_hidden_field('invoice' . $cus_row['orders_products_id'],$cus_row['invoice_printed']);
					?></td>
					<td ></td>
				</tr>	
			<?php }else if($cus_row['status']==4) {?>
					<tr class="backorderstyle" >
					<td class="dataTableContent" <?php echo $td_tag;?>><?php echo $disp_cusname;?></td>
					<td class="dataTableContent"><?php echo $sku;?></td>
					<td class="dataTableContent"></td>
					<td class="dataTableContent"  ><?php echo $cus_row['cus_name'] ;?></td>
					<td class="dataTableContent" align="right"><?php echo $cus_row['products_quantity'] ;?></td>
					<td class="dataTableContent"  align="center"><a href="javascript:mailto_backorder_customer_view(<?php echo $cus_row['products_id'];?>);"><img src="images/icons/mail.gif" border="0"></a></td>
					<td class="dataTableContent"  ><?php echo "<a href=javascript:doavailable('o',". $cus_row['orders_products_id'] .")>Available</a>";?></td>
				</tr>
		  <?php } 
		    }	if ($ord_total>0){?>
		<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td class="datatotal"></Td></Tr>
		<Tr><td colspan=3 ></td><Td class="dataTableContent" ><b><?php echo TEXT_TOTAL;?></b></td><td class="dataTableContent" align="right"><b><?php echo $ord_total;?></b></td></tr>
		<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td ></Td></Tr>
<?php
}
 }

function show_detailed_view_attributes($prd_id,$expand)
{
	global $where_clause,$date_clause,$net_total;
		$order_sql="select concat_ws(' ',cus.customers_firstname,cus.customers_lastname) as cus_name,cus.customers_id,o.orders_id,ord.products_id,o.customers_email_address,ord.products_quantity,ord.products_name,ord.orders_products_id,ord.orders_products_status as status,ord.invoice_printed,ord.packing_slip_printed,ord.products_sku,opa.* from " .  TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " cus," . TABLE_ORDERS_PRODUCTS . " ord," . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " opa where opa.orders_id=o.orders_id and opa.orders_products_id=ord.orders_products_id  and ord.orders_id=o.orders_id and o.customers_id=cus.customers_id and ord.products_type='P' and ord.orders_products_status<>3  and o.orders_status=2 and ord.products_id=" .$prd_id . $where_clause . $date_clause . ' order by opa.orders_products_id,opa.products_options_id';
		//echo $order_sql;
		$order_rec = tep_db_query($order_sql);
		$prev_pid=0;
		$key="";
		$row_count=tep_db_num_rows($order_rec);
		if($row_count<=0){
	  		//echo '<tr><td class="main" valign="top" align="center" width=100% colspan="4">' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
		}
		while($cus_row=mysql_fetch_assoc($order_rec)) {
			$p_id=$cus_row["orders_products_id"];
			if($p_id!=$prev_pid && $key!="" )
			{
				$key=substr($key,0,-1);
				$cus_array[$key][]=array("products_name"=>$prd_name,
									 "products_quantity"=>$prd_qty,
									 "status"=>$prd_status,
									 "cus_name"=>$cus_name,
									 "products_id"=>$prd_id,
									 "orders_products_id"=>$prev_pid,
									 "packing_slip_printed"=>$printed,
									 "invoice_printed"=>$invoice,
									 "customers_email_address"=>$email,
 									 "customers_id"=>$cus_id,
									 "att_name"=>$att_name,
									 "sku"=>$cus_row['products_sku']);//tep_get_sku_ids($prd_id,$key)
				$att_name="";
				$key="";
				$prev_pid=$cus_row['orders_products_id'];
				$key=$cus_row['products_options_id'] . '{' . $cus_row['products_options_values_id'] . '}-';
				$att_name=$cus_row['products_options'] . " : " . $cus_row['products_options_values'] . '<br>';
			} else{
				$prev_pid=$cus_row['orders_products_id'];
				$cus_name=$cus_row['cus_name'];
				$prd_name=$cus_row['products_name'];
				$prd_qty=$cus_row['products_quantity'];
				$prd_status=$cus_row['status'];
				$prd_id=$cus_row['products_id'];
				$printed=$cus_row['packing_slip_printed'];
				$invoice=$cus_row['invoice_printed'];
				$email=$cus_row['customers_email_address'];
				$cus_id=$cus_row['customers_id'];
				$key.=$cus_row['products_options_id'] . '{' . $cus_row['products_options_values_id'] . '}-';
				$att_name.=$cus_row['products_options'] . " : " . $cus_row['products_options_values'] . '<br>';
				$sku=$cus_row['products_sku'];//tep_get_sku_ids($prd_id)
			}
		}
		if($key!="")
		{
			$key=substr($key,0,-1);
			$sku=$cus_row['products_sku'];//tep_get_sku_ids($prd_id,$key)
			$cus_array[$key][]=array("products_name"=>$prd_name,
									 "products_quantity"=>$prd_qty,
									 "status"=>$prd_status,
									 "cus_name"=>$cus_name,
									 "products_id"=>$prd_id,
									 "orders_products_id"=>$prev_pid,
									 "packing_slip_printed"=>$printed,
									 "invoice_printed"=>$invoice,
									 "customers_email_address"=>$email,
 									 "customers_id"=>$cus_id,
									 "att_name"=>$att_name,
									 "sku"=>$sku);
			$att_name="";
			$key="";
		}
		$prev_product_name='';
		$ord_total=0;
		if(!isset($cus_array)) return;
		if($expand=="Y")
		{
			foreach($cus_array as $row1)
			{
				$prev_att_name="";
				foreach($row1 as $col1)
				{
					if ($prev_product_name!=$col1['products_name']){
						$prev_product_name=$col1['products_name']; 
						$disp_cusname=$prev_product_name;
						$td_tag="style='cursor:pointer;cursor:hand' onclick='javascript:doproductunexpand(" . $col1['products_id'] .");'";
					}else{
						$disp_cusname="";
						$td_tag="";
					}
					if ($prev_att_name!=$col1['att_name']){
						$prev_att_name=$col1['att_name']; 
						$disp_attname=$prev_att_name;
						$sku=$col1['sku'];	
					}else{
						$disp_attname="";
						$sku="";	
					}
					$ord_total+=$col1['products_quantity'];
					if($col1['status']!=4) {
						//not back ordered?>
				  		<tr class='dataTableRow'>
							<td class="dataTableContent" valign=top <?php echo $td_tag;?>><?php echo $disp_cusname;?></td>
							<td class="dataTableContent" valign=top><?php echo $sku;?></td>
							<td  class="dataTableContent" valign=top ><?php echo $disp_attname ;?></td>
							<td  class="dataTableContent" valign=top ><?php echo $col1['cus_name'] ;?></td>
							<td   class="dataTableContent" valign=top align="right"><?php echo $col1['products_quantity'] ;?></td>
							<td   class="dataTableContent" valign=top align="center"><?php echo tep_draw_checkbox_field('chk_orders[]',$col1['orders_products_id']) ;
												  echo tep_draw_hidden_field('pack' . $col1['orders_products_id'],$col1['packing_slip_printed']);
												  echo tep_draw_hidden_field('invoice' . $col1['orders_products_id'],$col1['invoice_printed']);
								  ?></td>
							<td ></td>
						</tr>
								
					<?php }else if($col1['status']==4) {?>
							<tr class="backorderstyle"  >
							<td class="dataTableContent" valign=top  <?php echo $td_tag;?>><?php echo $disp_cusname;?></td>
							<td class="dataTableContent" valign=top><?php echo $col1['sku'];?></td>
							<td class="dataTableContent" valign=top  ><?php echo $disp_attname ;?></td>
							<td class="dataTableContent"  valign=top ><?php echo $col1['cus_name'] ;?></td>
							<td class="dataTableContent" valign=top align="right"><?php echo $col1['products_quantity'] ;?></td>
							<td class="dataTableContent" valign=top  align="center"><a href="javascript:mailto_backorder_customer_view(<?php echo $col1['customers_id'];?>)"><img src="images/icons/mail.gif" border="0"></a></td>
							<td class="dataTableContent" valign=top   ><?php echo "<a href=javascript:doavailable('o',". $col1['orders_products_id'] .")>Available</a>";?></td>
						</tr>
				  <?php } 
			  }	
		}
	?>			
			<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td class="datatotal"></Td></Tr>
			<Tr><td colspan=3 ></td><Td class="dataTableContent" ><b><?php echo TEXT_TOTAL;?></b></td><td class="dataTableContent" align="right"><b><?php echo $ord_total;?></b></td></tr>
			<Tr><td colspan=3 ></td><Td colspan=2 ><hr></Td><Td ></Td></Tr>
<?php }else { //not detailed view 
			$icnt=0;
			foreach($cus_array as $row1)
			{
				$prev_att_name="";
				$ord_sub_total="";
				$backorder=false;
				$icnt++;
				foreach($row1 as $col1)
				{
					if ($prev_product_name!=$col1['products_name']){
						$prev_product_name=$col1['products_name']; 
						$disp_cusname=$prev_product_name;
						$prd_id=$col1['products_id']; 
						$td_tag="style='cursor:pointer;cursor:hand' onclick='javascript:doproductexpand(" . $col1['products_id'] .");'";
						$sku=$col1['sku'];
					}
					if ($prev_att_name!=$col1['att_name']){
						$prev_att_name=$col1['att_name']; 
						$disp_attname=$prev_att_name;
						$sku=$col1['sku'];
					}
					$ord_sub_total+=$col1['products_quantity'];
					if($col1['status']==4) {
						$backorder=true;
					}
				}
				if($icnt>1)
				{
					$disp_cusname="";
					$td_tag="";
				}			 
				$ord_total+=$ord_sub_total;
				if($backorder==false)
					$class="dataTableRow";
				else
					$class="backorderstyle";
				?>
				<tr class="<?php echo $class; ?>"  >
					<td class="dataTableContent" valign=top <?php echo $td_tag;?>><?php echo $disp_cusname; ?></td>
					<td class="dataTableContent"><?php echo $sku; ?></td>
					<td colspan="1" class="dataTableContent"><?php echo $disp_attname; ?></td>
					<td class="dataTableContent"></td>
					<td class="dataTableContent" colspan="1" align="right"><?php echo $ord_sub_total;?></td>
					<?php 
						if($backorder==false && $icnt<=1) {  //not backorder ?>
							<td class="dataTableContent" align="center"><?php echo tep_draw_checkbox_field('chk_products[]',$prd_id);?></td>
							<td></td>
						<?php }elseif($backorder==true && $icnt<=1) {?>
							<td class="dataTableContent" align="center"><a href="javascript:mailto_backorder_customer(<?php echo $prd_id;?>);"><img src="images/icons/mail.gif" border="0"></a></td>
							<td ><?php echo "<a href=javascript:doavailable('p',". $prd_id .")>Available</a>";?></td>
						<?php }
						else
							echo "<td colspan=2></td>";?>
				</tr>
				
	<?php	}
	$net_total+=$ord_total;
	?>			
			<!--<Tr><td colspan=2 ></td><Td colspan=2 ><hr></Td><Td class="datatotal"></Td></Tr>
			<Tr><td colspan=2 ></td><Td class="dataTableContent" ><b><?php //echo TEXT_TOTAL;?></b></td><td class="dataTableContent" align="right"><b><?php// echo $ord_total;?></b></td></tr>
			<Tr><td colspan=2 ></td><Td colspan=2 ><hr></Td><Td ></Td></Tr>-->

<?php }
 } ?>

<script language="JavaScript" type="text/javascript">
function gotoPage(pageNr) { 
	lastIds = new Array(); 
<?php
	foreach($pages_last_ids as $pg_last_id) {
?>	
	lastIds[lastIds.length] = <?php echo $pg_last_id ?>;
<?php
	}
?>
	document.f.page.value = pageNr;
	document.f.last_id.value = lastIds[pageNr-1];
	document.f.submit();
}

</script>  
	  </td>
	 </tr>
    </table>
   </td>
  </tr>
 </table>
 <?php /*if($formaction=="delivered" )
					{
						echo "<script>" ;
						if($set_all_delivered)
							echo "document.f.formaction.value='';";
						else
							echo "document.f.formaction.value='deliver_error';";
						echo "document.f.submit();";
						echo "</script>";
					}*/?>
	<!-- footer //-->
	<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
	<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
<?php
// function to create pdf details
	function generate_backorderpdf(&$prd_array){
		global $display_header,$login_id;
		// set initial parameters
		$table=new pdfTable("A4","l");
		$table->left_margin=20;
		$table->top_margin=20;
		$table->right_margin=20;
		$table->bottom_margin=20;
		$table->pdfInit();
		// Add Styles for table
		$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("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");

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

		// define column width
		$widths[0]=$table->width*15/100;
		
		$widths[1]=$table->width*45/100;
		$widths[2]=$table->width*10/100;
		$widths[3]=$table->width*10/100;
		$widths[4]=$table->width*15/100;
		$widths[5]=$table->width-($widths[2]+$widths[1]+$widths[0]+$widths[3]+$widths[4]);
		if(sizeof($prd_array)>0){
			$cat=&$prd_array[0];
			//output header details
			$prev_product_id=0;
			$total=0;
			$prev_cat="";
			$cols[]=array("text"=>TEXT_PRODUCTS,"width"=>$widths[0],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$cols[]=array("text"=>TEXT_SKU,"width"=>$widths[3],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$cols[]=array("text"=>TEXT_ATTRIBUTES,"width"=>$widths[1],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$cols[]=array("text"=>TEXT_ORDERID,"width"=>$widths[2],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$cols[]=array("text"=>TEXT_CUSTOMERS,"width"=>$widths[4],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$cols[]=array("text"=>TEXT_QUANTITY,"width"=>$widths[5],"align"=>"L","style"=>"subrowhead","valign"=>"M");
			$table->tableheaders["text"]=$cols;
			unset($cols);
			// output content
			for ($icnt=0;$icnt<sizeof($prd_array);$icnt++) {
				$row=&$prd_array[$icnt];
				if($prev_cat!=$row['cat_name'])
				{
					if($total>0)
					{
						$cols=array();
						$cols[]=array("text"=>"","width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3],"align"=>"L","style"=>"subrowhead","valign"=>"M");
						$cols[]=array("text"=>TEXT_TOTAL,"width"=>$widths[4],"align"=>"L","style"=>"subrowhead","valign"=>"M");
						$cols[]=array("text"=>$total,"width"=>$widths[5],"align"=>"L","style"=>"subrowhead","valign"=>"M");
						$table->OutputRow($cols,15);
						unset($cols);
						$total=0;
					}
					$cols=array();
					$cols[]=array("text"=>$row['cat_name'],"width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3]+$widths[4]+$widths[5],"align"=>"L","style"=>"headrow","valign"=>"M");
					$table->OutputRow($cols,15);
					unset($cols);
					$prev_cat=$row['cat_name'];
				}
				$product_id=$row["product_id"];
				$cols=array();
				$sku="";
				if ($prev_product_id!=$product_id) {
					
					$cols[]=array("text"=>$row["products_name"],"width"=>$widths[0],"align"=>"L","style"=>"row","valign"=>"M");
					$prev_product_id=$product_id;
					//$sku=$row['model'];
					$sku=$row['sku'];
				}
				else
				$cols[]=array("text"=>"","width"=>$widths[0],"align"=>"L","style"=>"row","valign"=>"M");
				$cols[]=array("text"=>$sku,"width"=>$widths[3],"align"=>"L","style"=>"row","valign"=>"M");
				$cols[]=array("text"=>$row['att_name'],"width"=>$widths[1],"align"=>"L","style"=>"row","valign"=>"M");
				$cols[]=array("text"=>$row['orderid'],"width"=>$widths[2],"align"=>"L","style"=>"row","valign"=>"M");
				$cols[]=array("text"=>$row['cus_name'],"width"=>$widths[4],"align"=>"L","style"=>"row","valign"=>"M");
				$cols[]=array("text"=>$row['quantity'],"width"=>$widths[5],"align"=>"R","style"=>"row","valign"=>"M");
				$table->OutputRow($cols,15);
				unset($cols);
				$total+=$row['quantity'];
			}
			if($total>0)
			{
				$cols=array();
				$cols[]=array("text"=>"","width"=>$widths[0]+$widths[1]+$widths[2]+$widths[3],"align"=>"L","style"=>"subrowhead","valign"=>"M");
				$cols[]=array("text"=>TEXT_TOTAL,"width"=>$widths[4],"align"=>"L","style"=>"subrowhead","valign"=>"M");
				$cols[]=array("text"=>$total,"width"=>$widths[5],"align"=>"R","style"=>"subrowhead","valign"=>"M");
				$table->OutputRow($cols,15);
				unset($cols);
			}
		} else {
			$cols[]=array("text"=>TEXT_NO_RECORDS_FOUND,"width"=>"100%","align"=>"C","style"=>"subrow","valign"=>"M");
			$table->OutputRow($cols,15);
			unset($cols);
		}
		// create pdf page
		$table->Render("reports_backorder_".$login_id."_".time().".pdf");
	}
	function write_category_name($category_id){
		$sql = "select parent_id,c.categories_id,categories_name from " . TABLE_CATEGORIES . " c," . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id=cd.categories_id and c.categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_category_name($result['parent_id']);
		}else{
			return "";
		}
	}
	
?>
