<?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');  
	
	define(BOX_WIDTH1,'125');
	
	$type=(isset($HTTP_POST_VARS["cbo_stock_type"])?$HTTP_POST_VARS["cbo_stock_type"]:-1);
	$category=(isset($HTTP_POST_VARS["cbo_category"])?(int)$HTTP_POST_VARS["cbo_category"]:0);
	$summary_show=(isset($HTTP_POST_VARS["chk_summary"])?true:false);
	$post_action=(isset($HTTP_POST_VARS["post_action"])?$HTTP_POST_VARS["post_action"]:'screen');
	$pdf_output=(isset($HTTP_POST_VARS["chk_pdf_output"])?true:false);
	$excel_output=(isset($HTTP_POST_VARS["chk_excel_output"])?true:false);
	$page=(isset($HTTP_POST_VARS["page"])?$HTTP_POST_VARS["page"]:1);
   $parent_id=(isset($HTTP_POST_VARS["parent_id"])?$HTTP_POST_VARS["parent_id"]:0);
   $expand_all=(isset($HTTP_POST_VARS["chk_expand_all"])?$HTTP_POST_VARS["chk_expand_all"]:0);
   if($expand_all)$category="-1";
   $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);
		if ($post_action==""){
			$pdf_output=true;
			$post_action="screen";
		}
				
		//echo $HTTP_SESSION_VARS["sess_report_filename"];
	
	if ($post_action!="screen"){
		$report_filename="inventory_" . $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);
		
		//tep_session_show_file($report_filename);
	}
		
	$found_results=false;
		$where="";
			if ($category!=0){
				$wherecategory.=" and pc.categories_id='" . $category . "'";
				$parent_id=$category;
			}
			if ($type==3){
				$where.="and date_format(p.products_date_added,'%Y-%m-%d') >= date_format(date_add('".getServerDate()."',interval -8-WEEKDAY('".getServerDate()."') day),'%Y-%m-%d')  and date_format(p.products_date_added,'%Y-%m-%d')<= date_format(date_add('".getServerDate()."',interval -7 day),'%Y-%m-%d')  ";
				//$where.=" and date_format(p.products_date_added,'%Y-%m-%d')>=date_sub(curdate(),interval date_format(p.products_date_added,'%w') day) ";
			}
			if ($type==4){
				$cur_month=date("m");
				$cur_year=date("Y");
				$first_date=mktime(0,0,0,$cur_month,1,$cur_year);
				$where.=" and date_format(p.products_date_added,'%Y-%m-%d')<='" . date('Y-m-d',$first_date) ."'";
			}
			if ($type==2){
				$where.=" and (p.is_attributes='Y' or p.products_quantity<=0) ";
				$where_attr=" and p.products_quantity<=0) ";
			}
			if($type==1){
				$where.=" and (p.is_attributes='Y' or (p.products_quantity<=" . STOCK_REORDER_LEVEL . " and p.products_quantity>0)) ";
				$where_attr=" and p.products_quantity<=" . STOCK_REORDER_LEVEL . " and p.products_quantity>0) ";
			}
			//get categories
				$parent_ids="";
				$parent_ids="and c.categories_id='".(int)$parent_id."'";
		
				$category_array=array();
				$category_array[]=array("id"=>-1,"text"=>TEXT_ALL_CATEGORIES);
				$category_query=tep_db_query("SELECT cd.categories_name,c.categories_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd " . 
							"where c.categories_id=cd.categories_id and cd.language_id='" . $languages_id . "' order by cd.categories_name");
				if($expand_all)		$parent_ids="";
							
				while($category_result=tep_db_fetch_array($category_query)){
					if($expand_all)
						$parent_ids.=$category_result["categories_id"].",";
					
					$category_array[]=array("id"=>$category_result["categories_id"],"text"=>$category_result["categories_name"]);
				}
			if($expand_all) $parent_ids="and c.categories_id in(".substr($parent_ids,0,-1).")";
			//get categories 
		// create the query for inventory report		
			$products_sql="SELECT distinct c.parent_id,p.products_id,pd.products_name,p.products_quantity,cd.categories_id,cd.categories_name,p.is_attributes from " . TABLE_PRODUCTS . " p, " .TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd, " .
											TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pc where p.products_id=pc.products_id and cd.categories_id=pc.categories_id
											and p.products_id=pd.products_id and pd.language_id='" . $languages_id . "' and cd.language_id='" . $languages_id . "' " . $where . $parent_ids ."  and c.categories_id=cd.categories_id  order by cd.categories_name,pd.products_name"; 
			
			$products_query=tep_db_query($products_sql);
		
			if (tep_db_num_rows($products_query)>0)  $found_results=true;
			$prd_array=array();
			
			
			 if ($found_results){
				// generate the output array with product details and category headings
					while($products_result=tep_db_fetch_array($products_query)){
						$add_result=true;
						$count_query=tep_db_query("SELECT count(op.products_id) as total from " . TABLE_ORDERS_PRODUCTS . " op where op.products_id='" . $products_result["products_id"] . "' and op.products_type='P'");
						$count_result=tep_db_fetch_array($count_query);
						$total_count=(int)$count_result["total"];
						$stock=$products_result["products_quantity"];
										
						//Attribute  checking
							$products_attributes_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" .  $products_result["products_id"] . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "'");
							$products_attributes = tep_db_fetch_array($products_attributes_query);
							$add_product=false;
							if($products_attributes['total']>0) {
								 $attribute_query=tep_db_query("Select * from " . TABLE_PRODUCTS_STOCK . " where products_id='" . $products_result["products_id"] . "' ");
								while($attribute_result=tep_db_fetch_array($attribute_query))
									{
										$attribute_detail=$attribute_result['attributes_id'];
										$attr_array=split('-',$attribute_detail);
										$size_attr=sizeof($attr_array);
										$attr_option_names="";
										if (!($type==1  or $type==2) or $attribute_result["products_quantity"]<=$check_quan){
										for($i=0;$i<$size_attr;$i++)
											{
											
												$value_array=split('{',$attr_array[$i]);
												//get options name
												$attr_query=tep_db_query("Select products_options_name from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id='" . $value_array[0] . "' ");
												$attr_result=tep_db_fetch_array($attr_query);
												//$attr_option_names.=$attr_result['products_options_name'] . " : ";
												
												//get option values name	
												$attr_value=substr($value_array[1],0,-1);
												$attr_value_query=tep_db_query("Select products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES .  " where products_options_values_id='" .  $attr_value . "' ");
												$attr_value_result=tep_db_fetch_array($attr_value_query);
												$attr_option_names.=$attr_value_result['products_options_values_name'] . ',';
												$add_product=true;
											}
											$attributes_name=substr($attr_option_names,0,-1);
										
											$attribute_array[]=array('products_id'=>$attribute_result['products_id'],
																	'attributes_name'=>$attributes_name,
																	'attributes_quantity'=>$attribute_result['products_quantity']);
										
										}						
														// out of stock
									//	if ($type==2 && $attribute_result['products_quantity']<=0) {
										 // print_r ($attribute_array);
												
										//	}
								 }
							}
								if ($products_result["is_attributes"]!='Y' or $add_product){
								  $prd_array[]=array("name"=>$products_result["products_name"],
													"id"=>$products_result["products_id"],
													"quan"=>$products_result["products_quantity"],
													"cat_id"=>$products_result["categories_id"],
													"cat_name"=>$products_result["categories_name"],
													"stock"=>$stock,
													"parent_id"=>$products_result["parent_id"]
												);
								}
										
						} 
					}
					
		//stock array
		$stock_array=array(	array('id'=>-1,'text'=>TEXT_ALL_PRODUCTS),
							array('id'=>1,'text'=>TEXT_LOW_INVENTORY),
							array('id'=>2,'text'=>TEXT_OUT_STOCK),
							array('id'=>3,'text'=>TEXT_RECENT_WEEK),
							array('id'=>4,'text'=>TEXT_RECENT_MONTH)
						);
		// output array
		$output_array=array( 	array('id'=>1,'text'=>TEXT_SCREEN),
								array('id'=>2,'text'=>TEXT_PDF),
								array('id'=>3,'text'=>TEXT_EXCEL)
							);
	
		// pdf output
				
		if ($post_action=="pdf"){
			out_pdf($prd_array);
			tep_redirect(DIR_WS_CATALOG . "images/" . $report_filename . ".pdf");
		}
		// excel output
		if ($post_action=="excel"){
			out_excel($prd_array);
			tep_redirect(DIR_WS_CATALOG . "images/" . $report_filename . ".csv");
		}
		tep_delete_temp_files("inventory_" . $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>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- 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_INVENTORY;?></td>!-->
				</tr>
				<tr>
					<td class="pageHeading"></td>
				</tr>
				<!-- --->
				<script language="JavaScript">
						function doReport(mode) {
							if (mode==3){
								document.f.post_action.value="excel"
								document.f.target="_blank";
							} else if (mode==2){
								document.f.post_action.value="pdf";
								document.f.target="_blank";
							} else {
								document.f.post_action.value="screen";
								document.f.target="_self";
							}
							document.f.submit();
						}
					
						function f_Print() {
							document.f.layout.value="print";
							document.f.target="_blank";
							document.f.submit();
						
						}
					function do_expand(row_id,type){
						if(type=='expand' && row_id>0){
						  var my_id="row"+row_id;
						  document.getElementById(my_id).style.display="";
						}else if(type!='expand'){
						  document.f.parent_id.value=row_id;
						  document.f.post_action.value="screen";
						  document.f.target="_self";
						  document.f.submit();
						}
					}
				</script>
					<?php 
						echo tep_draw_form("f",FILENAME_INVENTORY);
						echo '<input type="hidden" name="post_action" value="">';
					?>
				<input type="hidden" name="parent_id" value="<?php echo $parent_id;?>">
				<tr>
					<td>
						<table cellspacing="3" cellpadding="2" class="searchArea" width="100%" border="0">
							<tr >
								<td>
									<table border="0" cellpadding="0" cellspacing="0" width="100%">
										<tr class="main">
											<td nowrap><?php echo "<label>" . TEXT_CATEGORY . '</label>&nbsp;' . tep_draw_pull_down_menu("cbo_category",tep_get_category_tree('','','','','',TEXT_ALL_CATEGORIES ),$category);?></td>
											<td nowrap>
											<?php 	echo "<label>" . TEXT_STOCK_TYPE . '</label>&nbsp;' . tep_draw_pull_down_menu("cbo_stock_type",$stock_array,$type);
													
											?>
											</td>
											<td align="left" class="main">
												<?php
												echo '&nbsp;&nbsp;' . tep_draw_checkbox_field("chk_summary",1,$summary_show) . "&nbsp;<label>" . TEXT_SUMMARY_ONLY . "</label>";?>
											<td align="left" class="main">
												<?php echo '&nbsp;&nbsp;' . tep_draw_checkbox_field("chk_expand_all",1,$expand_all) . "&nbsp;<label>" . TEXT_EXPAND_ALL . "</label>";?> 
											</td>	 
												<td align="right" class="main">
												<?php
													echo '<a href="javascript:doReport(1);">' . tep_image_button('button_report_search.gif', IMAGE_SEARCH_PRODUCTS) . '</a>&nbsp;&nbsp;';
												?>
											</td>
										</tr>
										<tr height="30">
										<td  align="right" valign="bottom" colspan="5" ><?php echo '<a href="javascript:doReport(2);">' . tep_image_button('button_export_pdf.gif', IMG_EXPORT_PDF) . '</a>&nbsp;';?></td>
										</tr>
										
										<tr>
										<td align="right" valign="middle" colspan="5" ><?php echo '<a href="javascript:doReport(3);">' . tep_image_button('button_export_excel.gif', IMG_EXPORT_EXCEL) . '</a>&nbsp;';?> </td>
										</tr>
										<tr><td colspan="5"><?php echo tep_draw_separator("pixel_trans.gif","1","1");?></td></tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				</form>
				<tr ><td class="cell_bg_report_header">&nbsp;</td></tr>
				<?php 
				$swhere="";
				if ($category>0){
					$swhere.=" and c.categories_id='" . $category . "'";
				}
				$category_query=tep_db_query("select cd.categories_name,c.categories_id,c.parent_id from ".TABLE_CATEGORIES ." c," . TABLE_CATEGORIES_DESCRIPTION ." cd  where cd.language_id='".(int)$languages_id."' and c.categories_id=cd.categories_id ".$swhere." order by parent_id,categories_name");
				 
				$categories=array();
				$counts=array();
				while($category_result=tep_db_fetch_array($category_query)){
					$cat_id=$category_result["categories_id"];
					$parent_cat_id=$category_result["parent_id"];
					
					
					if (!isset($counts[$parent_cat_id])){
						$counts[$parent_cat_id]=1;
						$pos=0;
						$path=1;
						$level=0;
					} else {
						$counts[$parent_cat_id]+=1;
						$pos=$counts[$parent_cat_id];
						$path=$categories[$parent_cat_id]["path"] . $pos;
						$level=$categories[$parent_cat_id]["level"]+1;
					}
					$counts[$cat_id]=0;
					$categories[$cat_id]["path"]=$path;
					$categories[$cat_id]["name"]=$category_result["categories_name"];
					$categories[$cat_id]["level"]=$level;
				}
				uksort($categories,"user_cmp");
				if (count($categories)>0){
					reset($categories);
					$switch=true;
					$prev_category_id = 0;
					while(list($category_id,)=each($categories)){ 
					?>
						<!--<tr style="cursor:pointer;cursor:hand" class="dataTableHeadingTotal" onClick="javascript:do_expand(<?php //echo $category_id;?>)">
							<td class="dataTableHeadingContent"><?php //echo tep_draw_separator('pixel_trans.gif',10*$categories[$category_id]["level"],5) . $categories[$category_id]['name'];?></td>
						</tr>-->
						<?php if($parent_id!=$category_id && !$expand_all) 
								tep_content_title_top(tep_draw_separator('pixel_trans.gif',10*$categories[$category_id]["level"],5) . $categories[$category_id]['name'],false,false,true,'do_expand(' .  $category_id .');');
							  else
								tep_content_title_top(tep_draw_separator('pixel_trans.gif',10*$categories[$category_id]["level"],5) . $categories[$category_id]['name']);?>
						<tr>
							 <td align="left" width="100%" colspan="0">
							   <table border="0"  cellpadding="0" cellspacing="0" width="100%" id="row<?php echo $category_id; ?>">
							   <tr><td colspan="3"></td></tr>
								<?php 
									$sql = "select count(*) as amount_total from " . TABLE_CATEGORIES . " c," . TABLE_PRODUCTS_TO_CATEGORIES . " ptc," . TABLE_PRODUCTS . " p where p.products_id=ptc.products_id and ptc.categories_id=c.categories_id and c.categories_id='" . $category_id . "' and p.products_quantity<1";
									$query = tep_db_query($sql);
									$result = tep_db_fetch_array($query);
									if ($found_results && sizeof($prd_array)>0) {
								?>
								  <tr>
										<td width="100%" colspan="0" align="right">
											<table border="0" cellpadding="0" cellspacing="0" width="100%">
											<?php
												$total=0; 
												for ($icnt=0;$icnt<sizeof($prd_array);$icnt++){
													$row=&$prd_array[$icnt];
													$p_id=$row['id'];
													
													if(!$summary_show && $row['cat_id']==$category_id) {
											?>
											<?php if($prev_category_id!=$category_id) {?>
											  <tr class='dataTableHeadingTitleRow'>
												  <td width="25%" class='dataTableHeadingTitleContent' ><?php echo TEXT_ID;?></td>
												  <TD width="25%" class='dataTableHeadingTitleContent' align="left" ><?php echo TEXT_PRODUCT_NAME;?></TD>
												  <TD width="17%" class='dataTableHeadingTitleContent'  align="center" >&nbsp;</TD>
												  <TD width="17%" class='dataTableHeadingTitleContent'  align="center" >&nbsp;</TD>
												   <TD class='dataTableHeadingTitleContent'  align="right"><?php echo TEXT_STOCK;?> </TD>
											</tr>
											<?php 
													$prev_category_id=$category_id; 
												}
											?>
											<tr>
												<td colspan="5"><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
											</tr>
															<TR>
																  <Td colspan="5" class='dataTableRow'>
																	<table border="0" cellspacing="0" width="100%" cellpadding="0">
																		<tr>
																				<TD class='dataTableContent' align="left" width="22%"><?php echo $icnt+1; ?></td>
																				<TD class='dataTableContent' width="40%" align="left" nowrap><?php echo $row['name']; ?></TD>
																				<td  align="right" class='dataTableContent'> <?php echo $row['stock']; ?></td>
																	  </tr>
																	</table>
																 </td> 	
														   </TR>
															  <tr>
																<td class="dataTableContent" colspan="3">
																<table border="0" cellpadding="0" cellspacing="0" width="94%">
																	 <?PHP $size_attribute=sizeof($attribute_array);
																		 if($size_attribute>0) {
																			 for($j=0;$j<$size_attribute;$j++){
																				 if($attribute_array[$j]['products_id']==$p_id){?>
																				 <tr><td width="113"></td>
																				 <td width="110" class="dataTableContent"  align="right"nowrap="nowrap"><?PHP echo $attribute_array[$j]['attributes_name']; ?> </td>
																				 <td width="57" align="right"  nowrap="nowrap"class="dataTableContent"><?PHP echo $attribute_array[$j]['attributes_quantity']; ?> </td>
																				 </tr>
																			  <?php 	}
																					} 
																					if ($type==2 && $attribute_result['products_quantity']<=0) {
																			 	   echo  '<tr><td>'.$attribute_result['products_quantity'].'</td></tr>';
																				}
																			}
																			$total+=$row["stock"];
														  				?> 
																	 </table>
																 </td>
															 </tr>
												<?php  }else if($summary_show && $row['cat_id']==$category_id){
														 		$total+=$row["stock"];
														 }
												   $i++;
													}
													if($switch && $total==0 && $result['amount_total']==0 && ($parent_id==$category_id || $expand_all)){
														echo '<td class="main" align="center">' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
													}else{
														$switch=true;
													}
													?>
													<?php	if ($total>0) { ?>
													<tr>
														<td><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
													</tr>
													<tr>
														<td class="dataTableContent"></td>
														<td class="dataTableContent"></td>
														<td class="dataTableContent" colspan="2" align="right"><b><?php echo TEXT_TOTAL; ?></b></td>
														<td class='dataTableContent' align="right">
														<table width="246" border="0" cellpadding="0" cellspacing="0">
																		<tr>
																			<td class='dataTableContent'  align="right">
																				<?php echo '<b>'.$total.'</b>'; ?>	</td>
																		</tr>
																	  </table>
														
														</td>
														</tr>
														<?php } ?>
										 
										<tr>
											<td><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
										</tr>
										</table>
									</td>
							</tr>
							<?php 
							}
								else if($switch && $parent_id==$category_id){ 
							?>
							  <tr id="row<?php echo $category_id; ?>">
						
							<?php
								echo '<td class="main" align="center">' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
							}
							 ?>
							</table>
							</td>
						</tr>
					 <?php 
					 tep_content_title_bottom();
					 
					   } 
					 	}
					 ?>
				 <script language="javascript">do_expand(<?php echo $parent_id;?>,'expand');</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 to output excel content
		function out_excel(&$prd_array){
			global $summary_show,$attribute_array,$login_id,$prd_array,$report_filename_excel;
			
			$fp=fopen(DIR_FS_CATALOG . "images/" . $GLOBALS["report_filename"] . ".csv",'w');
			$output_string="";
			if(sizeof($prd_array)>0)
				$output_string.=sprintf("%s,%s,%s,%s\n",TEXT_ID,TEXT_PRODUCT_NAME,TEXT_ATTRIBUTE_QUANTITY,TEXT_STOCK);
			else
				$output_string.=TEXT_NO_RECORDS_FOUND;
			for ($icnt=0;$icnt<sizeof($prd_array);$icnt++){
				$row=&$prd_array[$icnt];
				$p_id=$row['id'];
				if ($prev_cat_id!=$row["cat_id"]){
					if ($total>0) {
						$output_string.=sprintf(",%s,,%s\n\n",TEXT_TOTAL,$total);
						$total=0;
					}
					if($attrib_total>0){
						$output_string.=sprintf(",%s,%s\n\n",TEXT_ATTRIBUTE_QUANTITY,$attrib_total);
						$attrib_total=0;
					}
					$prev_cat_id=$row["cat_id"];
					$output_string.=sprintf("%s\n",$row["cat_name"]);
				}
				if(!$summary_show) {
					$output_string.=sprintf("%s,%s,,%s\n",$icnt+1,$row['name'],$row['stock']);
					if(sizeof($attribute_array)>0) {
					for($j=0;$j<sizeof($attribute_array);$j++){  
						if($attribute_array[$j]['products_id']==$p_id){
							$output_string.=sprintf("%s,%s,%s\n",'',$attribute_array[$j]['attributes_name'],$attribute_array[$j]['attributes_quantity']);
							}
						}
					}
					
				}
			   $i++;
			   $total+=$row["stock"];
			}
			
			if ($total>0) {
				$output_string.=sprintf(",%s,,%s\n\n",TEXT_TOTAL,$total);
			}
			if($attrib_total>0){ 
				$output_string.=sprintf(",%s,%s\n\n",TEXT_ATTRIBUTE_QUANTITY,$attrib_total);
				$attrib_total=0;
			}
			fwrite($fp,$output_string,strlen($output_string));
			fclose($fp);
		}
	// function to output pdf content
		function out_pdf(&$prd_array){ 
			global $attribute_array,$prd_array,$summary_show,$page_width,$page_height,$col_width,$font_name,$font_size,$pdf,$row_height,$header_color,$row_color;
			//print_r ($attribute_array);
			define('FPDF_FONTPATH','font/');
			require('includes/fpdf.php');
			  
			define('PDF_LEFT_MARGIN',20);
			define('PDF_TOP_MARGIN',20);
			define('PDF_ORIENTATION','P');


			
			
			$row_height=14;
					
			$col_width[0]=60;
			$col_width[1]=80;
			$col_width[2]=200;
			$col_width[3]=50;
			$page_height=841.89-(PDF_LEFT_MARGIN*2);
			$page_width=595.28-(PDF_TOP_MARGIN*2);
			$col_width[1]=$page_width-($col_width[0]+$col_width[2]+$col_width[3]);
			$prd_count = sizeof($prd_array);
			
			$pdf=new FPDF(PDF_ORIENTATION,"pt",($page_size==2?"legal":"A4"));
			$pdf->AliasNbPages();
			$pdf->SetAutoPageBreak(false);
	
	
			$cur_y=$page_height;
			$cur_x=PDF_LEFT_MARGIN;
			check_page($cur_x,$cur_y,$prd_count);
			$attrib_total=0;
			for ($icnt=0;$icnt<sizeof($prd_array);$icnt++){
			   $row=&$prd_array[$icnt];
				$p_id=$row['id'];
				$cur_x=PDF_LEFT_MARGIN;
				if ($prev_cat_id!=$row["cat_id"]){
					if ($total>0) {
						$pdf->SetFont($font_name,'B',$font_size);
						$cur_x+=$col_width[0];
						$pdf->SetXY($cur_x,$cur_y);
						$pdf->Cell($col_width[0],$row_height , TEXT_ATTRIBUTE_QUANTITY , 0 , 0 ,"L");
						$cur_x+=$col_width[2];
						$pdf->SetXY($cur_x,$cur_y);
						$pdf->Cell($col_width[2],$row_height , $attrib_total , 0 , 0 ,"L");
						$cur_x+=$col_width[2];
						$attrib_total=0;
						$pdf->SetXY($cur_x,$cur_y);
						$pdf->Cell($col_width[2],$row_height , TEXT_TOTAL , 0 , 0 ,"L");
						$cur_x+=$col_width[3];
						$pdf->SetXY($cur_x,$cur_y);
						$pdf->Cell($col_width[3]-5,$row_height , $total , 0 , 0 ,"R");
						$pdf->SetFont($font_name,'',$font_size);
						check_page($cur_x,$cur_y,$prd_count);
						$total=0;
					}
					$prev_cat_id=$row["cat_id"];
					$pdf->SetFont($font_name,'B',$font_size+1);
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[0]+$col_width[1]+$col_width[2],$row_height,$row["cat_name"]);
					$pdf->SetFont($font_name,'',$font_size);
					check_page($cur_x,$cur_y,$prd_count);
				}
				if(!$summary_show) {
					$pdf->SetFont($font_name,'',$font_size);
					$pdf->SetFillColor($row_color[0],$row_color[1],$row_color[2]+$col_width[3]);
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[1],$row_height , $icnt+1 , 0 , 0 ,"L", 1);
					$cur_x+=$col_width[0];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->SetFont($font_name,'B',$font_size);
					$pdf->Cell($col_width[1]+$col_width[2],$row_height , $row["name"] , 0 , 0 ,"L", 1);
					$pdf->SetFont($font_name,'',$font_size);
					$cur_x+=$col_width[1];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->SetFont($font_name,'B',$font_size);
					$pdf->Cell($col_width[2]+$col_width[3],$row_height , $row["stock"] , 0 , 0 ,"R", 1);
					$pdf->SetFont($font_name,'',$font_size);
					$pdf->SetFillColor(255,255,255);
					check_page($cur_x,$cur_y,$prd_count);
					 $size_attribute=sizeof($attribute_array);
					 if($size_attribute>0) {
						 for($j=0;$j<$size_attribute;$j++){  
							   if($attribute_array[$j]['products_id']==$p_id){
									$pdf->SetFont($font_name,'',$font_size-2);
									//$pdf->SetFillColor($row_color[0],$row_color[1],$row_color[2]);
									$pdf->SetXY($cur_x,$cur_y);
									$pdf->Cell($col_width[1],$row_height , '' , 0 , 0 ,"L", 1);
									$cur_x+=$col_width[0];
									$pdf->SetXY($cur_x,$cur_y);
									$pdf->Cell($col_width[1],$row_height , $attribute_array[$j]['attributes_name'], 0 , 0 ,"L", 1);
									$cur_x+=$col_width[2];
									$pdf->SetXY($cur_x,$cur_y);
									$pdf->Cell($col_width[2],$row_height , $attribute_array[$j]['attributes_quantity'] , 0 , 0 ,"R", 1);
									$pdf->SetFillColor(255,255,255);
									check_page($cur_x,$cur_y,$prd_count);
								}
						} 
				  }
				}
				$total+=$row["stock"];
				
			}  
				if ($total>0) {
					$pdf->SetFont($font_name,'B',$font_size);
					$cur_x+=$col_width[0];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[0],$row_height , TEXT_TOTAL , 0 , 0 ,"L");
					$cur_x+=$col_width[1];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[1]+5,$row_height , $total , 0 , 0 ,"R");
					$pdf->SetFont($font_name,'',$font_size);
					$pdf->SetFont($font_name,'B',$font_size);
					$cur_x+=$col_width[2];
					$attrib_total=0;
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[2],$row_height , TEXT_ATTRIBUTE_QUANTITY   , 0 , 0 ,"R");
					$cur_x+=$col_width[3];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[3],$row_height , $attrib_total, 0 , 0 ,"R");
					$pdf->SetFont($font_name,'',$font_size);
					$total=0;
					check_page($cur_x,$cur_y,$prd_count);
				} 
			
			$pdf->output(DIR_FS_CATALOG . "images/" . $GLOBALS["report_filename"] . ".pdf");
		}
	// function to check page end in pdf output
		function check_page(&$cur_x,&$cur_y,&$prd_count){
			global $summary_show,$page_width,$page_height,$col_width,$font_name,$font_size,$pdf,$row_height,$col_width,$row_color,$header_color,$row_color;
			$cur_x=PDF_LEFT_MARGIN;
			$cur_y+=$row_height;
			if ($cur_y>$page_height){
				$pdf->AddPage();
				$cur_y=PDF_TOP_MARGIN;
				$pdf->SetFont($font_name,'B',$font_size);
			
		if($prd_count>0){	
				global $HTTP_POST_VARS;  
				$category_id = $HTTP_POST_VARS["cbo_category"];
				$stock_id = $HTTP_POST_VARS["cbo_stock_type"];
				$category_name="";
				$stock_type="";
			if($category_id == 0)
				$category_name="All Categories";
			else{
			$category_name_query = tep_db_query("select categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_id = '" . (int)$category_id . "'");
			$category_name_array = tep_db_fetch_array($category_name_query);
			$category_name = $category_name_array["categories_name"];
			}	
			
			
			//stock array
			$stock_array=array(	array('id'=>-1,'text'=>TEXT_ALL_PRODUCTS),
							array('id'=>1,'text'=>TEXT_LOW_INVENTORY),
							array('id'=>2,'text'=>TEXT_OUT_STOCK),
							array('id'=>3,'text'=>TEXT_RECENT_WEEK),
							array('id'=>4,'text'=>TEXT_RECENT_MONTH)
						); 
			
			$stock_type=$stock_array[$stock_id]["text"];
					if($stock_id == -1)
						$stock_type=TEXT_ALL_PRODUCTS;
			$summary = isset($HTTP_POST_VARS["chk_summary"])?TEXT_SUMMARY_ONLY:"";
				
				$pdf->setFillColor(255,255,255);
				$pdf->SetDrawColor(255,255,255);
				$pdf->setXY($cur_x,$cur_y);
				$pdf->cell(1,$row_height,TEXT_CATEGORY . " : " . $category_name . "                                     " 
				. TEXT_STOCK_TYPE . " : " . $stock_type . "                                        " . $summary  ,0,0,"L",1);
				
				
				$cur_y+=30;
				$cur_x=20; 
		} 
				
				$pdf->SetFillColor($header_color[0],$header_color[1],$header_color[2],$header_color[3]);
				$pdf->SetDrawColor(255,255,255);
				
				
				if($prd_count>0){
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[0],$row_height , TEXT_ID , 0 , 0 ,"L", 1);
					$cur_x+=$col_width[0]; 
										
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[1],$row_height , TEXT_PRODUCT_NAME , 0 , 0 ,"L", 1);
					$cur_x+=$col_width[1];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[2],$row_height , TEXT_ATTRIBUTE_QUANTITY , 0 , 0 ,"L", 1);
					$cur_x+=$col_width[2];
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[3],$row_height , TEXT_STOCK , 0 , 0 ,"R", 1);
					$cur_y+=$row_height*2;
				}else{
					$pdf->SetXY($cur_x,$cur_y);
					$pdf->Cell($col_width[1]+$col_width[3],$row_height , TEXT_NO_RECORDS_FOUND , 0 , 0 ,"R");
					$cur_y+=$row_height*2;
				}
				$cur_x=PDF_LEFT_MARGIN;
				$pdf->SetFont($font_name,'',$font_size);
				$pdf->SetFillColor(255,255,255);
				$pdf->SetDrawColor(0,0,0);
			}
		}

	function user_cmp($a, $b){
		global $categories;
		$atext="P" . $categories[$a]["path"];
		$btext="P" . $categories[$b]["path"];
	   if ( $atext== $btext) {
		   return 0;
	   }
	   return ($atext < $btext) ? -1 : 1;
	}
?>
