<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

print <<< HERE
<HTML>
<HEAD>
<TITLE> Inventory Report </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<style type="text/css">
/*
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                      }				 
table.master td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
				 
table.master td.sr  { font-size: 10px; 
					  font-style: italic; 
                      font-family:Times-New-Roman;
                    }

table.master td.grouplevel1 { font-size: 14px; 
							  font-weight: bold;
                              font-family:Times-New-Roman;
						      color: #0000FF;
							  background-color: #F0F0F0;
                            }
table.master td.grouplevel2 { font-size: 14px; 
                              font-family:Times-New-Roman;
						      color: #FF0000;
							  background-color: #F0F0F0;
                            }	
table.master td.grouplevel3 { font-size: 13px; 
							  font-style: italic;
                              font-family:Times-New-Roman;
						      color: #336600;
							  background-color: #F0F0F0;
                            }					
					
table.totals tr.summary { font-size: 13px; 
                          font-weight: bold;
                          font-family:Times-New-Roman;
						  background-color: #F0F0F0;
                        }					   

table.totals tr.grouplevel1total { font-size: 14px; 
								   font-weight: bold;
								   font-family:Times-New-Roman;
								   color: #0000FF;
								   background-color: #F0F0F0;
								 }				 
table.totals tr.grouplevel2total { font-size: 14px; 
							       font-family:Times-New-Roman;
							       color: #FF0000;
							       background-color: #F0F0F0;
						         }										 
table.totals tr.grouplevel3total { font-size: 13px; 
							       font-style: italic;
							       font-family:Times-New-Roman;
							       color: #336600;
							       background-color: #F0F0F0;
						          }						   				 
*/
</style>
</HEAD>

HERE;



include("config.inc.php");
include 'function.inc.php';

//Set Time Execution For the Report
//ini_set('max_execution_time', $config['ReportTimeExecution']);
set_time_limit(0);

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}



if ($printaccess==0 or $printaccess=='')
echo'<BODY oncontextmenu="return false;">';
else
echo'<BODY>';

$querylog="select fi_showcostprice,FI_ItemSelling1,FI_ItemSelling2,FI_ItemSelling3,FI_ItemSelling4,FI_ItemSelling5 from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')";
$resultlog=mysql_query($querylog) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
  extract($rows);
}
 

$querysetup="select grid_color1,grid_color2, DecimalBase, DecimalBase1, DecimalBase2, report_color1, report_color2, ifNull(InventoryRMaskqty,0) As InventoryRMaskqty, Base1, Base2, Company_Name As CompanyName from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}

$querylog=" select ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter, ".
		  " ifNull(FI_RepRestrictWarehouse,0) As FI_RepRestrictWarehouse ".
          " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."') ";
$resultlog=mysql_query($querylog) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_Grn,0) As Module_Grn, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Heatno,0) As Module_Heatno, ifNull(Module_expiredate,0) As Module_expiredate From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist  = mysql_num_rows($projectresult);

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%') ".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);		

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse where warehouse_code in ( select warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
		 "                                          where user_account='".$_SESSION['useraccount']."' ".
		 "                                          and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '') ) ".
		 " order by warehouse.warehouse_code";
$resultwh = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($resultwh);


$querygroup=" select distinct group_code,group_name ".
			" from grouping where group_code in (select group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."') ".
			" order by group_code";
$resultgroup = mysql_query($querygroup,$connection) or die(mysql_error());
$groupexist  = mysql_num_rows($resultgroup);

$now=current_server_time($connection);
$dt=split(" ",$now[0]);
$printdate=split("-",$dt[0]);
if (empty($existqty))     $existqty = 0;
if($existqty == 1) { 
 $layout='portrait';
 $tbwidth='730px';
 $descWidth='195';
 } else {
 $layout='landscape';
 $tbwidth='100%';
 $descWidth='400';
}
print <<< HERE
<table width="$tbwidth" border="0" align="left" >
HERE;
	//echo "<thead><tr><td align='left'>";
	
	//ShowReportHeader('Inventory',$layout, $connection);
	
	//echo"</td></tr></thead><tbody>";
if ($prtheader == 1){
	ShowReportHeader('Inventory','portrait', $connection);
} else {
	ShowReportTitle('Inventory','portrait', $connection);
}	

if ($cur == 'currency1'){
   $cur='null';  
   $displaycur = '';
}   
else {
   $displaycur = $cur;
   $cur="'".$cur."'";
}  


$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if($Module_expiredate==1 && $edatechk == 1)
	if ($fromedate != '')      $SelectedOptions .= "-> Expire Date From: ". $fromedate . "  To: ". $toedate ."<br>";	
if ($displaycur != '')    $SelectedOptions .= "-> Currency: ". $displaycur ."<br>";	
if ($fromitem != '')      $SelectedOptions .= "-> Item From: ". $fromitem . "  To: ". $toitem ."<br>";

if($Module_Heatno==1 and $vShowHeatno==1)
if ($fromheatno != '')      $SelectedOptions .= "-> HeatNo From: ". $fromheatno . "  To: ". $toheatno ."<br>";

if ($fromgroup != '')     $SelectedOptions .= "-> Group From: ". $fromgroup . "  To: ". $togroup ."<br>";
if ($fromsubgroup != '')  $SelectedOptions .= "-> SubGroup From: ". $fromsubgroup . "  To: ". $tosubgroup ."<br>";
if ($fromcategory != '')  $SelectedOptions .= "-> Category From: ". $fromcategory . "  To: ". $tocategory ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Project From: ". $fromproject . "  To: ". $toproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> Costcent From: ". $fromcostcent . "  To: ". $tocostcent . "<br>";
if ($fromwarehouse != '') $SelectedOptions .= "-> Warehouse From: ". $fromwarehouse . "  To: ". $towarehouse . "<br>";
if ($fromsupplier != '')  $SelectedOptions .= "-> Supplier From: ". $fromsupplier . "  To: ". $tosupplier . "<br>";



if (!empty($fromdate))   $fromdate = explodeword($fromdate);
if (!empty($todate))     $todate = explodeword($todate);  

if (!empty($fromedate))   $fromedate = explodeword($fromedate);
if (!empty($toedate))     $toedate = explodeword($toedate);  


$fromcur       = GetSQLValueString($fromcur, 'text');
$fromitem      = GetSQLValueString($fromitem, 'text');
$toitem        = GetSQLValueString($toitem, 'text');
$fromheatno      = GetSQLValueString($fromheatno, 'text');
$toheatno        = GetSQLValueString($toheatno, 'text');
$fromproject   = GetSQLValueString($fromproject, 'text');
$toproject     = GetSQLValueString($toproject, 'text');
$fromcostcent  = GetSQLValueString($fromcostcent, 'text');
$tocostcent    = GetSQLValueString($tocostcent, 'text');
$fromgroup     = GetSQLValueString($fromgroup, 'text');
$togroup       = GetSQLValueString($togroup, 'text');
$fromsubgroup  = GetSQLValueString($fromsubgroup, 'text');
$tosubgroup    = GetSQLValueString($tosubgroup, 'text');
$fromcategory  = GetSQLValueString($fromcategory, 'text');
$tocategory    = GetSQLValueString($tocategory, 'text');
$fromwarehouse = GetSQLValueString($fromwarehouse, 'text');
$towarehouse   = GetSQLValueString($towarehouse, 'text');
$fromdate	   = GetSQLValueString($fromdate, 'date');
$todate        = GetSQLValueString($todate, 'date');  
$fromedate	   = GetSQLValueString($fromedate, 'date');
$toedate        = GetSQLValueString($toedate, 'date');  
$fromsupplier  = GetSQLValueString($fromsupplier, 'date');   
$tosupplier    = GetSQLValueString($tosupplier, 'date');   
  

if (empty($prtqty))    $prtqty = 0;
if (empty($prtprice))  $prtprice = 0;
if (empty($prtprice1)) $prtprice1 = 0;
if (empty($prtprice2)) $prtprice2 = 0;
if (empty($prtprice3)) $prtprice3 = 0;
if (empty($prtprice4)) $prtprice4 = 0;
if (empty($prtprice5)) $prtprice5 = 0;
if (empty($prtcost))   $prtcost = 0;
if (empty($abvmax))    $abvmax = 0;
if (empty($blwmin))    $blwmin = 0;
if (empty($prtlpprice)) $prtlpprice = 0;


if (empty($booking))      $booking = 0;
if (empty($byserial))     $byserial = 0;
if (empty($showunmove))   $showunmove = 0;
if (empty($showunsold))   $showunsold = 0;
if (empty($packitem))     $packitem = 0;
if (empty($showdetail))   $showdetail = 0;
if (empty($showweight))   $showweight = 0;
if (empty($showunit2qty)) $showunit2qty = 0;
if (empty($showbarcode2)) $showbarcode2 = 0;
if (empty($nonstock)) 	  $nonstock = 0;




$displayprice = Array();
$priceaccess  = Array();
$prtprices    = Array();
   
if ($prtprice == 1 && $prtprice1 == 1)  { $prtprices[1] = 1; $displayprice[1] = 'I'; }
if ($prtprice == 1 && $prtprice2 == 1)  { $prtprices[2] = 1; $displayprice[2] = 'II'; }
if ($prtprice == 1 && $prtprice3 == 1)  { $prtprices[3] = 1; $displayprice[3] = 'III'; }
if ($prtprice == 1 && $prtprice4 == 1)  { $prtprices[4] = 1; $displayprice[4] = 'IV'; }
if ($prtprice == 1 && $prtprice5 == 1)  { $prtprices[5] = 1; $displayprice[5] = 'V'; }


if ($prtprice == 1 && $prtprice1 == 1 && $FI_ItemSelling1 == 1) $priceaccess[1] = 1;
if ($prtprice == 1 && $prtprice2 == 1 && $FI_ItemSelling2 == 1) $priceaccess[2] = 1;
if ($prtprice == 1 && $prtprice3 == 1 && $FI_ItemSelling3 == 1) $priceaccess[3] = 1;
if ($prtprice == 1 && $prtprice4 == 1 && $FI_ItemSelling4 == 1) $priceaccess[4] = 1;
if ($prtprice == 1 && $prtprice5 == 1 && $FI_ItemSelling5 == 1) $priceaccess[5] = 1;

$groupby1name = '';
$groupby2name = '';   
$groupby3name = '';
$QryGroupby1Code = '';
$QryGroupby2Code = '';
$QryGroupby3Code = '';
$QryGroupby1Name = '';
$QryGroupby2Name = '';
$QryGroupby3Name = '';

$SelWarehouse = 0;

if ($groupby3 != 1 ) {
	$pairs = explode(",", $groupby3);
	
	$vCount = count($pairs);
	if ($vCount > 1) {
		$QryGroupby3Code = 'Concat( ';
		$QryGroupby3Name = 'Concat( ';
	}	
	foreach ($pairs as $pair) {
		
		if ($groupby3name != '') {
			$groupby3name .= " & ";
			$QryGroupby3Code .= ", '*', ";
			$QryGroupby3Name .= ", '*', ";
		}	
			
		
		if ($pair == 20 ) {	
			$groupby3name    .= 'Transaction Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentProjectName,"None")';
		}
		else if ($pair == 4 ) {	
			$groupby3name    .= 'Transaction Project(Detail)';
			$QryGroupby3Code .= 'ifNull(ProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ProjectName,"None")';
		}
		else if ($pair == 21 ) {	
			$groupby3name 	 .= 'Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentMasterProject,"None")';
			$QryGroupby3Name .= 'ifNull(ParentMasterProject,"None")';
		}
		else if ($pair == 5 ) {	
			$groupby3name 	 .= 'Project(Detail)';
			$QryGroupby3Code .= 'ifNull(MasterProject,"None")';
			$QryGroupby3Name .= 'ifNull(MasterProject,"None")';
		}
		else if ($pair == 22 ) {	
			$groupby3name    .= 'Transaction Costcenter(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentCostcenterCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentCostcenterName,"None")';
		}
		else if ($pair == 6 ) {	
			$groupby3name    .= 'Transaction Costcenter(Detail)';	
			$QryGroupby3Code .= 'ifNull(CostcenterCode,"None")';
			$QryGroupby3Name .= 'ifNull(CostcenterName,"None")';
		}
		else if ($pair == 23 ) {
			$groupby3name 	 .= 'Costcenter(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentMasterCostcent,"None")';
			$QryGroupby3Name .= 'ifNull(ParentMasterCostcent,"None")';
		}
		else if ($pair == 7 ) {
			$groupby3name 	 .= 'Costcenter(Detail)';	
			$QryGroupby3Code .= 'ifNull(MasterCostcent,"None")';
			$QryGroupby3Name .= 'ifNull(MasterCostcent,"None")';
		}
		else if ($pair == 24 ) { 
			$SelWarehouse     = 1;
			$groupby3name	 .= 'Warehouse(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentWarehouseCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentWarehouseName,"None")';
		}
		else if ($pair == 8 ) { 	
			$SelWarehouse     = 1;
			$groupby3name	 .= 'Warehouse(Detail)';	
			$QryGroupby3Code .= 'ifNull(WarehouseCode,"None")';
			$QryGroupby3Name .= 'ifNull(WarehouseName,"None")';
		}
		else if ($pair == 25 )	{
			$groupby3name    .= 'Group(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentGroupName,"None")';
		}
		else if ($pair == 10 )	{
			$groupby3name    .= 'Group(Detail)';
			$QryGroupby3Code .= 'ifNull(GroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(GroupName,"None")';
		}
		else if ($pair == 26 )	{
			$groupby3name 	 .= 'Subgroup(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentSubGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentSubGroupName,"None")';
		}
		else if ($pair == 11 )	{
			$groupby3name 	 .= 'Subgroup(Detail)';
			$QryGroupby3Code .= 'ifNull(SubGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(SubGroupName,"None")';
		}
		else if ($pair == 12 ) {	
			$groupby3name 	 .= 'Category';
			$QryGroupby3Code .= 'ifNull(CategoryCode,"None")';
			$QryGroupby3Name .= 'ifNull(CategoryName,"None")';
		}
		else if ($pair == 13 ) {	
			$groupby3name 	 .= 'Supplier';
			$QryGroupby3Code .= 'ifNull(SupplierCode,"None")';
			$QryGroupby3Name .= 'ifNull(SupplierName,"None")';
		}
		else if ($pair == 14 ) {	
			$groupby3name 	 .= 'Expire Date';
			$QryGroupby3Code .= 'ifNull(Item_ExpireDate,"None")';
			$QryGroupby3Name .= 'ifNull(Item_ExpireDate,"None")';
		}
		
	}
	
	if ($vCount > 1) {
		$QryGroupby3Code .= ' ) ';
		$QryGroupby3Name .= ' ) ';
	}
	
	$QryGroupby3Code .= ' As Groupby3Code, ';
	$QryGroupby3Name .= ' As Groupby3Name, ';

} else 
{
	$QryGroupby3Code .= " -1 As Groupby3Code, ";
	$QryGroupby3Name .= " 'None' As Groupby3Name, ";
}
//echo $QryGroupby3Code."<br>";
//echo $QryGroupby3Name;
//exit;

if ($groupby1 != '' ) {
		
	if ($groupby1 == 20 ) {	
		$groupby1name    .= 'Transaction Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby1 == 4 ) {	
		$groupby1name    .= 'Transaction Project(Detail)';
		$QryGroupby1Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby1 == 21 ) {	
		$groupby1name 	 .= 'Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentMasterProject,"None")';
		$QryGroupby1Name .= 'ifNull(ParentMasterProject,"None")';
	}
	else if ($groupby1 == 5 ) {	
		$groupby1name 	 .= 'Project(Detail)';
		$QryGroupby1Code .= 'ifNull(MasterProject,"None")';
		$QryGroupby1Name .= 'ifNull(MasterProject,"None")';
	}
	else if ($groupby1 == 22 ) {	
		$groupby1name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentCostcenterCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentCostcenterName,"None")';
	}
	else if ($groupby1 == 6 ) {	
		$groupby1name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby1Code .= 'ifNull(CostcenterCode,"None")';
		$QryGroupby1Name .= 'ifNull(CostcenterName,"None")';
	}
	else if ($groupby1 == 23 ) {
		$groupby1name 	 .= 'Costcenter(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentMasterCostcent,"None")';
		$QryGroupby1Name .= 'ifNull(ParentMasterCostcent,"None")';
	}
	else if ($groupby1 == 7 ) {
		$groupby1name 	 .= 'Costcenter(Detail)';	
		$QryGroupby1Code .= 'ifNull(MasterCostcent,"None")';
		$QryGroupby1Name .= 'ifNull(MasterCostcent,"None")';
	}
	else if ($groupby1 == 24 ) { 	
		$SelWarehouse     = 1;
		$groupby1name	 .= 'Warehouse(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentWarehouseCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentWarehouseName,"None")';
	}
	else if ($groupby1 == 8 ) { 
		$SelWarehouse     = 1;
		$groupby1name	 .= 'Warehouse(Detail)';	
		$QryGroupby1Code .= 'ifNull(WarehouseCode,"None")';
		$QryGroupby1Name .= 'ifNull(WarehouseName,"None")';
	}
	else if ($groupby1 == 25 )	{
		$groupby1name    .= 'Group(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentGroupName,"None")';
	}
	else if ($groupby1 == 10 )	{
		$groupby1name    .= 'Group(Detail)';
		$QryGroupby1Code .= 'ifNull(GroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(GroupName,"None")';
	}
	else if ($groupby1 == 26 )	{
		$groupby1name 	 .= 'Subgroup(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentSubGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentSubGroupName,"None")';
	}
	else if ($groupby1 == 11 )	{
		$groupby1name 	 .= 'Subgroup(Detail)';
		$QryGroupby1Code .= 'ifNull(SubGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(SubGroupName,"None")';
	}
	else if ($groupby1 == 12 ) {	
		$groupby1name 	 .= 'Category';
		$QryGroupby1Code .= 'ifNull(CategoryCode,"None")';
		$QryGroupby1Name .= 'ifNull(CategoryName,"None")';
	}
	else if ($groupby1 == 13 ) {	
		$groupby1name 	 .= 'Supplier';
		$QryGroupby1Code .= 'ifNull(SupplierCode,"None")';
		$QryGroupby1Name .= 'ifNull(SupplierName,"None")';
	}
	else if ($groupby1 == 14 ) {	
		$groupby1name 	 .= 'Expire Date';
		$QryGroupby1Code .= 'ifNull(Item_ExpireDate,"None")';
		$QryGroupby1Name .= 'ifNull(Item_ExpireDate,"None")';
	}
	else {
		$groupby1name    .= '';				
		$QryGroupby1Code .= "-1";
		$QryGroupby1Name .= "'None'";
	}
		
	
	$QryGroupby1Code .= ' As Groupby1Code, ';
	$QryGroupby1Name .= ' As Groupby1Name, ';

} else 
{
	$QryGroupby1Code .= " -1 As Groupby1Code, ";
	$QryGroupby1Name .= " 'None' As Groupby1Name, ";
}

if ($groupby2 != '' ) {
		
	if ($groupby2 == 20 ) {	
		$groupby2name    .= 'Transaction Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby2 == 4 ) {	
		$groupby2name    .= 'Transaction Project(Detail)';
		$QryGroupby2Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby2 == 21 ) {	
		$groupby2name 	 .= 'Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentMasterProject,"None")';
		$QryGroupby2Name .= 'ifNull(ParentMasterProject,"None")';
	}
	else if ($groupby2 == 5 ) {	
		$groupby2name 	 .= 'Project(Detail)';
		$QryGroupby2Code .= 'ifNull(MasterProject,"None")';
		$QryGroupby2Name .= 'ifNull(MasterProject,"None")';
	}
	else if ($groupby2 == 22 ) {	
		$groupby2name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentCostcenterCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentCostcenterName,"None")';
	}
	else if ($groupby2 == 6 ) {	
		$groupby2name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby2Code .= 'ifNull(CostcenterCode,"None")';
		$QryGroupby2Name .= 'ifNull(CostcenterName,"None")';
	}
	else if ($groupby2 == 23 ) {
		$groupby2name 	 .= 'Costcenter(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentMasterCostcent,"None")';
		$QryGroupby2Name .= 'ifNull(ParentMasterCostcent,"None")';
	}
	else if ($groupby2 == 7 ) {
		$groupby2name 	 .= 'Costcenter(Detail)';	
		$QryGroupby2Code .= 'ifNull(MasterCostcent,"None")';
		$QryGroupby2Name .= 'ifNull(MasterCostcent,"None")';
	}
	else if ($groupby2 == 24 ) { 	
		$SelWarehouse     = 1;
		$groupby2name	 .= 'Warehouse(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentWarehouseCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentWarehouseName,"None")';
	}
	else if ($groupby2 == 8 ) { 	
		$SelWarehouse     = 1;
		$groupby2name	 .= 'Warehouse(Detail)';	
		$QryGroupby2Code .= 'ifNull(WarehouseCode,"None")';
		$QryGroupby2Name .= 'ifNull(WarehouseName,"None")';
	}
	else if ($groupby2 == 25 )	{
		$groupby2name    .= 'Group(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentGroupName,"None")';
	}
	else if ($groupby2 == 10 )	{
		$groupby2name    .= 'Group(Detail)';
		$QryGroupby2Code .= 'ifNull(GroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(GroupName,"None")';
	}
	else if ($groupby2 == 26 )	{
		$groupby2name 	 .= 'Subgroup(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentSubGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentSubGroupName,"None")';
	}
	else if ($groupby2 == 11 )	{
		$groupby2name 	 .= 'Subgroup(Detail)';
		$QryGroupby2Code .= 'ifNull(SubGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(SubGroupName,"None")';
	}
	else if ($groupby2 == 12 ) {	
		$groupby2name 	 .= 'Category';
		$QryGroupby2Code .= 'ifNull(CategoryCode,"None")';
		$QryGroupby2Name .= 'ifNull(CategoryName,"None")';
	}
	else if ($groupby2 == 13 ) {	
		$groupby2name 	 .= 'Supplier';
		$QryGroupby2Code .= 'ifNull(SupplierCode,"None")';
		$QryGroupby2Name .= 'ifNull(SupplierName,"None")';
	}
	else if ($groupby2 == 14 ) {	
		$groupby2name 	 .= 'Expire Date';
		$QryGroupby2Code .= 'ifNull(Item_ExpireDate,"None")';
		$QryGroupby2Name .= 'ifNull(Item_ExpireDate,"None")';
	}
	else {
		$groupby2name    .= '';				
		$QryGroupby2Code .= "-1";
		$QryGroupby2Name .= "'None'";
	}
		
	
	$QryGroupby2Code .= ' As Groupby2Code, ';
	$QryGroupby2Name .= ' As Groupby2Name, ';

} else 
{
	$QryGroupby2Code .= " -1 As Groupby2Code, ";
	$QryGroupby2Name .= " 'None' As Groupby2Name, ";
}


$SelectedGroupBy = "Group by:  ";
if ($groupby1 != '' ) $SelectedGroupBy = $SelectedGroupBy . $groupby1name.", ";
if ($groupby2 != '' ) $SelectedGroupBy = $SelectedGroupBy . $groupby2name.", ";
if ($groupby3 != 1 )  $SelectedGroupBy = $SelectedGroupBy . $groupby3name.", ";
$SelectedOptions = substr($SelectedGroupBy, 0, strlen($SelectedGroupBy)-2) . "<br>" . $SelectedOptions;
				

print <<<HERE

<tr><td>
<table class="report-master"  border="0" align="left" style='table-layout:fixed;clear:left;'>
<col width=100>
<tr><td>&nbsp;</td>
  <td  valign='top' width=100%><b>$SelectedOptions</b></td>
</tr>
<tr height='5'><td><h5></td></tr>
</table></td></tr>

HERE;


echo "<tr><td><table  border='0' width='' class='report-master' style='clear:left;' align='left' cellpadding='0' cellspacing='0'>";
echo"<thead><tr><td>";	

//Create Table Columns
CreateTableHeader($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $showweight, $showunit2qty, $showbarcode2,$Module_Heatno,$vShowHeatno,$descWidth,$tbwidth, $edatechk);

echo"</td></tr></thead>";
//echo"<tr><td><hr width='100%' color='black' size='2'></td></tr>";
 
 
$QueryRestrictPrj = " Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
					" 			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
					"              and (project_code is not null and project_code != '') ".
					"			 ) Q4  ";
					
$QueryRestrictCst = " Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
					"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
					"              and (costcent_code is not null and costcent_code != '') ".
					"			 ) Q5  ";
					

$query = '';

if ($showdetail == 0) {
	$query = $query." Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, Null as ItemCode, Null as ItemDescription, ".
					" WarehouseCode, Null as ItemUnit, Null as ItemMaxQty, Null as ItemMinQty, ItemWithSerialno, ".
					" sum(QtyPrev) As QtyPrev, sum(QtyIn) As QtyIn, sum(QtyOut) As QtyOut, sum(QtyExist) As QtyExist, sum(ReservedQty) As ReservedQty, ".
					" CurrencyCode, 0 as MeanCost, sum(ValIn) As ValIn, sum(ValOut) As ValOut, sum(ValueTotal) As ValueTotal, ".
					" 0 as SellPrice1, ItemCodePacked, QtyPack, Null as ItemWeight, Null as Item_UnitSalesDesc, 0 as TotalWeight, Null as Item_UnitPurchaseDesc, ".
					" sum(QtyUnit2) As QtyUnit2, Null as ItemBarcode2, 0 as SellPrice2, 0 as SellPrice3, 0 as SellPrice4, 0 as SellPrice5, 0 as LastPricePurchase,Item_Heatno, Item_ExpireDate,VAT,sum(ValueTotal1) As ValueTotal1 ".
					" From ( ";

}					

if ($packitem == 1) {
	$query = $query." Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, ItemCode, ItemDescription, WarehouseCode, ".
					" ItemUnit, ItemMaxQty, ItemMinQty, ItemWithSerialno, QtyPrev, QtyIn, QtyOut, QtyExist, ReservedQty, ".
					" CurrencyCode, MeanCost, ValIn, ValOut, ValueTotal, SellPrice1, ItemCodePacked, QtyPack, ItemWeight, Item_UnitSalesDesc, TotalWeight, ".
					" Item_UnitPurchaseDesc, QtyUnit2, ItemBarcode2, SellPrice2, SellPrice3, SellPrice4, SellPrice5, LastPricePurchase,Item_Heatno, Item_ExpireDate,VAT,ValueTotal1  ".
					" From ( ".
					" Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, ".
					" if($packitem=1, if(ItemCodePacked='' or ItemCodePacked is null, ItemCode, ItemCodePacked), ItemCode) As ItemCode, ".
					" ItemDescription, WarehouseCode, ItemUnit, ItemMaxQty, ItemMinQty, ItemWithSerialno, ".
					" min(floor(QtyPrev/QtyPack)) as QtyPrev, min(floor(QtyIn/QtyPack)) as QtyIn, ".
					" min(floor(QtyOut/QtyPack)) as QtyOut, min(floor(QtyExist/QtyPack)) as QtyExist, min(floor(ReservedQty/QtyPack)) as reservedqty, ".
					" CurrencyCode, MeanCost, ValIn, ValOut, ValueTotal, SellPrice1, ItemCodePacked, QtyPack, ItemWeight, Item_UnitSalesDesc, TotalWeight, ".
					" Item_UnitPurchaseDesc, min(floor(QtyUnit2/QtyPack)) as QtyUnit2, Null as ItemBarcode2, SellPrice2, SellPrice3, SellPrice4, SellPrice5, LastPricePurchase,Item_Heatno, Item_ExpireDate,VAT,ValueTotal1  ".
					" From ( ";
}

$query = $query." Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, ItemCode, ItemDescription, WarehouseCode, ".
				" ItemUnit, ItemMaxQty, ItemMinQty, ItemWithSerialno, QtyPrev, QtyIn, QtyOut, QtyExist, ReservedQty, ".
				" CurrencyCode, MeanCost, (MeanCost*QtyIn) as ValIn, (MeanCost*QtyOut) as ValOut,  (MeanCost*QtyExist) as ValueTotal, ".
				" SellPrice1, ItemCodePacked, QtyPack, ItemWeight, Item_UnitSalesDesc, (ItemWeight*QtyExist) as TotalWeight, Item_UnitPurchaseDesc, QtyUnit2, ItemBarcode2, ".
				" SellPrice2, SellPrice3, SellPrice4, SellPrice5, LastPricePurchase, Item_ExpireDate,VAT,(MeanCost1*QtyExist) as ValueTotal1 ";

$query = $query." From (   ".
			    "     Select ItemCode, ItemBarcode2, ItemDescription, WarehouseCode, ItemUnit, ItemMaxQty, ItemMinQty, ItemWeight, Item_UnitSalesDesc, Item_UnitPurchaseDesc, ItemWithSerialno, ".
                "     Sum(ifNull(QtyPrev,0)) as QtyPrev, Sum(ifNull(QtyIn,0)) as QtyIn, Sum(ifNull(QtyOut,0)) as QtyOut, Sum(ifNull(QtyUnit2,0)) as QtyUnit2, ".
				"     (Sum(ifNull(QtyPrev,0)) + Sum(ifNull(QtyIn,0)) - Sum(ifNull(QtyOut,0))) as QtyExist, ReservedQty, ";
$query = $query.$QryGroupby1Code . $QryGroupby1Name.
                $QryGroupby2Code . $QryGroupby2Name.
				$QryGroupby3Code . $QryGroupby3Name;
					  
$query = $query." CurrencyCode, ";
//nabil 2015-12-29
if ($fi_showcostprice == 1 && $prtcost == 1) {
	//if ($PCostMethod == 0) {		
	//	$query=$query." ifNull(MeanCostCur(ItemCode, concat(".$todate.", ' 23:59:59'), if(upper($cur)='".$Base1."', 1,if(upper($cur)='".$Base2."',2, 0)), CurrencyCode, if(upper($cur)='".$Base1."', '',if(upper($cur)='".$Base2."','',ifnull($fromcur, ItemCurrCode) ))),0) MeanCost,  ";
	//} else {
	//	$query=$query." ifNull(convertcurfunc(items.currency_code, '".$cur."', concat(".$todate.", ' 23:59:59'), 0, 0, '', '', ifNull(GetLastValuesFunc('".$Base1."', '".$PCurBase2."', ItemCode),0)),0)  MeanCost,  ";
	//}
	$query=$query." if(Item_CostMethod=0,ifNull(MeanCostCur(ItemCode, concat(".$todate.", ' 23:59:59'), if(upper($cur)='".$Base1."', 1,if(upper($cur)='".$Base2."',2, 0)), CurrencyCode, if(upper($cur)='".$Base1."', '',if(upper($cur)='".$Base2."','',ifnull($fromcur, ItemCurrCode) ))),0),
		ifNull(convertcurfunc(ItemCurrCode, ".$cur.", concat(".$todate.", ' 23:59:59'), 0, 0, '', '', ifNull(GetLastValuesDateFunc('".$Base1."', '".$PCurBase2."', ItemCode,concat(".$todate.", ' 23:59:59')),0)),0))  MeanCost,if(Item_CostMethod=0,ifNull(MeanCostCur(ItemCode, concat(".$todate.", ' 23:59:59'), if(upper($cur)='".$Base2."', 1,if(upper($cur)='".$Base1."',2, 0)), CurrencyCode, if(upper($cur)='".$Base2."', '',if(upper($cur)='".$Base1."','',ifnull($fromcur, ItemCurrCode) ))),0),
		ifNull(convertcurfunc(ItemCurrCode, ".$cur.", concat(".$todate.", ' 23:59:59'), 0, 0, '', '', ifNull(GetLastValuesDateFunc('".$Base1."', '".$PCurBase2."', ItemCode,concat(".$todate.", ' 23:59:59')),0)),0))  MeanCost1,  ";
} else {
	$query=$query." 0 as MeanCost,0 as MeanCost1, ";
}
				
$query = $query." ItemCodePacked, QtyPack, ".
				" if(upper($cur)='".$Base1."', Item_SellingPrice1Base1, if(upper($cur)='".$Base2."', Item_SellingPrice1Base2, Item_SellingPrice1)) as SellPrice1, ".
				" if(upper($cur)='".$Base1."', Item_SellingPrice2Base1, if(upper($cur)='".$Base2."', Item_SellingPrice2Base2, Item_SellingPrice2)) as SellPrice2, ".
				" if(upper($cur)='".$Base1."', Item_SellingPrice3Base1, if(upper($cur)='".$Base2."', Item_SellingPrice3Base2, Item_SellingPrice3)) as SellPrice3, ".
				" if(upper($cur)='".$Base1."', Item_SellingPrice4Base1, if(upper($cur)='".$Base2."', Item_SellingPrice4Base2, Item_SellingPrice4)) as SellPrice4, ".
				" if(upper($cur)='".$Base1."', Item_SellingPrice5Base1, if(upper($cur)='".$Base2."', Item_SellingPrice5Base2, Item_SellingPrice5)) as SellPrice5, ".
				" if(upper($cur)='".$Base1."', Item_LastPricePurchaseB1, if(upper($cur)='".$Base2."', Item_LastPricePurchaseB2, Item_LastPricePurchase)) as LastPricePurchase,Item_ExpireDate,VAT ".
				" From  ".
                " ( ".
				"   select items.item_code As ItemCode, item_description As ItemDescription, item_unit As ItemUnit, item_maxqty As ItemMaxQty, item_minqty As ItemMinQty, Items.Item_Barcode2 as ItemBarcode2, ".
				"   items.Item_Weight as ItemWeight, items.Item_UnitSalesDesc, items.Item_UnitPurchaseDesc, items.currency_code As ItemCurrCode, ifnull(items.item_withserialno,0) As ItemWithSerialno, ".
				"   ifNull(Grouping.Parent_Code, Items.Group_Code) As ParentGroupCode, Grouping.Group_Name As ParentGroupName, ".
				"   Items.Group_Code As GroupCode, Grouping.Group_Name As GroupName, ".
				"   ifNull(Subgroup.Parent_Code, Items.SubGroup_Code) As ParentSubGroupCode, Subgroup.Subgroup_Name As ParentSubGroupName, ".
				"   Items.SubGroup_Code As SubGroupCode, Subgroup.Subgroup_Name As SubGroupName, ".
				"   Items.Category_Code As CategoryCode, Category.Category_Name As CategoryName, ".
				"   Items.Ledger_Number As SupplierCode, Ledger.Ledger_Name As SupplierName, ".
				"   stktransaction.Warehouse_Code As WarehouseCode, warehouse.warehouse_name As WarehouseName, ".
				"   ifNull(Warehouse.Parent_Code, stktransaction.Warehouse_Code) As ParentWarehouseCode,  warehouse.warehouse_name As ParentWarehouseName, ".
				"   ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode, Costcent.Costcent_Name As ParentCostcenterName, ".
				"   stktransaction.Costcent_code As CostcenterCode, Costcent.Costcent_Name As CostcenterName, ".
				"   ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				"   stktransaction.Project_Code As ProjectCode, Project.Project_Name As ProjectName, ".
				//"   Items.Project_Code As MasterProject, Items.CostCent_Code As MasterCostcent, ".
				"   Items.Project_Code As MasterProject, stktransaction.CostCent_Code As MasterCostcent, ".
				"   ifNull(Project1.Parent_Code, Items.Project_Code) As ParentMasterProject, ifNull(Costcent1.Parent_Code, Items.CostCent_Code) As ParentMasterCostcent, ".
				//"   ifnull($fromcur, items.currency_code) As CurrencyCode, ".
				"   if(upper($cur)='".$Base1."', '".$Base1."',if(upper($cur)='".$Base2."','".$Base2."',ifnull($fromcur, items.currency_code))) As CurrencyCode, ".
				"   if(date_format(transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(transaction_date,'%Y-%m-%d')) , (ifNull(quantityproducein,0) + ifNull(quantityentered,0)), 0) QtyIn, ".
				"   if(date_format(transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(transaction_date,'%Y-%m-%d')) ,(ifNull(quantityproduceout,0) + ifNull(quantitydelivered,0)), 0) QtyOut, ".
				"   if(date_format(transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(transaction_date,'%Y-%m-%d')) , if(stktransaction.transaction_type IN ('GR','PI','DR','AI','AD','PD','TRT'), ifNull(Unit2Qty,0), (-1)*ifNull(Unit2Qty,0)), 0) QtyUnit2, ".
				"   if(date_format(transaction_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(transaction_date,'%Y-%m-%d')),(ifNull(quantityproducein,0) + ifNull(quantityentered,0) ) - (ifNull(quantityproduceout,0) + ifNull(quantitydelivered,0)), 0)  QtyPrev, ";
			  
				/*if ($fi_showcostprice == 1 && $prtcost == 1) {			
					$query=$query." ifNull(MeanCostCur(stktransaction.item_code, concat(".$todate.", ' 23:59:59'), if(upper($cur)='".$Base1."', 1,if(upper($cur)='".$Base2."',2, 1)), stktransaction.currency_code, if(upper($cur)='".$Base1."', '',if(upper($cur)='".$Base2."','',ifnull($fromcur, items.currency_code) ))),0) MeanCost,  ";
				} else {
					$query=$query." 0 as MeanCost, ";
				}*/

$query = $query." ifNull(Item_SellingPrice1,0) as Item_SellingPrice1, ifNull(Item_SellingPrice1Base1,0) as Item_SellingPrice1Base1, ifNull(Item_SellingPrice1Base2,0) as Item_SellingPrice1Base2, ".
				" ifNull(Item_SellingPrice2,0) as Item_SellingPrice2, ifNull(Item_SellingPrice2Base1,0) as Item_SellingPrice2Base1, ifNull(Item_SellingPrice2Base2,0) as Item_SellingPrice2Base2, ".
				" ifNull(Item_SellingPrice3,0) as Item_SellingPrice3, ifNull(Item_SellingPrice3Base1,0) as Item_SellingPrice3Base1, ifNull(Item_SellingPrice3Base2,0) as Item_SellingPrice3Base2, ".
				" ifNull(Item_SellingPrice4,0) as Item_SellingPrice4, ifNull(Item_SellingPrice4Base1,0) as Item_SellingPrice4Base1, ifNull(Item_SellingPrice4Base2,0) as Item_SellingPrice4Base2, ".
				" ifNull(Item_SellingPrice5,0) as Item_SellingPrice5, ifNull(Item_SellingPrice5Base1,0) as Item_SellingPrice5Base1, ifNull(Item_SellingPrice5Base2,0) as Item_SellingPrice5Base2, ".
				" ifNull(Item_LastPricePurchase,0) as Item_LastPricePurchase, ".
				" ifNull(convertcurfunc(items.currency_code, '".$Base1."', transaction_date, 0, 0, '', '', ifNull(Item_LastPricePurchase,0)),0) as Item_LastPricePurchaseB1, ".
				" ifNull(convertcurfunc(items.currency_code, '".$Base2."', transaction_date, 0, 0, '', '', ifNull(Item_LastPricePurchase,0)),0) as Item_LastPricePurchaseB2 ".
				" , stktransaction.Item_Heatno";
if ($booking==1) {
	$query=$query.", QtyBooking(stktransaction.item_code,if($SelWarehouse=1, stktransaction.warehouse_code, null), ifNull(". $todate.", now())) as ReservedQty ";
} else {
	$query=$query.", 0 as ReservedQty ";
}
				
if ($packitem == 1) 				
	$query = $query.", if(stktransaction.item_codepacked='', Null, stktransaction.Item_CodePacked) As ItemCodePacked, ifNull(packdt.packdt_quantity, 1) As QtyPack ";
else
	$query = $query.", Null As ItemCodePacked, 1 As QtyPack ";	
	
//nabil 2015-12-29
$query = $query." , Item_CostMethod, date_format(StkTransaction.Item_ExpireDate,'%d-%m-%Y') as Item_ExpireDate,IF(items.item_vat=0 ,'NO', IF(items.item_vat=NULL ,'NO', 'YES')) as VAT ";		
	
if ($showunmove == 1 || $showunsold == 1) {	
	$query = $query." from items ".
					" left join stktransaction on if($packitem=1, if(stktransaction.item_codepacked='' or stktransaction.item_codepacked is null, stktransaction.item_code, stktransaction.item_codepacked), stktransaction.item_code) = items.item_code ";
} else {
	$query = $query." from stktransaction ".
					" Inner Join Items on if($packitem=1, if(stktransaction.item_codepacked='' or stktransaction.item_codepacked is null, stktransaction.item_code, stktransaction.item_codepacked), stktransaction.item_code) = items.item_code ";
}	
					  
if ($packitem == 1) {				
	$query = $query." Left join packdt on stktransaction.item_codepacked = packdt.Item_Code and stktransaction.item_code = packdt.Item_CodePackDt ";
}
					  

$query = $query." left join grouping on items.group_code = grouping.group_code ".
				" left join subgroup on items.subgroup_code = subgroup.subgroup_code ".
				" left join category on items.category_code = category.category_code ".
				" left join suppliers on items.Ledger_Number = suppliers.Ledger_number ".
				" left join Ledger on items.Ledger_Number = Ledger.Ledger_Number ".
				" left join project on stktransaction.project_code = project.project_code ".
				" left join costcent on stktransaction.costcent_code = costcent.costcent_code ".
				" Left Join Costcent As Costcent1 on Costcent1.Costcent_Code = Items.CostCent_Code ".
				" Left Join Project As Project1 on Project1.Project_Code = Items.Project_Code ".
				" left join warehouse on stktransaction.warehouse_code = warehouse.warehouse_code ";
					
if ($showunmove == 1 || $showunsold == 1) {					
	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query = $query.$QueryRestrictPrj." on items.project_code like concat(Q4.project_code,'%') ";
									 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query = $query.$QueryRestrictCst." on items.costcent_code like concat(Q5.costcent_code,'%') ";
} else {
	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query = $query.$QueryRestrictPrj." on stktransaction.project_code like concat(Q4.project_code,'%') ";
									 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query = $query.$QueryRestrictCst." on stktransaction.costcent_code like concat(Q5.costcent_code,'%') ";
}		

$query = $query." where items.item_code between ifNull(".$fromitem.",items.item_code) and ifNull(". $toitem.",items.item_code) ";
if($itemprint == '1') $query = $query." and items.item_printed = 1 ";
else if($itemprint == '0') $query = $query." and items.item_printed = 0 ";	
else 	$query = $query." and (items.item_printed = 0 or items.item_printed = 1) ";			
$query = $query." and IfNull(stktransaction.item_heatno,-1) between ifNull(".$fromheatno.",IfNull(stktransaction.item_heatno,-1)) and ifNull(". $toheatno.",IfNull(stktransaction.item_heatno,-1))	".
				" and ifNull(items.Ledger_Number,'-1') between ifNull(".$fromsupplier.",ifNull(items.Ledger_Number,'-1')) and ifNull(". $tosupplier.",ifNull(items.Ledger_Number,'-1')) ".
				" and ifNull(stktransaction.project_code,'-1') between ifNull(".$fromproject.",ifNull(stktransaction.project_code,'-1')) and ifNull(". $toproject.",ifNull(stktransaction.project_code,'-1')) ".
				" and ifNull(stktransaction.costcent_code,'-1') between ifNull(".$fromcostcent.",ifNull(stktransaction.costcent_code,'-1')) and ifNull(". $tocostcent.",ifNull(stktransaction.costcent_code,'-1')) ".
				" and ifNull(stktransaction.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(stktransaction.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(stktransaction.warehouse_code,'-1')) ".
				" and ifNull(items.group_code,'-1') between ifNull(". $fromgroup .",ifNull(items.group_code,'-1')) and ifNull(". $togroup.",ifNull(items.group_code,'-1')) ".
				" And ifNull(Items.SubGroup_Code,'-1') between ifNull(". $fromsubgroup .",ifNull(Items.SubGroup_Code,'-1')) and ifNull(". $tosubgroup.",ifNull(Items.SubGroup_Code,'-1'))  ".
				" And ifNull(Items.Category_Code,'-1') between ifNull(". $fromcategory .",ifNull(Items.Category_Code,'-1')) and ifNull(". $tocategory.",ifNull(Items.Category_Code,'-1'))  ".
				" And (($nonstock = 1 and 1 = 1) or ($nonstock = 0 and ifNull(Items.Item_NonStock,0) = 0)) ";
if($Module_expiredate==1 && $edatechk == 1)
	$query=$query." and date_format(StkTransaction.Item_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(StkTransaction.Item_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(StkTransaction.Item_ExpireDate,'%Y-%m-%d')) ";
				//" and date_format(transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(transaction_date,'%Y-%m-%d'))  ".
				//" And Items.Item_NonStock = 0 ".
                //" And Item_FixedAsset = 0 ".
				
if ($showunmove != 1 && $showunsold != 1) {
	$query = $query." and ((($SelWarehouse=1 or $fromwarehouse is not null or $towarehouse is not null) and stktransaction.transaction_type IN ('GR','PI','PR','DI','DR','AI','AR','AD','PD','PDT','TR','TRT','SO','PO')) ".
					"   or (($SelWarehouse=0 and $fromwarehouse is null and $towarehouse is null) and stktransaction.transaction_type IN ('GR','PI','PR','DI','DR','AI','AR','AD','PD','PDT','SO','PO'))) ";
}					
					  
if ($whexist > 0  && $FI_RepRestrictWarehouse == 1 && $showunmove != 1 && $showunsold != 1)
	$query = $query." and stktransaction.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
if ($groupexist > 0)
	$query = $query." and items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  

  
//Tarek 2011-10-26  
if ($Module_Grn == 1)
	$query = $query." And StkTransaction.Transaction_Type <> 'PI' ";
	
$query = $query."  ) As Q1  ".
				"  Group By Groupby1Code, Groupby2Code, Groupby3Code, ItemCode, ItemCodePacked  ".
				"  Order by Groupby1Code, Groupby2Code, Groupby3Code, if($orderby=1, ItemCode, ItemDescription), ItemCodePacked  ".
				" ) As Q2  ";
				
					  
if ($packitem == 1) {
	$query = $query." ) As Q3 ".
				    " Group By Groupby1Code, Groupby2Code, Groupby3Code, ItemCode, ItemCodePacked ";
					
	if ($orderby == 1)
		$query = $query." Order By Groupby1Code, Groupby2Code, Groupby3Code, ItemCode, ItemCodePacked  ";
	else
		$query = $query." Order By Groupby1Code, Groupby2Code, Groupby3Code, ItemDescription, ItemCode, ItemCodePacked  ";
		
	$query = $query." ) As Q7 ";
					  
}				

$query = $query." Where (($zeroprint=1 and QtyExist = 0) or ($zeroprint=2 and round(QtyExist,$InventoryRMaskqty) != 0) or ($zeroprint=3 and 1 = 1) ) " .
				" And (($abvmax=1 and QtyExist > ItemMaxQty) or ($blwmin=1 and QtyExist < ItemMinQty) or ($abvmax=0 and $blwmin=0 and 1=1)) ".
				" And (if('$shownegativeqty' = '1',QtyExist < 0,1 = 1))";
				
if ($showunmove == 1) {
	if ($packitem == 1) {
		$query = $query." and not exists ( select 1 from  stktransaction as stk ".
						"                  where stk.item_code = Q7.ItemCode ".
						"                  and date_format(stk.transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(stk.transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(stk.transaction_date,'%Y-%m-%d')) ".
						"                ) ";
	} else {
		$query = $query." and not exists ( select 1 from  stktransaction as stk ".
						"                  where stk.item_code = Q2.ItemCode ".
						"                  and date_format(stk.transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(stk.transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(stk.transaction_date,'%Y-%m-%d')) ".
						"                ) ";
	}
}
else if ($showunsold == 1) {
	if ($packitem == 1) {
		$query = $query." and not exists ( select 1 from  stktransaction as stk ".
						"                  where stk.item_code = Q7.ItemCode ".
						"				   and stk.transaction_type in ('SI','DI') ".
						"                  and date_format(stk.transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(stk.transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(stk.transaction_date,'%Y-%m-%d')) ".
						"                ) ";
	} else {
		$query = $query." and not exists ( select 1 from  stktransaction as stk ".
						"                  where stk.item_code = Q2.ItemCode ".
						"				   and stk.transaction_type in ('SI','DI') ".
						"                  and date_format(stk.transaction_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(stk.transaction_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(stk.transaction_date,'%Y-%m-%d')) ".
						"                ) ";
	}
}

if ($showdetail == 0) {
	$query = $query." ) As Q8 ".
					" Group By Groupby1Code, Groupby2Code, Groupby3Code ".
					" Order By Groupby1Code, Groupby2Code, Groupby3Code ";
}
	
	
				
echo $query;
//exit;

$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArrayTotalByGroup1   = Array();
$ArrayTotalByGroup2   = Array();
$ArrayTotalByGroup3   = Array();

$MainGroup1 = '';
$MainGroup2 = '';
$MainGroup3 = '';
$groupby1desc = '';
$groupby2desc = '';
$groupby3desc = '';

$col=0;
$result=mysql_query($query, $connection) or die(mysql_error());

while($rows=mysql_fetch_row($result)){
	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
    
    	
	//Group By Options Level 3 Totals
	if ( ($groupby3 != 1 && $showdetail == 1) && (($MainGroup3 != $rows[4] && $MainGroup3 != '') || ($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
		
		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
				
		$StyleClass  = 'grouplevel3total';
		$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
		DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup3, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);
					
	}
		
	//Group By Options Level 2 Totals
	if ( ($groupby2 != '' && ($showdetail == 1 || $groupby3 != 1)) && (($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
	  
		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
				

		$StyleClass  = 'grouplevel2total';
		$TotalsLabel = 'Total 2 - '.$groupby2name.' : '.$groupby2code;
		DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup2, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);
		
	}
		
	//Group By Options Level 1 Totals
	if ( ($groupby1 != '' && ($showdetail == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 != $rows[0] && $MainGroup1 != '') ){
	  
		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
				
		
		$StyleClass  = 'grouplevel1total';
		$TotalsLabel = 'Total 1 -  '.$groupby1name.' : '.$groupby1code;
		DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup1, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);

	}
	
	if ( ($groupby1 != ''  && $MainGroup1 != '' && $MainGroup1 != $rows[0]) || 
		 ($groupby2 != ''  && $MainGroup2 != '' && $MainGroup2 != $rows[2]) ||
		 ($groupby3 != 1   && $MainGroup3 != '' && $MainGroup3 != $rows[4])  )
	{
		echo "<tr><td align='left' valign='top'>&nbsp;</td></tr>"; 
	}
		
	//Group By Options Level 1 Names 
	if ( ($groupby1 != '' && ($showdetail == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 == '' || $MainGroup1 != $rows[0])  ){
			
		$groupby1code = '';
		if ($rows[0] == -1)
		   $groupby1code = '';
		else
            $groupby1code = $rows[0];			
		
		echo "<tr>";
		echo "   <td align='left' valign='top' class='grouplevel1' style='padding-left:120px'>1 -  ". $groupby1name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby1code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
		         str_replace('*',' --> ',$rows[1]) ."</td>";
		echo "</tr>"; 
				
						
		$MainGroup1   = $rows[0];
		$groupby1desc = $rows[1];
		
		$MainGroup2   = '';
		$groupby2desc = '';
		$MainGroup3   = '';
		$groupby3desc = '';	
		
		unset($ArrayTotalByGroup1);		
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);
		
	}
		
	//Group By Options Level 2 Names 
	if ( ($groupby2 != '' && ($showdetail == 1 || $groupby3 != 1)) && ($MainGroup2 == '' || $MainGroup2 != $rows[2])  ){
			
		$groupby2code = '';
		if ($rows[2] == -1)
		   $groupby2code = '';
		else
              $groupby2code = $rows[2];			
		
		echo "<tr>";
		echo "   <td align='left' valign='top' class='grouplevel2' style='padding-left:120px'>2 -   ". $groupby2name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby2code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
		         str_replace('*',' --> ',$rows[3]) ."</td>";
		echo "</tr>"; 
				
						
		$MainGroup2   = $rows[2];
		$groupby2desc = $rows[3];
		
		$MainGroup3   = '';
		$groupby3desc = '';	
		
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);

	}
		
	//Group By Options Level 3 Names 
	if ( ($groupby3 != 1 && $showdetail == 1) && ($MainGroup3 == '' || $MainGroup3 != $rows[4])  ){
			
		$groupby3code = '';
		if ($rows[4] == -1)
		   $groupby3code = '';
		else
            $groupby3code = $rows[4];			
			   
		echo "<tr >";
		echo "   <td align='left' valign='top' class='grouplevel3' style='padding-left:120px'>3 -  ". $groupby3name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby3code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
		         str_replace('*',' --> ',$rows[5]) ."</td>";
		echo "</tr>"; 
				
		echo "<tr>";
		echo "   <td align='left' valign='top'>&nbsp;</td>";
		echo "</tr>"; 
						
		$MainGroup3   = $rows[4];
		$groupby3desc = $rows[5];
			
		unset($ArrayTotalByGroup3);
	}
    
	
	echo "<tr><td colspan=2>";
	
	//Create Table Columns
	CreateTableStructure($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $showweight, $showunit2qty, $showbarcode2, $Module_Heatno, $vShowHeatno,$descWidth,$tbwidth, $edatechk);

	echo "<tr class='group' $color>"; 
	
	if ($showdetail == 0 && $groupby1 != '' && $groupby2 == '' && $groupby3 == 1) {
		echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rows[0])."  -  ".str_replace('*',' --> ',$rows[1])."</td>";
	}
	else if ($showdetail == 0 && $groupby2 != '' && $groupby3 == 1) {
		echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rows[2])."  -  ".str_replace('*',' --> ',$rows[3])."</td>";
	}
	else if ($showdetail == 0 && $groupby3 != 1) {
		echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rows[4])."  -  ".str_replace('*',' --> ',$rows[5])."</td>";
	}
	else {
		if( $edatechk == 1) echo "<td align='left' valign='top' > ". $rows[37] ."</td>";
		echo "<td align='left' valign='top' > ". $rows[6] ."</td>";
		echo "<td align='left' valign='top' >". $rows[7] ."</td>";
	}
	
	echo "<td align='left' valign='top' >". $rows[27] ."</td>";
	echo "<td align='left' valign='top' >". $rows[9] ."</td>";
	
	
	
	if($Module_Heatno==1 and $vShowHeatno==1)	
	echo "<td align='left' valign='top' >". $rows[37] ."</td>";
	
	if ($showweight == 1 ) {
		echo "<td align='right' valign='top' >". $rows[26] ."</td>";
		echo "<td align='right' valign='top' >". number_format($rows[28], $InventoryRMaskqty) ."</td>";
	}
	
	if ($showbarcode2 == 1 ) {
		echo "<td align='left' valign='top' >". $rows[31] ."</td>";
	}
	
	if ($existqty == 0 ) {
		if ($prtqty == 1) {
			echo "<td align='right' valign='top' >". number_format($rows[13], $InventoryRMaskqty) ."</td>";
			echo "<td align='right' valign='top' >". number_format($rows[14], $InventoryRMaskqty) ."</td>";
			echo "<td align='right' valign='top' >". number_format($rows[15], $InventoryRMaskqty) ."</td>";
			echo "<td align='right' valign='top' >". number_format($rows[16], $InventoryRMaskqty) ."</td>";
		
			if ($showunit2qty==1) {
				echo "<td align='right' valign='top' >". $rows[29] ."</td>";
				echo "<td align='right' valign='top' >". number_format($rows[30], $InventoryRMaskqty) ."</td>";
			}
			
			if ($booking==1) {
				echo "<td align='right' valign='top' >". number_format($rows[17], $InventoryRMaskqty) ."</td>";
				echo "<td align='right' valign='top' >". number_format(($rows[16]-$rows[17]), $InventoryRMaskqty) ."</td>";
			}
		}	
		
		if ($abvmax == 1)
			echo "<td align='right' valign='top' >". number_format($rows[10], $InventoryRMaskqty) ."</td>";
		if ($blwmin == 1)
			echo "<td align='right' valign='top' >". number_format($rows[11], $InventoryRMaskqty) ."</td>";  
		
		if ($prtprices[1] == 1 || $prtprices[2] == 1 || $prtprices[3] == 1 || $prtprices[4] == 1 || $prtprices[5] == 1 || $prtcost == 1) 
			echo "<td align='center' valign='top' >". $rows[18] ."</td>";

		if ($prtcost == 1 && $fi_showcostprice == 1)	{
			echo "<td align='right'  valign='top' >". number_format($rows[19], $DecimalBase) ."</td>";
			echo "<td align='right'  valign='top' >". number_format($rows[20], $DecimalBase) ."</td>";
			echo "<td align='right'  valign='top' >". number_format($rows[21], $DecimalBase) ."</td>";
			echo "<td align='right'  valign='top' >". number_format($rows[22], $DecimalBase) ."</td>";
		}	
		
		if ($prtlpprice == 1 && $fi_showcostprice == 1)	{
			echo "<td align='right'  valign='top' >". number_format($rows[36], $DecimalBase) ."</td>";
		}	
				
		if ($prtprices[1] == 1 && $priceaccess[1] == 1)
			echo "<td align='right'  valign='top' >". number_format($rows[23], $DecimalBase) ."</td>";
		if ($prtprices[2] == 1 && $priceaccess[2] == 1)
			echo "<td align='right'  valign='top' >". number_format($rows[32], $DecimalBase) ."</td>";
		if ($prtprices[3] == 1 && $priceaccess[3] == 1)
			echo "<td align='right'  valign='top' >". number_format($rows[33], $DecimalBase) ."</td>";	
		if ($prtprices[4] == 1 && $priceaccess[4] == 1)
			echo "<td align='right'  valign='top' >". number_format($rows[34], $DecimalBase) ."</td>";
		if ($prtprices[5] == 1 && $priceaccess[5] == 1)
			echo "<td align='right'  valign='top' >". number_format($rows[35], $DecimalBase) ."</td>";
			
	} else {
	   echo "<td align='right' valign='top' >". number_format($rows[16], $InventoryRMaskqty) ."</td>";
	   //nabil 2015-12-29
	    if ($prtcost == 1 && $fi_showcostprice == 1)	{
			echo "<td align='right'  valign='top' >". number_format($rows[19], $DecimalBase) ."</td>";
			echo "<td align='right'  valign='top' >". number_format($rows[22], $DecimalBase) ."</td>";
		}
	   if ($showunit2qty==1) {
			echo "<td align='right' valign='top' >". $rows[29] ."</td>";
			echo "<td align='right' valign='top' >". number_format($rows[30], $InventoryRMaskqty) ."</td>";
		}
			
	   if ($booking==1) {
			echo "<td align='right' valign='top' >". number_format($rows[17], $InventoryRMaskqty) ."</td>";
			echo "<td align='right' valign='top' >". number_format(($rows[16]-$rows[17]), $InventoryRMaskqty) ."</td>";
		}
	   
	}
	
	echo "<td align='center' valign='top' >". $rows[38] ."</td>";
	echo "</tr>";
	echo "</table></td></tr>"; 
	
	//If By Serial Option Selected And ItemWitheSerial True
	if ($byserial == 1 && $rows[12]) {
		$sub_query = " Select Distinct Purchasesserialno.SerialNo_Code ".
					 " From Purchasesserialno ".
					 " left join purchasesdt on purchasesdt.purchasedt_id = Purchasesserialno.purchasedt_id
					   left join salesdt on salesdt.saledt_id = Purchasesserialno.purchasedt_id
					   left join transferdt on transferdt.transferdt_id = Purchasesserialno.purchasedt_id
					   left join adjustmentdt on adjustmentdt.adjustmentdt_id = Purchasesserialno.purchasedt_id
						left join production on production.production_id = Purchasesserialno.purchasedt_id
						left join deliverydt on deliverydt.deliverydt_id = Purchasesserialno.purchasedt_id ".
					 " Where Purchasesserialno.Item_Code = '".$rows[6]."' ".
					 " And Purchasesserialno.Journal_Type in ('PI','DR','SR','TR','AI','PD') ".
					 " And ifNull(SerialNo_Used,0) = 0  ";
					 //" And (RelatedSerial_Id Is Null or RelatedSerial_Id = '') ".
					 //" And Not Exists ( Select 1 From Purchasesserialno As PSerNo ".
					 //"                  Where PSerNo.RelatedSerial_Id = Purchasesserialno.Serial_ID ".
					 //"                  And PSerNo.Journal_Type in ('PR','DI','SI','TR','AR','PD') ".
					 //"                 ) ";
		$sub_query = $sub_query." and ( ((date_format(purchase_date, '%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
								and date_format(purchase_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d')) and purchasesdt.journal_type='PI')
						or ((date_format(sale_date,'%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
							and date_format(sale_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d')) and salesdt.journal_type='SR')
						or (date_format(transfer_date, '%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
							and date_format(transfer_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d'))
						or ((date_format(adjustment_date, '%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
								and date_format(adjustment_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d')) and adjustmentdt.journal_type='AI')
						or (date_format(production_date, '%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
							and date_format(production_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d'))
						or ((date_format(delivery_date, '%y-%m-%d') >= date_format($fromdate,'%y-%m-%d')
							and date_format(delivery_date, '%y-%m-%d')<= date_format($todate,'%y-%m-%d')) and deliverydt.journal_type='DR')) ";
		if ($SelWarehouse == 1)			 
			$sub_query = $sub_query." And Purchasesserialno.Warehouse_Code = '".$rows[8]."' ";
		else
			$sub_query = $sub_query." And ifNull(Purchasesserialno.Warehouse_Code,'-1') between ifNull(". $fromwarehouse .",ifNull(Purchasesserialno.Warehouse_Code,'-1')) and ifNull(". $towarehouse.",ifNull(Purchasesserialno.Warehouse_Code,'-1')) ";
		//echo $sub_query;
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$subnum=mysql_num_rows($sub_result);
			
		if ($subnum != 0)
		{
			$SerialCode='';
			while($sub_row=mysql_fetch_array($sub_result)){
				$SerialCode = $SerialCode.", ".$sub_row[0];
			}
				
			$SerialCode = substr($SerialCode,2);
			echo "<tr><td align='left' valign='top' class='sr'>Serial No :";
			echo $SerialCode;
			echo "</td></tr>";
		}
	
	}
	
	
	$ArrayTotalByReport['QtyPrev']      = $ArrayTotalByReport['QtyPrev']      + $rows[13];
	$ArrayTotalByReport['QtyIn']        = $ArrayTotalByReport['QtyIn']     	  + $rows[14];
	$ArrayTotalByReport['QtyOut']     	= $ArrayTotalByReport['QtyOut']       + $rows[15];
	$ArrayTotalByReport['QtyExist']     = $ArrayTotalByReport['QtyExist']     + $rows[16];
	$ArrayTotalByReport['QtyUnit2']     = $ArrayTotalByReport['QtyUnit2']     + $rows[30];
	$ArrayTotalByReport['QtyBooking']   = $ArrayTotalByReport['QtyBooking']   + $rows[17];
	$ArrayTotalByReport['QtyRemaining']	= $ArrayTotalByReport['QtyRemaining'] + ($rows[16]-$rows[17]);
	$ArrayTotalByReport['ValIn']  	    = $ArrayTotalByReport['ValIn'] 		  + $rows[20];
	$ArrayTotalByReport['ValOut']   	= $ArrayTotalByReport['ValOut'] 	  + $rows[21];
	$ArrayTotalByReport['TotalVal']   	= $ArrayTotalByReport['TotalVal'] 	  + $rows[22];
	$ArrayTotalByReport['TotalWeight']  = $ArrayTotalByReport['TotalWeight']  + $rows[28];
	
	$ArrayTotalByGroup1['QtyPrev']      = $ArrayTotalByGroup1['QtyPrev']      + $rows[13];
	$ArrayTotalByGroup1['QtyIn']        = $ArrayTotalByGroup1['QtyIn']     	  + $rows[14];
	$ArrayTotalByGroup1['QtyOut']     	= $ArrayTotalByGroup1['QtyOut']       + $rows[15];
	$ArrayTotalByGroup1['QtyExist']     = $ArrayTotalByGroup1['QtyExist']     + $rows[16];
	$ArrayTotalByGroup1['QtyUnit2']     = $ArrayTotalByGroup1['QtyUnit2']     + $rows[30];
	$ArrayTotalByGroup1['QtyBooking']   = $ArrayTotalByGroup1['QtyBooking']   + $rows[17];
	$ArrayTotalByGroup1['QtyRemaining']	= $ArrayTotalByGroup1['QtyRemaining'] + ($rows[16]-$rows[17]);
	$ArrayTotalByGroup1['ValIn']  	    = $ArrayTotalByGroup1['ValIn'] 		  + $rows[20];
	$ArrayTotalByGroup1['ValOut']   	= $ArrayTotalByGroup1['ValOut'] 	  + $rows[21];
	$ArrayTotalByGroup1['TotalVal']   	= $ArrayTotalByGroup1['TotalVal'] 	  + $rows[22];
	$ArrayTotalByGroup1['TotalWeight']  = $ArrayTotalByGroup1['TotalWeight']  + $rows[28];
	
	$ArrayTotalByGroup2['QtyPrev']      = $ArrayTotalByGroup2['QtyPrev']      + $rows[13];
	$ArrayTotalByGroup2['QtyIn']        = $ArrayTotalByGroup2['QtyIn']     	  + $rows[14];
	$ArrayTotalByGroup2['QtyOut']     	= $ArrayTotalByGroup2['QtyOut']       + $rows[15];
	$ArrayTotalByGroup2['QtyExist']     = $ArrayTotalByGroup2['QtyExist']     + $rows[16];
	$ArrayTotalByGroup2['QtyUnit2']     = $ArrayTotalByGroup2['QtyUnit2']     + $rows[30];
	$ArrayTotalByGroup2['QtyBooking']   = $ArrayTotalByGroup2['QtyBooking']   + $rows[17];
	$ArrayTotalByGroup2['QtyRemaining']	= $ArrayTotalByGroup2['QtyRemaining'] + ($rows[16]-$rows[17]);
	$ArrayTotalByGroup2['ValIn']  	    = $ArrayTotalByGroup2['ValIn'] 		  + $rows[20];
	$ArrayTotalByGroup2['ValOut']   	= $ArrayTotalByGroup2['ValOut'] 	  + $rows[21];
	$ArrayTotalByGroup2['TotalVal']   	= $ArrayTotalByGroup2['TotalVal'] 	  + $rows[22];
	$ArrayTotalByGroup2['TotalWeight']  = $ArrayTotalByGroup2['TotalWeight']  + $rows[28];
	
	$ArrayTotalByGroup3['QtyPrev']      = $ArrayTotalByGroup3['QtyPrev']      + $rows[13];
	$ArrayTotalByGroup3['QtyIn']        = $ArrayTotalByGroup3['QtyIn']     	  + $rows[14];
	$ArrayTotalByGroup3['QtyOut']     	= $ArrayTotalByGroup3['QtyOut']       + $rows[15];
	$ArrayTotalByGroup3['QtyExist']     = $ArrayTotalByGroup3['QtyExist']     + $rows[16];
	$ArrayTotalByGroup3['QtyUnit2']     = $ArrayTotalByGroup3['QtyUnit2']     + $rows[30];
	$ArrayTotalByGroup3['QtyBooking']   = $ArrayTotalByGroup3['QtyBooking']   + $rows[17];
	$ArrayTotalByGroup3['QtyRemaining']	= $ArrayTotalByGroup3['QtyRemaining'] + ($rows[16]-$rows[17]);
	$ArrayTotalByGroup3['ValIn']  	    = $ArrayTotalByGroup3['ValIn'] 		  + $rows[20];
	$ArrayTotalByGroup3['ValOut']   	= $ArrayTotalByGroup3['ValOut'] 	  + $rows[21];
	$ArrayTotalByGroup3['TotalVal']   	= $ArrayTotalByGroup3['TotalVal'] 	  + $rows[22];
	$ArrayTotalByGroup3['TotalWeight']  = $ArrayTotalByGroup3['TotalWeight']  + $rows[28];
	
	$col+=1;
}

//Group By Options Level 3 Totals
if ( ($groupby3 != 1 && $showdetail == 1) && (($MainGroup3 != $rows[4] && $MainGroup3 != '') || ($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
		
	echo "<tr><td><hr width='$tbwidth' color='black' size='1'></td></tr>";
				
	$StyleClass  = 'grouplevel3total';
	$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
	DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup3, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);
					
}
		
//Group By Options Level 2 Totals
if ( ($groupby2 != '' && ($showdetail == 1 || $groupby3 != 1)) && (($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
	  
	echo "<tr><td><hr width='$tbwidth' color='black' size='1'></td></tr>";

	$StyleClass  = 'grouplevel2total';
	$TotalsLabel = 'Total 2 - '.$groupby2name.' : '.$groupby2code;
	DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup2, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);
		
}
		
//Group By Options Level 1 Totals
if ( ($groupby1 != '' && ($showdetail == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 != $rows[0] && $MainGroup1 != '') ){
	  
	echo "<tr><td><hr width='$tbwidth' color='black' size='1'></td></tr>";
				
	$StyleClass  = 'grouplevel1total';
	$TotalsLabel = 'Total 1 - '.$groupby1name.' : '.$groupby1code;
	DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByGroup1, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);

}
	
// Display Totals By Report			
echo "<tr><td><hr width='$tbwidth' color='black' size='1'></td></tr>";

$StyleClass  = 'summary';
$TotalsLabel = 'Totals';
DisplayTotals($showdetail, $prtqty, $existqty, $booking, $abvmax, $blwmin, $prtprices, $priceaccess, $fi_showcostprice, $prtcost, $prtlpprice, $ArrayTotalByReport, $DecimalBase, $InventoryRMaskqty, $TotalsLabel, $StyleClass, $showweight, $showunit2qty, $showbarcode2,$descWidth,$tbwidth);


//echo "<th >V.A.T</th>";
echo "</table>";

function DisplayTotals($PShowDetail, $PPrtQty, $PPrtExistQty, $PPrtBooking, $PPrtAbvMax, $PPrtBlwMin, $PPrtPrice, $PPriceAccess, $FI_ShowCostPrice, $PPrtCost, $PPrtLPPrice, $PArrayTotal, $PDecimalBase, $PInventoryRMaskqty, $PTotalsLabel, $PStyleClass, $PShowWeight, $PShowUnit2Qty, $PShowBarCode2, $descWidth,$tbwidth) {
	echo "<tr><td>";
	
	echo "<table  border='0' width='$tbwidth' align='left' class='totals'>
		  <col width=120>";
	
	if ($PPrtExistQty == 0 && ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1))	  
		echo "<col width=200>";
	else
		echo "<col width=$descWidth>";

	echo "<col width=50>";
	echo "<col width=35>";
	
	if ($PShowWeight == 1) {
		echo "<col width=60>";
		echo "<col width=80>";
	}
	
	if ($PShowBarCode2 == 1) {
		echo "<col width=100>";
	}	

	if ($PPrtExistQty == 0 ) {

		if ($PPrtQty == 1) {
			echo" <col width=90>
				  <col width=120>
				  <col width=120>
				  <col width=120>";
				  
			if ($PShowUnit2Qty==1) {
				echo "<col width=50>
					  <col width=90>";
			}
			
			if ($PPrtBooking==1) {
				echo "<col width=90>
					  <col width=90>";
			}
		}
		

		if ($PPrtAbvMax == 1)
			echo "<col width=60>";
		if ($PPrtBlwMin == 1)  
			echo "<col width=60>";

		if ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1) echo "<col width=40>";
				
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
			echo "<col width=130>";
			echo "<col width=130>";
			echo "<col width=130>";
		}	
		
		if ($PPrtLPPrice == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
		}
		
		if ($PPrtPrice[1] == 1 && $PPriceAccess[1] == 1)	echo "<col width=100>";
		if ($PPrtPrice[2] == 1 && $PPriceAccess[2] == 1)	echo "<col width=100>";
		if ($PPrtPrice[3] == 1 && $PPriceAccess[3] == 1)	echo "<col width=100>";
		if ($PPrtPrice[4] == 1 && $PPriceAccess[4] == 1)	echo "<col width=100>";
		if ($PPrtPrice[5] == 1 && $PPriceAccess[5] == 1)	echo "<col width=100>";
	
	} else {
		echo" <col width=90>";
		//nabil 2015-12-29
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<col width=90>";
			echo "<col width=90>";
			}
			
		if ($PShowUnit2Qty==1) {
			echo "<col width=50>
				  <col width=90>";
		}

		if ($PPrtBooking==1) {
			echo "<col width=90>
				  <col width=90>";
		}

	}
	
	echo "<tr class='".$PStyleClass."'>"; 
	echo "	<td>&nbsp;</td>";
	echo "  <td align='left' colspan='3'><b>".$PTotalsLabel."</b></td>";
	
	if ($PShowWeight == 1) {
		echo "   <td align='right'> &nbsp; </td>"; 
		echo "   <td align='right' >".number_format($PArrayTotal['TotalWeight'] , $PInventoryRMaskqty)." </td>"; 
	}
	
	if ($PShowBarCode2 == 1) {
		echo "<td>&nbsp;</td>";
	} 
		
    if ($PPrtExistQty == 0 ) {

		if ($PPrtQty == 1) {
			echo "   <td align='right' >".number_format($PArrayTotal['QtyPrev'] , $PInventoryRMaskqty)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['QtyIn']   , $PInventoryRMaskqty)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['QtyOut']  , $PInventoryRMaskqty)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['QtyExist'], $PInventoryRMaskqty)." </td>"; 
			if ($PShowUnit2Qty==1) {
				echo "   <td align='right' >&nbsp; </td>"; 
				echo "   <td align='right' >".number_format($PArrayTotal['QtyUnit2'], $PInventoryRMaskqty)." </td>"; 
			}
			if ($PPrtBooking==1) {
				echo "   <td align='right' >".number_format($PArrayTotal['QtyBooking'],   $PInventoryRMaskqty)." </td>"; 
				echo "   <td align='right' >".number_format($PArrayTotal['QtyRemaining'], $PInventoryRMaskqty)." </td>"; 
			}
		}	
		
		if ($PPrtAbvMax == 1)
			echo "<td align='right'>&nbsp;</td>"; 
		if ($PPrtBlwMin == 1)  
			echo "<td align='right'>&nbsp;</td>"; 
			
		
		if ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1) echo "<td align='right'>&nbsp;</td>"; 

		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "   <td align='right'> &nbsp; </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['ValIn']    , $PDecimalBase)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['ValOut']   , $PDecimalBase)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['TotalVal'] , $PDecimalBase)." </td>"; 
		}	
		
		if ($PPrtLPPrice == 1 && $FI_ShowCostPrice == 1)	{
			echo "   <td align='right'> &nbsp; </td>"; 
		}
				
		if ($PPrtPrice[1] == 1 && $PPriceAccess[1] == 1)	echo "<td align='right'>&nbsp; </td>";
		if ($PPrtPrice[2] == 1 && $PPriceAccess[2] == 1)	echo "<td align='right'>&nbsp; </td>";
		if ($PPrtPrice[3] == 1 && $PPriceAccess[3] == 1)	echo "<td align='right'>&nbsp; </td>";
		if ($PPrtPrice[4] == 1 && $PPriceAccess[4] == 1)	echo "<td align='right'>&nbsp; </td>";
		if ($PPrtPrice[5] == 1 && $PPriceAccess[5] == 1)	echo "<td align='right'>&nbsp; </td>";
			
	} else  {
	    echo "   <td align='right' >".number_format($PArrayTotal['QtyExist'], $PInventoryRMaskqty)." </td>"; 
		//nabil 2015-12-29
		
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<td >&nbsp;</td>";
			echo "<td align='right'>".number_format($PArrayTotal['TotalVal'], $PInventoryRMaskqty)."</td>";
		}
		
		if ($PShowUnit2Qty==1) {
			echo "   <td align='right' >&nbsp; </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['QtyUnit2'], $PInventoryRMaskqty)." </td>"; 
		}
			
		if ($PPrtBooking==1) {
			echo "   <td align='right' >".number_format($PArrayTotal['QtyBooking'],   $PInventoryRMaskqty)." </td>"; 
			echo "   <td align='right' >".number_format($PArrayTotal['QtyRemaining'], $PInventoryRMaskqty)." </td>"; 
		}
	}
		
	
	echo "</tr>";
	echo "</table>";
	echo "</td></tr>";
	
}

function CreateTableHeader($PShowDetail, $PPrtQty, $PPrtExistQty, $PPrtBooking, $PPrtAbvMax, $PPrtBlwMin, $PPrtPrice, $PPriceAccess, $FI_ShowCostPrice, $PPrtCost, $PPrtLPPrice, $PShowWeight, $PShowUnit2Qty, $PShowBarCode2,$Module_Heatno,$vShowHeatno,$descWidth,$tbwidth, $edatechk) {
	echo "<table  border='0' width='$tbwidth' align='left' class='master' style='table-layout:fixed' cellspacing=0>
		  ";
		if($edatechk ==1) echo "<col width=120>";
		  echo "<col width=120>";
	if ($PPrtExistQty == 0 && ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1))	  
		echo "<col width=200>";
	else
		echo "<col width=$descWidth>";

	echo "<col width=50>";
	echo "<col width=35>";
	if($Module_Heatno==1 and $vShowHeatno==1)	
	echo "<col width=35>";
	if ($PShowWeight == 1) {
		echo "<col width=60>";
		echo "<col width=80>";
	}
	
	if ($PShowBarCode2 == 1) {
		echo "<col width=100>";
	}

	if ($PPrtExistQty == 0 ) {

		if ($PPrtQty == 1) {
			echo" <col width=90>
				  <col width=120>
				  <col width=120>
				  <col width=120>";
				  
			if ($PShowUnit2Qty==1) {
				echo "<col width=50>
					  <col width=90>";
			}
			
			if ($PPrtBooking==1) {
				echo "<col width=90>
					  <col width=90>";
			}
		}
		

		if ($PPrtAbvMax == 1)
			echo "<col width=60>";
		if ($PPrtBlwMin == 1)  
			echo "<col width=60>";

		if ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1) echo "<col width=40>";
				
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
			echo "<col width=130>";
			echo "<col width=130>";
			echo "<col width=130>";
		}

		if ($PPrtLPPrice == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
		}	
		
		if ($PPrtPrice[1] == 1 && $PPriceAccess[1] == 1)	echo "<col width=100>";
		if ($PPrtPrice[2] == 1 && $PPriceAccess[2] == 1)	echo "<col width=100>";
		if ($PPrtPrice[3] == 1 && $PPriceAccess[3] == 1)	echo "<col width=100>";
		if ($PPrtPrice[4] == 1 && $PPriceAccess[4] == 1)	echo "<col width=100>";
		if ($PPrtPrice[5] == 1 && $PPriceAccess[5] == 1)	echo "<col width=100>";
	
	} else {
		echo" <col width=90>";
		//nabil 2015-12-29
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<col width=90>";
			echo "<col width=90>";
		}
		if ($PShowUnit2Qty==1) {
			echo "<col width=50>
				  <col width=90>";
		}

		if ($PPrtBooking==1) {
			echo "<col width=90>
				  <col width=90>";
		}

	}
	echo" <col width=100>";
	echo "<tr>";

	if ($PShowDetail == 0) {
		echo"<th >Grouping</th>
			 <th >Description</th>
			 <th >UM</th>
			 <th >Unit</th>";

			 

		
	} else {
		if($edatechk == 1) echo"<th >Expire Date</th>";
		echo"<th >Item Code</th>
			 <th >Description</th>
			 <th >UM</th>
			 <th >Unit</th>";
	}	

if($Module_Heatno==1 and $vShowHeatno==1)	
	echo"<th >HeatNo</th>";
	
	if ($PShowWeight == 1) {
		echo" <th >Weight</th>
			  <th >Total Weight</th>";
	}

	if ($PShowBarCode2 == 1) {
		echo" <th >Barcode2</th>";
	}
	
	if ($PPrtExistQty == 0 ) {		
		if ($PPrtQty == 1) {
			echo"<th >Prev. Qty </th>
				 <th >Qty. In</th>
				 <th >Qty. Out</th>
				 <th >Existing</th>";
			
			if ($PShowUnit2Qty==1) {
				 echo" <th >Unit2</th>
					   <th >Unit2 Qty</th>";
			}
			
			if ($PPrtBooking==1) {
				 echo" <th >Booking</th>
					   <th >Remaining</th>";
			}
		}		

		if ($PPrtAbvMax == 1)
			echo "<th>Max Qty</th>";
		if ($PPrtBlwMin == 1)  
			echo "<th>Min Qty</th>";
		

		if ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1) echo "<th >Cur.</th>";

		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<th >Mean Cost</th>";
			echo "<th >Value In</th>";
			echo "<th >Value Out</th>";
			echo "<th >Value</th>";
			//echo "<th >Taxable</th>";
		}
			
		if ($PPrtLPPrice == 1 && $FI_ShowCostPrice == 1)	{
			echo "<th >Last Pur.Price</th>";
		}		
			
		if ($PPrtPrice[1] == 1 && $PPriceAccess[1] == 1)	echo "<th >Sell.Price I</th>";
		if ($PPrtPrice[2] == 1 && $PPriceAccess[2] == 1)	echo "<th >Sell.Price II</th>";
		if ($PPrtPrice[3] == 1 && $PPriceAccess[3] == 1)	echo "<th >Sell.Price III</th>";
		if ($PPrtPrice[4] == 1 && $PPriceAccess[4] == 1)	echo "<th >Sell.Price IV</th>";
		if ($PPrtPrice[5] == 1 && $PPriceAccess[5] == 1)	echo "<th >Sell.Price V</th>";
		//echo "<th >V.A.T</th>";
			
	} else {
		echo"<th >Existing</th>";
		//nabil 2015-12-29
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<th >Mean Cost</th>";
			echo "<th >Value</th>";
		}
		if ($PShowUnit2Qty==1) {
			 echo" <th >Unit2</th>
				   <th >Unit2 Qty</th>";
		}
		
		if ($PPrtBooking==1) {
			 echo" <th >Booking</th>
				   <th >Remaining</th>";	
		}
		
	}
	echo "<th >V.A.T</th>";
	echo "</tr>";
	echo "</table>";

}

function CreateTableStructure($PShowDetail, $PPrtQty, $PPrtExistQty, $PPrtBooking, $PPrtAbvMax, $PPrtBlwMin, $PPrtPrice, $PPriceAccess, $FI_ShowCostPrice, $PPrtCost, $PPrtLPPrice, $PShowWeight, $PShowUnit2Qty, $PShowBarCode2, $Module_Heatno, $vShowHeatno,$descWidth,$tbwidth, $edatechk) {
	echo "<table  border='0' width='$tbwidth' align='left' class='master' >";
	if($edatechk ==1) echo "<col width=120>";
	echo "<col width=120>";
	if ($PPrtExistQty == 0 && ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1))	  
		echo "<col width=200>";
	else
		echo "<col width=$descWidth>";

	echo "<col width=50>";	
	echo "<col width=35>";
	
if($Module_Heatno==1 and $vShowHeatno==1)	
	echo "<col width=35>";
	
	if ($PShowWeight == 1) {
		echo "<col width=60>";
		echo "<col width=80>";
	}
	
	if ($PShowBarCode2 == 1) {
		echo "<col width=100>";
	}

	if ($PPrtExistQty == 0 ) {

		if ($PPrtQty == 1) {
			echo" <col width=90>
				  <col width=120>
				  <col width=120>
				  <col width=120>";
				  
			if ($PShowUnit2Qty==1) {
				echo "<col width=50>
					  <col width=90>";
			}
			
			if ($PPrtBooking==1) {
				echo "<col width=90>
					  <col width=90>";
			}
		}
		

		if ($PPrtAbvMax == 1)
			echo "<col width=60>";
		if ($PPrtBlwMin == 1)  
			echo "<col width=60>";

		if ($PPrtPrice[1] == 1 || $PPrtPrice[2] == 1 || $PPrtPrice[3] == 1 || $PPrtPrice[4] == 1 || $PPrtPrice[5] == 1 || $PPrtCost == 1) echo "<col width=40>";
				
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
			echo "<col width=130>";
			echo "<col width=130>";
			echo "<col width=130>";
		}
		
		if ($PPrtLPPrice == 1 && $FI_ShowCostPrice == 1) {
			echo "<col width=120>";
		}
		
		if ($PPrtPrice[1] == 1 && $PPriceAccess[1] == 1)	echo "<col width=100>";
		if ($PPrtPrice[2] == 1 && $PPriceAccess[2] == 1)	echo "<col width=100>";
		if ($PPrtPrice[3] == 1 && $PPriceAccess[3] == 1)	echo "<col width=100>";
		if ($PPrtPrice[4] == 1 && $PPriceAccess[4] == 1)	echo "<col width=100>";
		if ($PPrtPrice[5] == 1 && $PPriceAccess[5] == 1)	echo "<col width=100>";
	
	} else {
		echo" <col width=90>";
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)	{
			echo "<col width=90>";
			echo "<col width=90>";
		}
		if ($PShowUnit2Qty==1) {
			echo "<col width=50>
				  <col width=90>";
		}

		if ($PPrtBooking==1) {
			echo "<col width=90>
				  <col width=90>";
		}

	}


}

function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p') ";
  $result=mysql_query($string,$connection) or die(mysql_error());
  $now=mysql_fetch_row($result);

  return $now;
}

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}



if ($printaccess==1)
print <<< HERE

<script language=javascript>
if (typeof(window.print) != 'undefined')
{
   // window.print();
}
</script>
</BODY>
</HTML>
HERE;

?>