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

session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}

print <<< HERE
<HTML>
<HEAD>
<TITLE> Inventory Comparison Report </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">

<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 tr.group { font-size: 14px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }					 
				 
table.master td.sr  { font-size: 10px; 
					  font-style: italic; 
                      font-family:Times-New-Roman;
                    }	
					
table.group td { font-size: 12px; 
                 font-weight: bold;
				 font-style: italic;
                 font-family:Times-New-Roman;
               }				 
				 
table.detail td { font-size: 10px; 
                  font-family:Times-New-Roman;
                 }	
				 
table.headerdetail td { font-size: 10px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }				 
table.totals td { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }					  
				 

</style>




</HEAD>

HERE;



include("config.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");

$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,FI_ItemSelling6 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, 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);
}

$querysalessetup="select SalesTTC from salessetup";
$resultsalessetup=mysql_query($querysalessetup,$connection) or die(mysql_error());
while($rowssalessetup=mysql_fetch_array($resultsalessetup)){
  extract($rowssalessetup);
}

$queryPurchasesetup="select PurchaseTTC from PurchaseSetup";
$resultPurchasesetup=mysql_query($queryPurchasesetup,$connection) or die(mysql_error());
while($rowsPurchasesetup=mysql_fetch_array($resultPurchasesetup)){
  extract($rowsPurchasesetup);
}

$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_Delivery,0) As Module_Delivery, ifNull(Module_Grn,0) As Module_Grn 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]);

$ReportTitle = '';
if ($transtype == 'PI') 	  $ReportTitle = 'Purchase Comparison Report';
else if ($transtype == 'PR')  $ReportTitle = 'Return Purchase Comparison Report';
else if ($transtype == 'PIR') $ReportTitle = 'Purchase & Return Purchase Comparison Report';
else if ($transtype == 'SI')  $ReportTitle = 'Sales Comparison Report';
else if ($transtype == 'SR')  $ReportTitle = 'Return Sales Comparison Report';
else if ($transtype == 'SIR') $ReportTitle = 'Sales & Return Sales Comparison Report';
else if ($transtype == 'AI')  $ReportTitle = 'Adjustment IN Comparison Report';
else if ($transtype == 'AR')  $ReportTitle = 'Adjustment OUT Comparison Report';
else if ($transtype == 'PD')  $ReportTitle = 'Production IN Comparison Report';
else if ($transtype == 'PDT') $ReportTitle = 'Production OUT Comparison Report';
else if ($transtype == 'TRT') $ReportTitle = 'Transfer IN Comparison Report';
else if ($transtype == 'TR')  $ReportTitle = 'Transfer OUT Comparison Report';

print <<< HERE
<table width="100%" border="0" align="center">
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>$ReportTitle</b></font></td>
  <td width='10%'><font size=1><b> Printed Date: </b> <br><b>Time: </b>
  <td width='10%'><font size=1>
HERE;


echo $printdate[2]."/".$printdate[1]."/".$printdate[0];
//echo DATE("d"."/"."m"."/"."Y");
echo "<br>".$dt[1]." ".$dt[2];

if ($curr == ''){
   $curr='';  
   $displaycur = '';
}   
else {
   $displaycur = $curr;
   $curr="'".$curr."'";
}  

//If Option Daily, and Days differnce between Start and End dates > 30
//Then Set the EndDate equal to StartDate plus 30 days.

if ($period == 1 ) {
	$Days = dateDiff(explodeword($fromdate), explodeword($todate))+1; 
	if ($Days == 30) $todate = addDays(explodeword($fromdate), 29, 'd/m/Y'); 
	if ($Days >= 31) $todate = addDays(explodeword($fromdate), 30, 'd/m/Y');
	
}	


$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($displaycur != '')    $SelectedOptions .= "-> Currency: ". $displaycur ."<br>";	
if ($fromclient != '')    $SelectedOptions .= "-> Client From: ". $fromclient . "  To: ". $toclient ."<br>";
if ($fromsupplier != '')  $SelectedOptions .= "-> Supplier From: ". $fromsupplier . "  To: ". $tosupplier ."<br>";
if ($fromsalesman != '')  $SelectedOptions .= "-> Salesman From: ". $fromsalesman . "  To: ". $tosalesman ."<br>";
if ($fromitem != '')      $SelectedOptions .= "-> Item From: ". $fromitem . "  To: ". $toitem ."<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 ($frombustype != '')   $SelectedOptions .= "-> Client Business Type From: ". $frombustype . "  To: ". $tobustype ."<br>";


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

$vMonthFrom = intval(substr($fromdate, 5, 2));
$vMonthTo   = intval(substr($todate, 5, 2));
$vYearFrom  = substr($fromdate, 0, 4);
$vYearTo    = substr($todate, 0, 4);    

$fromitem      = GetSQLValueString($fromitem, 'text');
$toitem        = GetSQLValueString($toitem, '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');   
$fromclient    = GetSQLValueString($fromclient, 'text');
$toclient      = GetSQLValueString($toclient, 'text');
$fromsupplier  = GetSQLValueString($fromsupplier, 'text');
$tosupplier    = GetSQLValueString($tosupplier, 'text');
$fromsalesman  = GetSQLValueString($fromsalesman, 'text');
$tosalesman    = GetSQLValueString($tosalesman, 'text'); 
$frombustype   = GetSQLValueString($frombustype, 'text');
$tobustype     = GetSQLValueString($tobustype, 'text'); 

  
if (empty($transtype)) 	  $transtype = 'SI';	
if (empty($period)) 	  $period = 2;	
if (empty($showdetail))   $showdetail = 0;
if (empty($prtprice)) 	  $prtprice = 0;
if (empty($prtcost)) 	  $prtcost = 0;
if (empty($prtamt)) 	  $prtamt = 0;
if (empty($prtqty))	 	  $prtqty = 0;
if (empty($prtqtyexist))  $prtqtyexist = 0;
if (empty($prtqtySO))	  $prtqtySO = 0;
if (empty($prtqtyPO))	  $prtqtyPO = 0;
if (empty($prtavg))	 	  $prtavg = 0;
if (empty($prtshortage))  $prtshortage = 0;
if (empty($showallitems)) $showallitems = 0;
if (empty($prtgroup)) 	  $prtgroup = 0;
if (empty($prtsubgroup))  $prtsubgroup = 0;
if (empty($prtcategory))  $prtcategory = 0;
if (empty($prtcolor)) 	  $prtcolor = 0;
if (empty($prtsize))	  $prtsize = 0;
if (empty($prtcharges))	  $prtcharges = 0;
if(empty($promprint))     $promprint = 3;   


$MasterByLabel = '';
if ($groupby == 2 )       $MasterByLabel  = 'Group';
else if ($groupby == 3 )  $MasterByLabel  = 'SubGroup';
else if ($groupby == 4 )  $MasterByLabel  = 'Category';
else if ($groupby == 5 )  $MasterByLabel  = 'Warehouse';
else if ($groupby == 6 )  $MasterByLabel  = 'Project';
else if ($groupby == 7 )  $MasterByLabel  = 'CostCenter';
else if ($groupby == 8 )  $MasterByLabel  = 'Client';
else if ($groupby == 9 )  $MasterByLabel  = 'Supplier';
else if ($groupby == 10 ) $MasterByLabel  = 'Client Group';

print <<<HERE
</font></td>
</tr>
<tr>
   <td colspan='4' width='100%'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table>

<table class="params" width="100%" border="0" align="center" >
<tr>
  <td width="100%" valign='top'><b>$SelectedOptions</b></td>
</tr>
<tr height='5'><td><h5></td></tr>
</table>

HERE;

// tableeee
echo "<table width='100%' border='0' class='master' align='center' cellpadding='0' cellspacing='0'>";

//echo "  <tr><td colspan='3'>";

//Create Table Columns
CreateTableStructure($period, $vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $fromdate, $todate, $prtqtyexist, $prtqtySO, $prtqtyPO, $prtqty, $prtprice, $prtamt, $fi_showcostprice, $prtcost, $sellprices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $showdetail, $prtavg, $prtshortage, $prtgroup, $prtsubgroup, $prtcategory, $prtcolor, $prtsize, $prtcharges );		


if ($prtqty == 1 && $prtamt == 1 && ($period == 1 || $period == 2)) {

	echo"<tr>";

	$vCountColumns = 3;
	if ($prtgroup == 1)    $vCountColumns += 1;
	if ($prtsubgroup == 1) $vCountColumns += 1;
	if ($prtcategory == 1) $vCountColumns += 1;
	if ($prtcolor == 1)    $vCountColumns += 1;
	if ($prtsize == 1)	   $vCountColumns += 1;
	if ($prtqtyexist == 1) $vCountColumns += 1;
	if ($prtqtySO == 1)    $vCountColumns += 1;
	if ($prtqtyexist == 1 && $prtqtySO == 1)	$vCountColumns += 1;

	echo"	<th align='left' colspan=".$vCountColumns.">&nbsp;</th>";	
		
	if ($period == 1 ) {
		$dayscount = dateDiff($fromdate, $todate);
		for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
			if ($prtcharges == 1)
				echo" <th align='center' colspan='4'>".showDays($fromdate, $d)."</th> ";
			else	
				echo" <th align='center' colspan='2'>".showDays($fromdate, $d)."</th> ";	
		}
		$LastColLabel = showDays($fromdate, $d);
	}
	else if ($period == 2 ) {
		for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

			if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo - 1; }
			else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
			else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo - 1; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				if ($prtcharges == 1)
					echo" <th align='center' colspan='4'>".showMonthYear($m,$y)."</th> ";
				else
					echo" <th align='center' colspan='2'>".showMonthYear($m,$y)."</th> ";
			}
		}
		
		$LastColLabel = showMonthYear($m,($y-1));
	} 
	
	if ($prtavg == 1 && $prtcharges == 1)
		echo" <th align='center' colspan='4'>Average</th> ";
	else if ($prtavg == 1)
		echo" <th align='center' colspan='2'>Average</th> ";	
		
	if ($prtcharges == 1)	
		echo" <th align='center' colspan='4'>$LastColLabel</th> ";
	else	
		echo" <th align='center' colspan='2'>$LastColLabel</th> ";
	
	if ($prtshortage == 1 && $prtcharges == 1)
		echo" <th align='center' colspan='4'>Shortage</th> ";
	else if ($prtshortage == 1)
		echo" <th align='center' colspan='2'>Shortage</th> ";	
	
	echo"</tr>";

}

echo "<tr>";

$styleth = "border-left:1px solid black ; border-bottom:2px solid black";

if ($showdetail == 0) {
	echo"<th style='$styleth' >Grouping</th>
		 <th style='$styleth'>Description</th>
		 <th style='$styleth'>Unit</th>";
} else {
	echo"<th style='$styleth'>Item Code</th>
		 <th style='$styleth'>Description</th>
		 <th style='$styleth'>Unit</th>";
}		 

if ($prtgroup == 1)
	echo "<th style='$styleth'>Group Code</th>";	
if ($prtsubgroup == 1)
	echo "<th style='$styleth'>SubGroup Code</th>";	
if ($prtcategory == 1)
	echo "<th style='$styleth'>Category Code</th>";	
if ($prtcolor == 1)
	echo "<th style='$styleth'>Item Color</th>";	
if ($prtsize == 1)
	echo "<th style='$styleth'>Item Size</th>";		

if ($prtqtyexist == 1)
	echo "<th style='$styleth'>Qty Exist</th>";	
if ($prtqtySO == 1)
	echo "<th style='$styleth'>Qty SO Pending</th>";		 
if ($prtqtyexist == 1 && $prtqtySO == 1)	
	echo "<th style='$styleth'>Qty Remain</th>";
	
if ($period == 1 ) {
	$dayscount = dateDiff($fromdate, $todate);
	for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
		if ($prtqty == 1 && $prtamt == 1 && $prtcharges == 1) {
			echo "<th align='center' style='$styleth'>Quantity</th>";
			echo "<th align='center' style='$styleth'>Amount</th>";
			echo "<th align='center' style='$styleth'>Charges</th>";
			echo "<th align='center' style='$styleth'>SubTotal</th>";
		} else if ($prtqty == 1 && $prtamt == 1) {
			echo "<th align='center' style='$styleth'>Quantity</th>";
			echo "<th align='center' style='$styleth'>Amount</th>";	
		} else if ($prtqty == 1 || $prtamt == 1) {
			echo" <th align='center' style='$styleth'>".showDays($fromdate, $d)."</th> ";
		}	
	}
	
	$LastColLabel = showDays($fromdate, $d);
}	
else if ($period == 2 ) {
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo - 1; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo - 1; }
		else { $vMFrom = 1; $vMTo = 12; }
					
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
			if ($prtqty == 1 && $prtamt == 1 && $prtcharges == 1) {
				echo "<th align='center' style='$styleth'>Quantity</th>";
				echo "<th align='center' style='$styleth'>Amount</th>";
				echo "<th align='center' style='$styleth'>Charges</th>";
				echo "<th align='center' style='$styleth'>SubTotal</th>";
			} else if ($prtqty == 1 && $prtamt == 1) {
				echo "<th align='center' style='$styleth'>Quantity</th>";
				echo "<th align='center' style='$styleth'>Amount</th>";
			} else if ($prtqty == 1 || $prtamt == 1) {
				echo" <th align='center' style='$styleth'>".showMonthYear($m,$y)."</th> ";
			}	
		}
	}	
	
	$LastColLabel = showMonthYear($m,($y-1));
}
else if ($period == 3 ) {
	if ($prtqty == 1) echo "<th align='center' style='$styleth'>Quantity</th>";
	if ($prtamt == 1) echo "<th align='center' style='$styleth'>Amount</th>";
	if ($prtcharges == 1) {
		echo "<th align='center' style='$styleth'>Charges</th>";
		echo "<th align='center' style='$styleth'>SubTotal</th>";
	}
}

if ($period == 1 || $period == 2) {
	if ($prtqty == 1 && $prtamt == 1) {
		if ($prtavg == 1) {
			echo "<th align='center' style='$styleth'>Quantity</th>";
			echo "<th align='center' style='$styleth'>Amount</th>";
			if ($prtcharges == 1) {
				echo "<th align='center' style='$styleth'>Charges</th>";
				echo "<th align='center' style='$styleth'>SubTotal</th>";
			}	
		}
		
		echo "<th align='center' style='$styleth'>Quantity</th>";
		echo "<th align='center' style='$styleth'>Amount</th>";
		
		if ($prtcharges == 1) {
			echo "<th align='center' style='$styleth'>Charges</th>";
			echo "<th align='center' style='$styleth'>SubTotal</th>";
		}
		
		if ($prtshortage == 1) {
			echo "<th align='center' style='$styleth'>Quantity</th>";
			echo "<th align='center' style='$styleth'>Amount</th>";
			if ($prtcharges == 1) {
				echo "<th align='center' style='$styleth'>Charges</th>";
				echo "<th align='center' style='$styleth'>SubTotal</th>";
			}
		}	
	} else {
		if ($prtqty == 1) {
			if ($prtavg == 1)
				echo"<th style='$styleth' >Avg. Qty </th>";
				
			echo"<th style='$styleth'>$LastColLabel</th>";
			
			if ($prtshortage == 1)
				echo"<th style='$styleth'>Shortage</th>";
		}	
		else if ($prtamt == 1) {
			if ($prtavg == 1)
				echo"<th style='$styleth'>Avg. Amt </th>";
				
			echo"<th style='$styleth' >$LastColLabel</th>";
			
			if ($prtshortage == 1)
				echo"<th style='$styleth'>Shortage</th>";
		}
	}	
}


if ($prtqtyPO == 1)
	echo"<th style='$styleth'>Qty PO Pending</th>";
	
if ($showdetail == 1) {	
	if ($prtcost == 1 && $fi_showcostprice == 1)
		echo "<th style='$styleth'>Mean Cost</th>";	
		
	$priceoptions = explode(',', $sellprices);
	foreach($priceoptions as $price) {
		if ($price == 1)  	   $displayprice = 'I';
		else if ($price == 2)  $displayprice = 'II';
		else if ($price == 3)  $displayprice = 'III';
		else if ($price == 4)  $displayprice = 'IV';
		else if ($price == 5)  $displayprice = 'V';
		
		$priceaccess = 0;
		if (($price == 1 && $FI_ItemSelling1 == 1) || ($price == 2 && $FI_ItemSelling2 == 1) || 
			($price == 3 && $FI_ItemSelling3 == 1) || ($price == 4 && $FI_ItemSelling4 == 1) ||
			($price == 5 && $FI_ItemSelling5 == 1) ) $priceaccess = 1;

		if ($prtprice == 1 && $priceaccess == 1 && $price != 0)
			echo "<th style='$styleth'>Sell. Price $displayprice</th>";
	}	
}
	
echo"     </tr>";	
//echo"	</table></td></tr>";	
//echo"  <tr><td colspan='29'><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 = '';

$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, ".
				" QtyExist, QtySOPend, QtyRemain, QtyPOPend, CurrencyCode, MeanCostAmount, ItemSellingPrice1, ItemSellingPrice2, ".
				" ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize ";

if ($period == 1 ) {
	$dayscount = dateDiff($fromdate, $todate);
	
	for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
		$query = $query.", Sum(Qty".addDays($fromdate, $d).") AS Qty".addDays($fromdate, $d).
						", Sum(Amt".addDays($fromdate, $d).") + Sum(VatAmt".addDays($fromdate, 0).$y.") AS Amt".addDays($fromdate, $d).
						", Sum(Chg".addDays($fromdate, $d).") AS Chg".addDays($fromdate, $d).
						", Sum(SubTot".addDays($fromdate, $d).") AS SubTot".addDays($fromdate, $d);
						
	}
	
	$query = $query.", Sum(Qty".addDays($fromdate, $d).") AS Qty".addDays($fromdate, $d).
					", Sum(Amt".addDays($fromdate, $d).") + Sum(VatAmt".addDays($fromdate, 0).") AS Amt".addDays($fromdate, $d).
					", Sum(Chg".addDays($fromdate, $d).") AS Chg".addDays($fromdate, $d).
					", Sum(SubTot".addDays($fromdate, $d).") AS SubTot".addDays($fromdate, $d);
}												
else if ($period == 2 ) {
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
					
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
		
			$query = $query.", Sum(Qty".getMonth($m).$y.") AS Qty".getMonth($m).$y.
							", Sum(Amt".getMonth($m).$y.") + Sum(VatAmt".getMonth($m).$y.") AS Amt".getMonth($m).$y.
							", Sum(Chg".getMonth($m).$y.") AS Chg".getMonth($m).$y.
							", Sum(SubTot".getMonth($m).$y.") AS SubTot".getMonth($m).$y;
		}
	}
	
	//$query = $query.", Sum(Qty".getMonth($m).$y.") AS Qty".getMonth($m).$y.
		//			", Sum(Amt".getMonth($m).$y.") AS Amt".getMonth($m).$y;
}	
else if ($period == 3 ) {
	$query = $query.", Sum(TransQty) As TransQty, Sum(TransAmount)+sum(ifnull(VatAmt,0)) As TransAmount, Sum(TransCharges) As TransCharges, Sum(TransSubTotal) As TransSubTotal ";
}	

$query = $query." From ( ";

$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, ".
				" QtyExist, QtySOPend, QtyRemain, QtyPOPend, CurrencyCode, MeanCostAmount, ItemSellingPrice1, ItemSellingPrice2, ".
				" ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize ";
								
if ($period == 1 ) {
	$dayscount = dateDiff($fromdate, $todate);
	for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
		$query = $query.", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , TransQty, 0) AS Qty".addDays($fromdate, $d).
						", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransAmount,0), 0) AS Amt".addDays($fromdate, $d).
						", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransCharges,0), 0) AS Chg".addDays($fromdate, $d).
						", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransSubTotal,0), 0) AS SubTot".addDays($fromdate, $d).
						", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(VatAmt,0), 0) AS VatAmt".addDays($fromdate, $d);
	}
	
	$query = $query.", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , TransQty, 0) AS Qty".addDays($fromdate, $d).
					", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransAmount,0), 0) AS Amt".addDays($fromdate, $d).
					", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransCharges,0), 0) AS Chg".addDays($fromdate, $d).
					", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(TransSubTotal,0), 0) AS SubTot".addDays($fromdate, $d).
					", if(Date_format(TransDate,'%Y-%m-%d')='".addDays($fromdate, $d, 'Y-m-d')."' , ifNull(VatAmt,0), 0) AS VatAmt".addDays($fromdate, $d);
}				
else if ($period == 2 ) {
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
					
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
			$query = $query.", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', TransQty, 0) AS Qty".getMonth($m).$y.
							", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', ifNull(TransAmount,0), 0) AS Amt".getMonth($m).$y.
							", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', ifNull(TransCharges,0), 0) AS Chg".getMonth($m).$y.
							", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', ifNull(TransSubTotal,0), 0) AS SubTot".getMonth($m).$y.
							", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', ifNull(VatAmt,0), 0) AS VatAmt".getMonth($m).$y;
		}
	}
	
	//$query = $query.", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', TransQty, 0) AS Qty".getMonth($m).$y.
		//			", if(Month(TransDate)='".$m."' And Year(TransDate)='".$y."', ifNull(TransAmount,0), 0) AS Amt".getMonth($m).$y;

}

else if ($period == 3 ) {
	$query = $query.", TransQty, TransAmount, TransCharges, TransSubTotal, VatAmt ";
}	
				
	
$query = $query." From ( ";

				
if ($transtype == 'PI' || $transtype == 'PR'|| $transtype == 'PIR') {
	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, ifNull(TransCharges,0) As TransCharges, (ifNull(TransCharges,0) + (ifNull(TransPrice,0)*TransQty)) As TransSubTotal, ".
					" 0 as VatAmt ".
					" From ( ";
	
	$query = $query." Select Purchases.Purchase_Date As TransDate, Purchases.Currency_Code As CurrencyCode, ".
					" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, PurchasesDt.Warehouse_Code, ".
					" if($groupby=6, Purchases.Project_Code, if($groupby=7, Purchases.Costcent_Code, if($groupby=8, Null, if($groupby=9, Purchases.Supplier_Code, '')))))))) As MasterCode,   ".
					" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
					" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, if($groupby=8, Null, if($groupby=9, Suppliers.Ledger_Name, '')))))))) As MasterDescription,  ".
					" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
					" if(PurchasesDt.Journal_Type = 'PI', ifNull(PurchasesDt.PurchaseDt_Quantity,0), (-1)*ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As TransQty,  ".
					" if($PurchaseTTC=1, if(ifNull(PurchasesDt.PurchaseDt_PriceTTC,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_PriceTTCBase2,0), ifNull(PurchasesDt.PurchaseDt_PriceTTC,0))) - ".
					"                  (ifNull(if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_PriceTTCBase2,0), ifNull(PurchasesDt.PurchaseDt_PriceTTC,0))),0) * ifNull(PurchasesDt.PurchaseDt_DiscountPer, 0)/100))*PurchasesDt.PurchaseDt_Quantity - ".
					"                  ifNull(if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_DiscountBase2,0), ifNull(PurchasesDt.PurchaseDt_DiscountAmount,0))),0))/PurchasesDt.PurchaseDt_Quantity) ,0)),  ".
					" if(ifNull(PurchasesDt.PurchaseDt_Price,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_PriceBase2,0), ifNull(PurchasesDt.PurchaseDt_Price,0))) - ".
					"         (ifNull(if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_PriceBase2,0), ifNull(PurchasesDt.PurchaseDt_Price,0))),0) * ifNull(PurchasesDt.PurchaseDt_DiscountPer, 0)/100))*PurchasesDt.PurchaseDt_Quantity - ".
					"         ifNull(if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_DiscountBase2,0), ifNull(PurchasesDt.PurchaseDt_DiscountAmount,0))),0))/PurchasesDt.PurchaseDt_Quantity) ,0)) ) As TransPrice,  ".
					" if(upper($curr)='".$Base1."', ifNull(PurchasesDt.PurchaseDt_ChargesBase1,0), if(upper($curr)='".$Base2."', ifNull(PurchasesDt.PurchaseDt_ChargesBase2,0), ifNull(PurchasesDt.PurchaseDt_Charges,0))) As TransCharges, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
					" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

	if ($prtcost == 1)
		$query= $query." ifNull(MeanCostCur(PurchasesDt.Item_Code, concat(date_format(Purchases.Purchase_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Purchases.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$query= $query." 0 As MeanCostAmount, ";
	
					
	if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
	else $query = $query." 0 As QtyExist, ";
	
	if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
	else $query = $query." 0 As QtySOPend, ";
	
	if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
	else $query = $query." 0 As QtyPOPend ";
	
					
	if ($showallitems != 1)	{		   
		$query= $query. " From PurchasesDt  ".
						" Inner Join Purchases on PurchasesDt.Purchase_ID = Purchases.Purchase_ID ".
						" Inner Join Items on PurchasesDt.Item_Code = Items.Item_Code ";
	} else {					
		$query= $query. " From Items  ".
						" Left Join PurchasesDt on PurchasesDt.Item_Code = Items.Item_Code ".		
						" Left Join Purchases on PurchasesDt.Purchase_ID = Purchases.Purchase_ID ";
	}	
	
	$query= $query. " Left Join Suppliers on Suppliers.Ledger_Number = Purchases.Supplier_Code ".
					" 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 Costcent on Costcent.Costcent_Code = Purchases.Costcent_Code ".
					" Left Join Project on Project.Project_Code = Purchases.Project_Code ".
					" Left Join Warehouse on Warehouse.Warehouse_Code = PurchasesDt.Warehouse_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on Purchases.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on Purchases.Costcent_Code like concat(Q5.costcent_code,'%') ";		 
					   
	if ($prtqtyexist == 1 && $showdetail == 1) {				   
		$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
						"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
						"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						"               Group By Stk.Item_Code ".
						"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
	}

	if ($prtqtySO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
						"			   From (           ".
						"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
						"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
						"             		  From SorderDt ".
						"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
						"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
						" 					  And Sorder.Sorder_Type = 'SO' ".
						"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
						"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
		
	}
	
	if ($prtqtyPO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
						"			   From (           ".
						"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
						"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
						"             		  From PorderDt ".
						"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
						"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
						//" 					  And Porder.Porder_Type = 'PO' ".
						"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
						"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
		
	}

	$query= $query.	" Where 1 = 1  ";
	
	if ($showallitems != 1)
		$query= $query." And Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Purchases.Purchase_Date,'%Y-%m-%d'))  ";
		
	$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
					" 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 ifNull(Purchases.Supplier_Code,'-1') between ifNull(".$fromsupplier.", ifNull(Purchases.Supplier_Code,'-1')) and ifNull(". $tosupplier.", ifNull(Purchases.Supplier_Code,'-1')) ".
					" And ifNull(Purchases.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Purchases.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Purchases.Project_Code,'-1')) ".
					" And ifNull(Purchases.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Purchases.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Purchases.Costcent_Code,'-1')) ".
					" And ifNull(PurchasesDt.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(PurchasesDt.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(PurchasesDt.warehouse_code,'-1')) ";
				
				
				if ($transtype == 'PIR')     $query= $query." 	And ifNull(Purchases.Journal_Type,'PI') in ('PI','PR') ";
				else if ($transtype == 'PI') $query= $query."	And ifNull(Purchases.Journal_Type,'PI') in ('PI') ";
				else if ($transtype == 'PR') $query= $query."	And ifNull(Purchases.Journal_Type,'PR') in ('PR') ";
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And PurchasesDt.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']."')  ";  

	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";
	
	
}

else if (($transtype == 'SI' || $transtype == 'SR'|| $transtype == 'SIR') && $Module_Delivery == 1) {
	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, 0 As TransCharges, 0 As TransSubTotal, ".
					" ifNull(ItemVat,0)* ifNull(TransPrice,0)* TransQty / 100 as VatAmt ".
					" From ( ";
	
	$query = $query." Select Sales.Sale_Date As TransDate, Sales.Currency_Code As CurrencyCode, ".
					" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, SalesDt.Warehouse_Code, ".
					" if($groupby=6, Sales.Project_Code, if($groupby=7, Sales.Costcenter_Code, if($groupby=8, Sales.Client_Code, if($groupby=9, Items.Ledger_Number, if($groupby=10, ifNull(Clients.ClientGrp_Code,'None'), ''))))))))) As MasterCode,   ".
					" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
					" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, if($groupby=8, Clients.Ledger_Name, if($groupby=9, Suppliers.Ledger_Name, if($groupby=10, ifNull(LedgerGrp.LedgerGrp_Name,'None'), ''))))))))) As MasterDescription,  ".
					" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
					" if(SalesDt.Journal_Type = 'SI', ifNull(SalesDt.SaleDt_Quantity,0), (-1)*ifNull(SalesDt.SaleDt_Quantity,0)) As TransQty,  ".
					" if($SalesTTC=1, if(ifNull(SalesDt.SaleDt_PriceTTC,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_PriceTTCBase2,0), ifNull(SalesDt.SaleDt_PriceTTC,0))) - ".
					" (ifNull(if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_PriceTTCBase2,0), ifNull(SalesDt.SaleDt_PriceTTC,0))),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100))*SalesDt.SaleDt_Quantity - ".
					" ifNull(if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_DiscountBase2,0), ifNull(SalesDt.SaleDt_DiscountAmount,0))),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_TransportBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_TransportBase2,SalesDt.SaleDt_TransportAmount)),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_BonusBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_BonusBase2,SalesDt.SaleDt_BonusAmount)),0))/SalesDt.SaleDt_Quantity) ,0)),  ".
					" if(ifNull(SalesDt.SaleDt_Price,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_PriceBase2,0), ifNull(SalesDt.SaleDt_Price,0))) - ".
					" (ifNull(if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_PriceBase2,0), ifNull(SalesDt.SaleDt_Price,0))),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100))*SalesDt.SaleDt_Quantity - ".
					" ifNull(if(upper($curr)='".$Base1."', ifNull(SalesDt.SaleDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(SalesDt.SaleDt_DiscountBase2,0), ifNull(SalesDt.SaleDt_DiscountAmount,0))),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_TransportBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_TransportBase2,SalesDt.SaleDt_TransportAmount)),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_BonusBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_BonusBase2,SalesDt.SaleDt_BonusAmount)),0))/SalesDt.SaleDt_Quantity) ,0)) ) As TransPrice,  ".
					" if(ifNull(sale_chkvat,0) = 1, SalesDt.Item_Vat, 0) As ItemVat, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
					" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

	if ($prtcost == 1)
		$query= $query." ifNull(MeanCostCur(SalesDt.Item_Code, concat(date_format(Sales.Sale_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Sales.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$query= $query." 0 As MeanCostAmount, ";
	
					
	if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
	else $query = $query." 0 As QtyExist, ";
	
	if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
	else $query = $query." 0 As QtySOPend, ";
	
	if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
	else $query = $query." 0 As QtyPOPend ";
	
					
	if ($showallitems != 1)	{		   
		$query= $query. " From SalesDt  ".
						" Inner Join Sales on SalesDt.Sale_ID = Sales.Sale_ID ".
						" Inner Join Items on SalesDt.Item_Code = Items.Item_Code ";
	} else {					
		$query= $query. " From Items  ".
						" Left Join SalesDt on SalesDt.Item_Code = Items.Item_Code ".		
						" Left Join Sales on SalesDt.Sale_ID = Sales.Sale_ID ";
	}	
	
	$query= $query. " Left Join Clients on Clients.Ledger_Number = Sales.Client_Code ".
					" Left Join LedgerGrp on LedgerGrp.LedgerGrp_Code = Clients.ClientGrp_Code ".
					" Left Join Suppliers on Items.Ledger_Number = Suppliers.Ledger_Number ".
					" 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 Costcent on Costcent.Costcent_Code = Sales.Costcenter_Code ".
					" Left Join Project on Project.Project_Code = Sales.Project_Code ".
					" Left Join Warehouse on Warehouse.Warehouse_Code = SalesDt.Warehouse_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on Sales.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on Sales.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
					   
	if ($prtqtyexist == 1 && $showdetail == 1) {				   
		$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
						"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
						"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						"               Group By Stk.Item_Code ".
						"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
	}

	if ($prtqtySO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
						"			   From (           ".
						"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
						"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
						"             		  From SorderDt ".
						"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
						"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
						" 					  And Sorder.Sorder_Type = 'SO' ".
						"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
						"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
		
	}
	
	if ($prtqtyPO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
						"			   From (           ".
						"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
						"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
						"             		  From PorderDt ".
						"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
						"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
						//" 					  And Porder.Porder_Type = 'PO' ".
						"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
						"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
		
	}

	$query= $query.	" Where 1 = 1  ";
	
	if ($showallitems != 1)
		$query= $query." And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ";
		
	$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
					" 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 ifNull(Items.Ledger_Number,'-1') between ifNull(".$fromsupplier.", ifNull(Items.Ledger_Number,'-1')) and ifNull(". $tosupplier.", ifNull(Items.Ledger_Number,'-1')) ".
					" And ifNull(Sales.Client_Code,'-1') between ifNull(".$fromclient.",ifNull(Sales.Client_Code,'-1')) and ifNull(". $toclient.",ifNull(Sales.Client_Code,'-1')) ".
					" And ifNull(Sales.Salesman_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Sales.Salesman_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Sales.Salesman_Code,'-1')) ".
					" And ifNull(Sales.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Sales.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Sales.Project_Code,'-1')) ".
					" And ifNull(Sales.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Sales.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Sales.Costcenter_Code,'-1')) ".
					" And ifNull(Clients.Client_BusinessType,'-1') between ifNull(".$frombustype.",ifNull(Clients.Client_BusinessType,'-1')) and ifNull(". $tobustype.",ifNull(Clients.Client_BusinessType,'-1')) ".
					" And ifNull(SalesDt.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(SalesDt.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(SalesDt.warehouse_code,'-1')) ".
					" And (($promprint=1 and ifNull(SalesDt.SaleDt_Promotion,0) = 1) Or ($promprint=2 and ifNull(SalesDt.SaleDt_Promotion,0) = 0) Or ($promprint=3 and 1 = 1))  ";
				
				
				if ($transtype == 'SIR')     $query= $query." 	And ifNull(Sales.Journal_Type,'SI') in ('SI','SR') ";
				else if ($transtype == 'SI') $query= $query."	And ifNull(Sales.Journal_Type,'SI') in ('SI') ";
				else if ($transtype == 'SR') $query= $query."	And ifNull(Sales.Journal_Type,'SR') in ('SR') ";
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And SalesDt.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']."')  ";  

	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";


}

else if (($transtype == 'SI' || $transtype == 'SR'|| $transtype == 'SIR') && $Module_Delivery == 0) {

	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, 0 As TransCharges, 0 As TransSubTotal, ".
					" ifNull(ItemVat,0)* ifNull(TransPrice,0)* TransQty / 100 as VatAmt ".
					" From ( ";
	
	$query = $query." Select Deliveries.Delivery_Date As TransDate, Deliveries.Currency_Code As CurrencyCode, ".
					" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, DeliveryDt.Warehouse_Code, ".
					" if($groupby=6, Deliveries.Project_Code, if($groupby=7, Deliveries.Costcent_Code, if($groupby=8, Deliveries.Client_Code, if($groupby=9, Items.Ledger_Number, if($groupby=10, ifNull(Clients.ClientGrp_Code,'None'), ''))))))))) As MasterCode,   ".
					" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
					" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, if($groupby=8, Clients.Ledger_Name, if($groupby=9, Suppliers.Ledger_Name, if($groupby=10, ifNull(LedgerGrp.LedgerGrp_Name,'None'), ''))))))))) As MasterDescription,  ".
					" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
					" if(DeliveryDt.Journal_Type = 'DI', ifNull(DeliveryDt.DeliveryDt_Quantity,0), (-1)*ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As TransQty,  ".
					" if($SalesTTC=1, if(ifNull(DeliveryDt.DeliveryDt_PriceTTC,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_PriceTTCBase2,0), ifNull(DeliveryDt.DeliveryDt_PriceTTC,0))) - ".
					" (ifNull(if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_PriceTTCBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_PriceTTCBase2,0), ifNull(DeliveryDt.DeliveryDt_PriceTTC,0))),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100))*DeliveryDt.DeliveryDt_Quantity - ".
					" ifNull(if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_DiscountBase2,0), ifNull(DeliveryDt.DeliveryDt_DiscountAmount,0))),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_TransportAmountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_TransportAmountBase2,DeliveryDt.DeliveryDt_TransportAmount)),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_BonusBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_BonusBase2,DeliveryDt.DeliveryDt_BonusAmount)),0))/DeliveryDt.DeliveryDt_Quantity) ,0)),  ".
					" if(ifNull(DeliveryDt.DeliveryDt_Price,0)=0, 0, ifNull( (((if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_PriceBase2,0), ifNull(DeliveryDt.DeliveryDt_Price,0))) - ".
					" (ifNull(if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_PriceBase2,0), ifNull(DeliveryDt.DeliveryDt_Price,0))),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100))*DeliveryDt.DeliveryDt_Quantity - ".
					" ifNull(if(upper($curr)='".$Base1."', ifNull(DeliveryDt.DeliveryDt_DiscountBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt.DeliveryDt_DiscountBase2,0), ifNull(DeliveryDt.DeliveryDt_DiscountAmount,0))),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_TransportAmountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_TransportAmountBase2,DeliveryDt.DeliveryDt_TransportAmount)),0) - ".
					" ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_BonusBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_BonusBase2,DeliveryDt.DeliveryDt_BonusAmount)),0))/DeliveryDt.DeliveryDt_Quantity) ,0)) )
					As TransPrice,  if(ifNull(Delivery_VAT,0) > 0, DeliveryDt.Item_Vat, 0) As ItemVat,".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
					" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

	if ($prtcost == 1)
		$query= $query." ifNull(MeanCostCur(DeliveryDt.Item_Code, concat(date_format(Deliveries.Delivery_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Deliveries.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$query= $query." 0 As MeanCostAmount, ";
	
					
	if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
	else $query = $query." 0 As QtyExist, ";
	
	if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
	else $query = $query." 0 As QtySOPend, ";
	
	if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
	else $query = $query." 0 As QtyPOPend ";
	
					
	if ($showallitems != 1)	{		   
		$query= $query. " From DeliveryDt  ".
						" Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
						" Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ";
	} else {					
		$query= $query. " From Items  ".
						" Left Join DeliveryDt on DeliveryDt.Item_Code = Items.Item_Code ".		
						" Left Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ";
	}					
	
	$query= $query.	" Left Join Clients on Clients.Ledger_Number = Deliveries.Client_Code ".
					" Left Join LedgerGrp on LedgerGrp.LedgerGrp_Code = Clients.ClientGrp_Code ".
					" Left Join Suppliers on Items.Ledger_Number = Suppliers.Ledger_Number ".
					" 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 Costcent on Costcent.Costcent_Code = Deliveries.Costcent_Code ".
					" Left Join Project on Project.Project_Code = Deliveries.Project_Code ".
					" Left Join Warehouse on Warehouse.Warehouse_Code = DeliveryDt.Warehouse_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on Deliveries.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on Deliveries.Costcent_Code like concat(Q5.costcent_code,'%') ";		 
					   
	if ($prtqtyexist == 1 && $showdetail == 1) {				   
		$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
						"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
						"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						"               Group By Stk.Item_Code ".
						"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
	}

	if ($prtqtySO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
						"			   From (           ".
						"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
						"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
						"             		  From SorderDt ".
						"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
						"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
						" 					  And Sorder.Sorder_Type = 'SO' ".
						"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
						"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
		
	}
	
	if ($prtqtyPO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
						"			   From (           ".
						"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
						"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
						"             		  From PorderDt ".
						"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
						"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
						//" 					  And Porder.Porder_Type = 'PO' ".
						"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
						"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
		
	}

	$query= $query.	" Where 1 = 1  ";
	
	if ($showallitems != 1)
		$query= $query." And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ";
		
	$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
					" 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 ifNull(Items.Ledger_Number,'-1') between ifNull(".$fromsupplier.", ifNull(Items.Ledger_Number,'-1')) and ifNull(". $tosupplier.", ifNull(Items.Ledger_Number,'-1')) ".
					" And ifNull(Deliveries.Client_Code,'-1') between ifNull(".$fromclient.",ifNull(Deliveries.Client_Code,'-1')) and ifNull(". $toclient.",ifNull(Deliveries.Client_Code,'-1')) ".
					" And ifNull(Deliveries.Salesman_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Deliveries.Salesman_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Deliveries.Salesman_Code,'-1')) ".
					" And ifNull(Deliveries.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Deliveries.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Deliveries.Project_Code,'-1')) ".
					" And ifNull(Deliveries.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Deliveries.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Deliveries.Costcent_Code,'-1')) ".
					" And ifNull(Clients.Client_BusinessType,'-1') between ifNull(".$frombustype.",ifNull(Clients.Client_BusinessType,'-1')) and ifNull(". $tobustype.",ifNull(Clients.Client_BusinessType,'-1')) ".
					" And ifNull(DeliveryDt.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(DeliveryDt.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(DeliveryDt.warehouse_code,'-1')) ".
					" And (($promprint=1 and ifNull(DeliveryDt.DeliveryDt_Promotion,0) = 1) Or ($promprint=2 and ifNull(DeliveryDt.DeliveryDt_Promotion,0) = 0) Or ($promprint=3 and 1 = 1))  ";
				
				
				if ($transtype == 'SIR')     $query= $query." 	And ifNull(Deliveries.Journal_Type, 'DI') in ('DI','DR') ";
				else if ($transtype == 'SI') $query= $query."	And ifNull(Deliveries.Journal_Type, 'DI') in ('DI') ";
				else if ($transtype == 'SR') $query= $query."	And ifNull(Deliveries.Journal_Type, 'DR') in ('DR') ";
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And DeliveryDt.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']."')  ";  

	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";
	
	
	
}


else if ($transtype == 'TR' || $transtype == 'TRT') {

	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, 0 As TransCharges, 0 As TransSubTotal ".
					" From ( ";
	
	$query = $query." Select Transfer.Transfer_Date As TransDate, TransferDt.Cur_Code As CurrencyCode, ".
					" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, if('".$transtype."'='TR', TransferDt.TransferDt_WarehouseFrom, TransferDt_WarehouseTo), ".
					" if($groupby=6, if('".$transtype."'='TR', Transfer.Project_Code1, Transfer.Project_Code2), if($groupby=7, if('".$transtype."'='TR', Transfer.Costcenter_Code, ToCostcenter_Code), '')))))) As MasterCode,   ".
					" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
					" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, '')))))) As MasterDescription,  ".
					" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
					" ifNull(TransferDt.TransferDt_Quantity,0) As TransQty,  ".
					" if(upper($curr)='".$Base1."', TransferDt.TransferDt_PriceBase1, if(upper($curr)='".$Base2."',TransferDt.TransferDt_PriceBase2, TransferDt.TransferDt_Price)) As TransPrice, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
					" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

	if ($prtcost == 1)
		$query= $query." ifNull(MeanCostCur(TransferDt.Item_Code, concat(date_format(Transfer.Transfer_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), TransferDt.Cur_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$query= $query." 0 As MeanCostAmount, ";
	
					
	if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
	else $query = $query." 0 As QtyExist, ";
	
	if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
	else $query = $query." 0 As QtySOPend, ";
	
	if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
	else $query = $query." 0 As QtyPOPend ";
	
					
	if ($showallitems != 1)	{		   
		$query= $query. " From TransferDt  ".
						" Inner Join Transfer on TransferDt.Transfer_ID = Transfer.Transfer_ID ".
						" Inner Join Items on TransferDt.Item_Code = Items.Item_Code ";
	} else {					
		$query= $query. " From Items  ".
						" Left Join TransferDt on TransferDt.Item_Code = Items.Item_Code ".		
						" Left Join Transfer on TransferDt.Transfer_ID = Transfer.Transfer_ID  ";
	}
	
	$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 ";
					
	if ($transtype == 'TR')	{
		$query= $query." Left Join Costcent on Costcent.Costcent_Code = Transfer.Costcenter_Code ".
					   " Left Join Project on Project.Project_Code = Transfer.Project_Code1 ".
					   " Left Join Warehouse on Warehouse.Warehouse_Code = TransferDt.TransferDt_WarehouseFrom ";
	} else {
		$query= $query." Left Join Costcent on Costcent.Costcent_Code = Transfer.ToCostcenter_Code ".
					   " Left Join Project on Project.Project_Code = Transfer.Project_Code2 ".
					   " Left Join Warehouse on Warehouse.Warehouse_Code = TransferDt.TransferDt_WarehouseTo ";
	}
					   

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on Transfer.project_code1 like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on Transfer.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
					   
	if ($prtqtyexist == 1 && $showdetail == 1) {				   
		$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
						"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
						"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						"               Group By Stk.Item_Code ".
						"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
	}

	if ($prtqtySO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
						"			   From (           ".
						"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
						"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
						"             		  From SorderDt ".
						"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
						"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
						" 					  And Sorder.Sorder_Type = 'SO' ".
						"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
						"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
		
	}
	
	if ($prtqtyPO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
						"			   From (           ".
						"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
						"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
						"             		  From PorderDt ".
						"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
						"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
						//" 					  And Porder.Porder_Type = 'PO' ".
						"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
						"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
		
	}

	$query= $query.	" Where 1 = 1  ";
	
	if ($showallitems != 1)
		$query= $query." And Date_format(Transfer.Transfer_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Transfer.Transfer_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Transfer.Transfer_Date,'%Y-%m-%d'))  ";
		
	$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
					" 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 ifNull(Transfer.Project_Code1,'-1') between ifNull(".$fromproject.",ifNull(Transfer.Project_Code1,'-1')) and ifNull(". $toproject.",ifNull(Transfer.Project_Code1,'-1')) ".
					" And ifNull(Transfer.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Transfer.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Transfer.Costcenter_Code,'-1')) ".
					" And (( ifNull(TransferDt.TransferDt_WarehouseFrom,'-1') = ifNull(". $fromwarehouse .",ifNull(TransferDt.TransferDt_WarehouseFrom,'-1'))) or   ".
					" 	   ( ifNull(TransferDt.TransferDt_WarehouseTo,'-1') = ifNull(". $towarehouse .",ifNull(TransferDt.TransferDt_WarehouseTo,'-1'))) )   ";
					
				
				
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And TransferDt.TransferDt_WarehouseFrom 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']."')  ";  

	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";
	
}

else if ($transtype == 'AI' || $transtype == 'AR') {

	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, 0 As TransCharges, 0 As TransSubTotal ".
					" From ( ";
	
	$query = $query." Select Adjustment.Adjustment_Date As TransDate, Adjustment.Currency_Code As CurrencyCode, ".
					" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, AdjustmentDt.Warehouse_Code, ".
					" if($groupby=6, Adjustment.Project_Code, if($groupby=7, Adjustment.Costcent_Code, '')))))) As MasterCode,   ".
					" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
					" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, '')))))) As MasterDescription,  ".
					" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
					" if(AdjustmentDt.Journal_Type = 'AI', ifNull(AdjustmentDt.AdjustmentDt_Quantity,0), ifNull(AdjustmentDt.AdjustmentDt_Quantity,0)) As TransQty,  ".
					" if(upper($curr)='".$Base1."', AdjustmentDt.AdjustmentDt_PriceBase1, if(upper($curr)='".$Base2."',AdjustmentDt.AdjustmentDt_PriceBase2, AdjustmentDt.AdjustmentDt_Price)) As TransPrice, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
					" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
					" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

	if ($prtcost == 1)
		$query= $query." ifNull(MeanCostCur(AdjustmentDt.Item_Code, concat(date_format(Adjustment.Adjustment_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Adjustment.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$query= $query." 0 As MeanCostAmount, ";
	
					
	if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
	else $query = $query." 0 As QtyExist, ";
	
	if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
	else $query = $query." 0 As QtySOPend, ";
	
	if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
	else $query = $query." 0 As QtyPOPend ";
	
					
	if ($showallitems != 1)	{		   
		$query= $query. " From AdjustmentDt  ".
						" Inner Join Adjustment on AdjustmentDt.Adjustment_ID = Adjustment.Adjustment_ID ".
						" Inner Join Items on AdjustmentDt.Item_Code = Items.Item_Code ";
	} else {					
		$query= $query. " From Items  ".
						" Left Join AdjustmentDt on AdjustmentDt.Item_Code = Items.Item_Code ".		
						" Left Join Adjustment on AdjustmentDt.Adjustment_ID = Adjustment.Adjustment_ID  ";
	}
	
	$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 Costcent on Costcent.Costcent_Code = Adjustment.Costcent_Code ".
					" Left Join Project on Project.Project_Code = Adjustment.Project_Code ".
					" Left Join Warehouse on Warehouse.Warehouse_Code = AdjustmentDt.Warehouse_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on Adjustment.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on Adjustment.Costcent_Code like concat(Q5.costcent_code,'%') ";		 
					   
	if ($prtqtyexist == 1 && $showdetail == 1) {				   
		$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
						"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
						"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						"               Group By Stk.Item_Code ".
						"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
	}

	if ($prtqtySO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
						"			   From (           ".
						"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
						"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
						"             		  From SorderDt ".
						"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
						"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
						" 					  And Sorder.Sorder_Type = 'SO' ".
						"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
						"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
		
	}
	
	if ($prtqtyPO == 1 && $showdetail == 1) {
		$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
						"			   From (           ".
						"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
						"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
						"             		  From PorderDt ".
						"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
						"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
						//" 					  And Porder.Porder_Type = 'PO' ".
						"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
						"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
						"              	    ) as A Group By Item_Code ".
						" 					Having QuantityPending > 0 ";
		
		$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
		
	}

	$query= $query.	" Where 1 = 1  ";
	
	if ($showallitems != 1)
		$query= $query." And Date_format(Adjustment.Adjustment_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Adjustment.Adjustment_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Adjustment.Adjustment_Date,'%Y-%m-%d'))  ";
		
	$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
					" 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 ifNull(Adjustment.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Adjustment.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Adjustment.Project_Code,'-1')) ".
					" And ifNull(Adjustment.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Adjustment.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Adjustment.Costcent_Code,'-1')) ".
					" And ifNull(AdjustmentDt.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(AdjustmentDt.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(AdjustmentDt.warehouse_code,'-1')) ";
				
				
				if ($transtype == 'AI')      $query= $query."	And ifNull(AdjustmentDt.AdjustmentDt_Quantity,0) >= 0 ";
				else if ($transtype == 'AR') $query= $query."	And ifNull(AdjustmentDt.AdjustmentDt_Quantity,0) < 0 ";
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And AdjustmentDt.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']."')  ";  

	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";
	
}



else if ($transtype == 'PD' || $transtype == 'PDT') {

	$query = $query." Select MasterCode, MasterDescription, ItemCode, ItemDescription, ItemUnit, TransDate, TransQty, ".
					" QtyExist, QtySOPend, (QtyExist - QtySOPend) As QtyRemain, QtyPOPend, CurrencyCode, (ifNull(TransPrice,0)*TransQty) As TransAmount, MeanCostAmount, ".
					" ItemSellingPrice1, ItemSellingPrice2, ItemSellingPrice3, ItemSellingPrice4, ItemSellingPrice5, ItemSellingPrice6, ".
					" ItemGroup, ItemSubGroup, ItemCategory, ItemColor, ItemSize, 0 As TransCharges, 0 As TransSubTotal ".
					" From ( ";
	
	if ($transtype == 'PDT') {
		$query = $query." Select Production.Production_Date As TransDate, Production.Currency_Code As CurrencyCode, ".
						" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, ProductionDt.Warehouse_Code, ".
						" if($groupby=6, Production.Project_Code, if($groupby=7, Production.Costcenter_Code, '')))))) As MasterCode,   ".
						" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
						" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, '')))))) As MasterDescription,  ".
						" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
						" (-1)*ifNull(ProductionDt.ProductionDt_Quantity,0) As TransQty,  ".
						" if(upper($curr)='".$Base1."',ProductionDt.ProductionDt_CostBase1,if(upper($curr)='".$Base2."',ProductionDt.ProductionDt_CostBase2, ProductionDt.ProductionDt_Cost)) As TransPrice, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
						" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

		if ($prtcost == 1)
			$query= $query." ifNull(MeanCostCur(ProductionDt.Item_Code, concat(date_format(Production.Production_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Production.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
		else
			$query= $query." 0 As MeanCostAmount, ";
		
						
		if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
		else $query = $query." 0 As QtyExist, ";
		
		if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
		else $query = $query." 0 As QtySOPend, ";
		
		if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
		else $query = $query." 0 As QtyPOPend ";
		
						
		if ($showallitems != 1)	{		   
			$query= $query. " From ProductionDt  ".
							" Inner Join Production on ProductionDt.Production_ID = Production.Production_ID ".
							" Inner Join Items on ProductionDt.Item_Code = Items.Item_Code ";
		} else {					
			$query= $query. " From Items  ".
							" Left Join ProductionDt on ProductionDt.Item_Code = Items.Item_Code ".		
							" Left Join Production on ProductionDt.Production_ID = Production.Production_ID  ";
		}
	
		$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 Costcent on Costcent.Costcent_Code = Production.Costcenter_Code ".
						" Left Join Project on Project.Project_Code = Production.Project_Code ".
						" Left Join Warehouse on Warehouse.Warehouse_Code = ProductionDt.Warehouse_Code ";

		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$query= $query.$QueryRestrictPrj." on Production.project_code like concat(Q4.project_code,'%') ";
									 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query= $query.$QueryRestrictCst." on Production.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
						   
		if ($prtqtyexist == 1 && $showdetail == 1) {				   
			$query= $query. " Left Join (  ".
							"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
							"               From StkTransaction Stk ".
							"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
							"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
							"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
							"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
							"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
							"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
							"               Group By Stk.Item_Code ".
							"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
		}

		if ($prtqtySO == 1 && $showdetail == 1) {
			$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
							"			   From (           ".
							"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
							"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
							"             		  From SorderDt ".
							"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
							"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
							"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
							" 					  And Sorder.Sorder_Type = 'SO' ".
							"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
							"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
							"              	    ) as A Group By Item_Code ".
							" 					Having QuantityPending > 0 ";
			
			$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
			
		}
		
		if ($prtqtyPO == 1 && $showdetail == 1) {
			$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
							"			   From (           ".
							"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
							"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
							"             		  From PorderDt ".
							"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
							"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
							"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
							//" 					  And Porder.Porder_Type = 'PO' ".
							"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
							"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
							"              	    ) as A Group By Item_Code ".
							" 					Having QuantityPending > 0 ";
			
			$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
			
		}

		$query= $query.	" Where (Production.Production_Reference Is Not Null And Production.Production_Reference != '')  ";
		
		if ($showallitems != 1)
			$query= $query." And Date_format(Production.Production_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Production.Production_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Production.Production_Date,'%Y-%m-%d'))  ";
			
		$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
						" 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 ifNull(Production.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Production.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Production.Project_Code,'-1')) ".
						" And ifNull(Production.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Production.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Production.Costcenter_Code,'-1')) ".
						" And ifNull(ProductionDt.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(ProductionDt.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(ProductionDt.warehouse_code,'-1')) ";
					
					
					if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
						$query= $query." 	And ProductionDt.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']."')  ";  
	}
	else if ($transtype == 'PD') {
		$query = $query." Select Production.Production_Date As TransDate, Production.Currency_Code As CurrencyCode, ".
						" if($groupby=2, Items.Group_Code, if($groupby=3, Items.SubGroup_Code, if($groupby=4, Items.Category_Code, if($groupby=5, Production.Warehouse_Code, ".
						" if($groupby=6, Production.Project_Code, if($groupby=7, Production.Costcenter_Code, '')))))) As MasterCode,   ".
						" if($groupby=2, Grouping.Group_Name, if($groupby=3, Subgroup.Subgroup_Name, if($groupby=4, Category.Category_Name, if($groupby=5, Warehouse.Warehouse_Name, ".
						" if($groupby=6, Project.Project_Name, if($groupby=7, Costcent.Costcent_Name, '')))))) As MasterDescription,  ".
						" if($showdetail=1, Items.Item_Code, '') As ItemCode, if($showdetail=1, Items.Item_Description, '') As ItemDescription, if($showdetail=1, Items.Item_Unit, '') As ItemUnit, ".
						" ifNull(Production.Production_Quantity,0) As TransQty,  ".
						" if(upper($curr)='".$Base1."',Production.Production_TotalBase1,if(upper($curr)='".$Base2."',Production.Production_TotalBase2, Production.Production_Total))/ifNull(Production.Production_Quantity,1) As TransPrice, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice1Base2,0), ifNull(Items.Item_SellingPrice1,0))) As ItemSellingPrice1, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice2Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice2Base2,0), ifNull(Items.Item_SellingPrice2,0))) As ItemSellingPrice2, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice3Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice3Base2,0), ifNull(Items.Item_SellingPrice3,0))) As ItemSellingPrice3, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice4Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice4Base2,0), ifNull(Items.Item_SellingPrice4,0))) As ItemSellingPrice4, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice5Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice5Base2,0), ifNull(Items.Item_SellingPrice5,0))) As ItemSellingPrice5, ".
						" if(upper($curr)='".$Base1."', ifNull(Items.Item_SellingPrice6Base1,0), if(upper($curr)='".$Base2."', ifNull(Items.Item_SellingPrice6Base2,0), ifNull(Items.Item_SellingPrice6,0))) As ItemSellingPrice6, ".
						" Items.Group_Code As ItemGroup, Items.SubGroup_Code As ItemSubGroup, Items.Category_Code As ItemCategory, Items.Item_Color As ItemColor, Items.Item_Size As ItemSize, ";

		if ($prtcost == 1)
			$query= $query." ifNull(MeanCostCur(Production.Item_Code, concat(date_format(Production.Production_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1, if(upper($curr)='".$Base2."',2, 1)), Production.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
		else
			$query= $query." 0 As MeanCostAmount, ";
		
						
		if ($prtqtyexist == 1 && $showdetail == 1) $query = $query." ifNull(QQtyExist.QuantityExists,0) As QtyExist, ";
		else $query = $query." 0 As QtyExist, ";
		
		if ($prtqtySO == 1 && $showdetail == 1) $query = $query." ifNull(QQtySOPend.QuantityPending,0) As QtySOPend, ";
		else $query = $query." 0 As QtySOPend, ";
		
		if ($prtqtyPO == 1 && $showdetail == 1) $query = $query." ifNull(QQtyPOPend.QuantityPending,0) As QtyPOPend ";
		else $query = $query." 0 As QtyPOPend ";
		
						
		if ($showallitems != 1)	{		   
			$query= $query. " From Production  ".
							" Inner Join Items on Production.Item_Code = Items.Item_Code ";
		} else {					
			$query= $query. " From Items  ".
							" Left Join Production on Production.Item_Code = Items.Item_Code ";
		}
		
		$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 Costcent on Costcent.Costcent_Code = Production.Costcenter_Code ".
						" Left Join Project on Project.Project_Code = Production.Project_Code ".
						" Left Join Warehouse on Warehouse.Warehouse_Code = Production.Warehouse_Code ";

		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$query= $query.$QueryRestrictPrj." on Production.project_code like concat(Q4.project_code,'%') ";
									 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query= $query.$QueryRestrictCst." on Production.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
						   
		if ($prtqtyexist == 1 && $showdetail == 1) {				   
			$query= $query. " Left Join (  ".
							"               Select Stk.Item_Code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
							"               From StkTransaction Stk ".
							"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull('". $todate."',date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
							"  				And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
							"               And ifNull(Stk.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Stk.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Stk.Project_Code,'-1')) ".
							"               And ifNull(Stk.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Stk.Costcent_Code,'-1')) ".
							"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
							"               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
							"               Group By Stk.Item_Code ".
							"             ) As QQtyExist on Items.Item_Code = QQtyExist.Item_Code   ";
		}

		if ($prtqtySO == 1 && $showdetail == 1) {
			$query= $query.	" Left Join ( Select Item_Code, Sum(QuantitySorder - QuantityDelivered) as QuantityPending ".
							"			   From (           ".
							"                     Select SorderDt.Sorder_ID, SorderDt.Item_Code, ifNull(SorderDt.SorderDt_Quantity,0) As QuantitySorder, ".
							"                     Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
							"             		  From SorderDt ".
							"       		      Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
							"       		      Left Outer Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID And DeliveryDt.Journal_Type = 'DI')   ".
							"	            	  Where ifNull(SorderDt.SorderDt_OldData,0) = 0  ".
							" 					  And Sorder.Sorder_Type = 'SO' ".
							"                     And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0 ".
							"              	      Group by SorderDt.Sorder_ID, SorderDt.SorderDt_ID, SorderDt.Item_Code ".
							"              	    ) as A Group By Item_Code ".
							" 					Having QuantityPending > 0 ";
			
			$query = $query."	          ) As QQtySOPend on QQtySOPend.Item_Code = Items.Item_Code ";
			
		}
		
		if ($prtqtyPO == 1 && $showdetail == 1) {
			$query= $query.	" Left Join ( Select Item_Code, Sum(QuantityPorder - QuantityPurchased) as QuantityPending ".
							"			   From (           ".
							"                     Select PorderDt.Porder_ID, PorderDt.Item_Code, ifNull(PorderDt.PorderDt_Quantity,0) As QuantityPorder, ".
							"                     Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
							"             		  From PorderDt ".
							"       		      Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
							"       		      Left Outer Join PurchasesDt on (PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_Id And PurchasesDt.Journal_Type = 'PI') ".
							"	            	  Where ifNull(PorderDt.PorderDt_OldData,0) = 0  ".
							//" 					  And Porder.Porder_Type = 'PO' ".
							"                     And ifNull(PurchasesDt.PurchaseDt_OldData,0) = 0 ".
							"              	      Group by PorderDt.Porder_ID, PorderDt.PorderDt_ID, PorderDt.Item_Code ".
							"              	    ) as A Group By Item_Code ".
							" 					Having QuantityPending > 0 ";
			
			$query = $query."	          ) As QQtyPOPend on QQtyPOPend.Item_Code = Items.Item_Code ";
			
		}

		$query= $query.	" Where 1 = 1  ";
		
		if ($showallitems != 1)
			$query= $query.	" And Date_format(Production.Production_Date,'%Y-%m-%d') between ifNull('". $fromdate."',date_format(Production.Production_Date,'%Y-%m-%d')) and ifNull('". $todate."',date_format(Production.Production_Date,'%Y-%m-%d'))  ";
			
		$query= $query.	" And Items.Item_Code between ifNull(".$fromitem.",Items.Item_Code) and ifNull(". $toitem.",Items.Item_Code) ".
						" 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 ifNull(Production.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Production.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Production.Project_Code,'-1')) ".
						" And ifNull(Production.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Production.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Production.Costcenter_Code,'-1')) ".
						" And ifNull(Production.warehouse_code,'-1') between ifNull(".$fromwarehouse.",ifNull(Production.warehouse_code,'-1')) and ifNull(". $towarehouse.",ifNull(Production.warehouse_code,'-1')) ";
					
					
					if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
						$query= $query." 	And Production.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']."')  ";  
	}
	
	$query= $query." 	Order by MasterCode, ItemCode, TransDate  ";				
	$query= $query." ) Q1 ";
	
	
}


$query= $query."    ) Q2 ";
$query= $query."    Order by MasterCode, ItemCode  ";				
$query= $query." ) Q3 ".
			   " Group By MasterCode, ItemCode ".
			   " Order by MasterCode, ItemCode  ";
	
//echo $query; 
//exit;	

$ArrayTotalByPeriod   = Array();
$ArrayTotalByMaster   = Array();

$MasterByCode = '';
$MasterByName = '';

$result=mysql_query($query,$connection) or die(mysql_error());
while($rows=mysql_fetch_row($result)){

	if (($showdetail == 1 && $groupby != 1) && ($MasterByCode != $rows[0] && $MasterByCode != '')) {
		    
		echo "<tr>";
		echo "   <td colspan='3'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
			
	//	echo "<tr><td colspan='3'>";

		// Display Totals By Group	
		$StyleClass  = 'totals';
		$TotalsLabel = 'Total by '.$MasterByLabel;
		
		DisplayTotals($period, $vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $fromdate, $todate, $prtqtyexist, $prtqtySO, $prtqtyPO, $prtqty, $prtprice, $prtamt, $fi_showcostprice, $prtcost, $sellprices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $showdetail, $prtavg, $prtshortage, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass, $prtgroup, $prtsubgroup, $prtcategory, $prtcolor, $prtsize, $prtcharges);		

	//	echo"</td></tr>";
		echo "<tr><td colspan='3'>&nbsp;</td></tr>";	
			
	}
	
	if (($showdetail == 1 && $groupby != 1) && ($MasterByCode == '' || $MasterByCode!= $rows[0])) {
		echo "<tr class='group'>";
		echo "   <td align='center' valign='top' colspan='3' >". $rows[0]." - ".$rows[1] ."</td>";
		echo "</tr>"; 
		
	    $MasterByCode = $rows[0];
		$MasterByName = $rows[1];
		
		unset($ArrayTotalByMaster);
	}
	
	
	
//	echo "  <tr><td colspan='3'>";
	
	//Create Table Columns
	CreateTableStructure($period, $vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $fromdate, $todate, $prtqtyexist, $prtqtySO, $prtqtyPO, $prtqty, $prtprice, $prtamt, $fi_showcostprice, $prtcost, $sellprices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $showdetail, $prtavg, $prtshortage, $prtgroup, $prtsubgroup, $prtcategory, $prtcolor, $prtsize, $prtcharges);

//	echo"	<tr>";
	
	if ($showdetail == 0 && $groupby != 1) {
		echo "<td align='center' valign='top' >". $rows[0] ."</td>";
		echo "<td align='center' valign='top' >". $rows[1] ."</td>";
	}
	else {
		echo "<td align='center' valign='top' >". $rows[2] ."</td>";
		echo "<td align='center' valign='top' >". $rows[3] ."</td>";
	}
	
	echo "<td align='center' valign='top' >". $rows[4] ."</td>";
	
	if ($prtgroup == 1)
		echo "<td align='center' valign='top' >". $rows[18] ."</td>";
	if ($prtsubgroup == 1)
		echo "<td align='center' valign='top' >". $rows[19] ."</td>";
	if ($prtcategory == 1)
		echo "<td align='center' valign='top' >". $rows[20] ."</td>";
	if ($prtcolor == 1)
		echo "<td align='center' valign='top' >". $rows[21] ."</td>";
	if ($prtsize == 1)
		echo "<td align='center' valign='top' >". $rows[22] ."</td>";
	
	if ($prtqtyexist == 1)
		echo "<td align='center' valign='top' >". number_format($rows[6], $InventoryRMaskqty) ."</td>";
	if ($prtqtySO == 1)
		echo "<td align='center' valign='top' >". number_format($rows[7], $InventoryRMaskqty) ."</td>";
	if ($prtqtyexist == 1 && $prtqtySO == 1)	
		echo "<td align='center' valign='top' >". number_format($rows[8], $InventoryRMaskqty) ."</td>";
		
	if ($period == 1) {
		$i = 23;
		$j = 0;
		$TotalQtyByRow      = 0;
		$TotalAmountByRow   = 0;
		$TotalChargesByRow  = 0;
		$TotalSubTotalByRow = 0;
		$AverageQtyByRow    = 0;
		$LastQtyByRow       = 0;
		$ShortageQtyByRow   = 0;
		$AverageAmtByRow    = 0;
		$LastAmtByRow       = 0;
		$ShortageAmtByRow   = 0;
		$AverageChgByRow    = 0;
		$LastChgByRow       = 0;
		$ShortageChgByRow   = 0;
		$AverageSubByRow    = 0;
		$LastSubByRow       = 0;
		$ShortageSubByRow   = 0;
		
		$dayscount = dateDiff($fromdate, $todate);
		
		for ( $d = 0; $d <= $dayscount - 1; $d += 1) {	
			if ($prtqty == 1) {
				echo "<td align='center'  valign='top' >". number_format($rows[$i], $InventoryRMaskqty) ."</td>";
			}	
			if ($prtamt == 1) {
				echo "<td align='center' valign='top' >". format_currency($rows[$i + 1], $DecimalBase) ."</td>";
			}	
			
			if($prtcharges == 1){
				echo "<td align='center' valign='top' >". format_currency($rows[$i + 2], $DecimalBase) ."</td>";
				echo "<td align='center' valign='top' >". format_currency($rows[$i + 3], $DecimalBase) ."</td>";
			}
				
			$TotalQtyByRow     	  = $TotalQtyByRow + $rows[$i];
			$TotalAmountByRow  	  = $TotalAmountByRow + $rows[$i + 1];
			$TotalChargesByRow    = $TotalChargesByRow + $rows[$i + 2];
			$TotalSubTotalByRow   = $TotalSubTotalByRow + $rows[$i + 3];
				
			$ArrayTotalByPeriod['Qty'][$d]        = $ArrayTotalByPeriod['Qty'][$d] + $rows[$i];
			$ArrayTotalByPeriod['Amount'][$d]     = $ArrayTotalByPeriod['Amount'][$d] + $rows[$i + 1];
			$ArrayTotalByPeriod['Charges'][$d]    = $ArrayTotalByPeriod['Charges'][$d] + $rows[$i + 2];
			$ArrayTotalByPeriod['SubTotal'][$d]   = $ArrayTotalByPeriod['SubTotal'][$d] + $rows[$i + 3];
			
			$ArrayTotalByMaster['Qty'][$d]        = $ArrayTotalByMaster['Qty'][$d] + $rows[$i];
			$ArrayTotalByMaster['Amount'][$d]     = $ArrayTotalByMaster['Amount'][$d] + $rows[$i + 1];
			$ArrayTotalByMaster['Charges'][$d]    = $ArrayTotalByMaster['Charges'][$d] + $rows[$i + 2];
			$ArrayTotalByMaster['SubTotal'][$d]   = $ArrayTotalByMaster['SubTotal'][$d] + $rows[$i + 3];
			
			$i = $i + 4;
			$j = $j + 1;
		}
		
		$ArrayTotalByPeriod['Qty'][$d]        = $ArrayTotalByPeriod['Qty'][$d] + $rows[$i];
		$ArrayTotalByPeriod['Amount'][$d]     = $ArrayTotalByPeriod['Amount'][$d] + $rows[$i + 1];
		$ArrayTotalByPeriod['Charges'][$d]    = $ArrayTotalByPeriod['Charges'][$d] + $rows[$i + 2];
		$ArrayTotalByPeriod['SubTotal'][$d]   = $ArrayTotalByPeriod['SubTotal'][$d] + $rows[$i + 3];
			
		$ArrayTotalByMaster['Qty'][$d]        = $ArrayTotalByMaster['Qty'][$d] + $rows[$i];
		$ArrayTotalByMaster['Amount'][$d]     = $ArrayTotalByMaster['Amount'][$d] + $rows[$i + 1];
		$ArrayTotalByMaster['Charges'][$d]    = $ArrayTotalByMaster['Charges'][$d] + $rows[$i + 2];
		$ArrayTotalByMaster['SubTotal'][$d]   = $ArrayTotalByMaster['SubTotal'][$d] + $rows[$i + 3];
		
		if ($j > 0)	$AverageQtyByRow = ($TotalQtyByRow / $j);
		if ($j > 0)	$AverageAmtByRow = ($TotalAmountByRow / $j);
		if ($j > 0)	$AverageChgByRow = ($TotalChargesByRow / $j);
		if ($j > 0)	$AverageSubByRow = ($TotalSubTotalByRow / $j);
		$LastQtyByRow = $rows[$i];
		$LastAmtByRow = $rows[$i + 1];
		$LastChgByRow = $rows[$i + 2];
		$LastSubByRow = $rows[$i + 3];
		$ShortageQtyByRow = $AverageQtyByRow - $LastQtyByRow;
		$ShortageAmtByRow = $AverageAmtByRow - $LastAmtByRow;
		$ShortageChgByRow = $AverageChgByRow - $LastChgByRow;
		$ShortageSubByRow = $AverageSubByRow - $LastSubByRow;
	}
	else if ($period == 2 ) {
		$i = 23;
		$j = 0;
		$TotalQtyByRow      = 0;
		$TotalAmountByRow   = 0;
		$TotalChargesByRow  = 0;
		$TotalSubTotalByRow = 0;
		$AverageQtyByRow    = 0;
		$LastQtyByRow       = 0;
		$ShortageQtyByRow   = 0;
		$AverageAmtByRow    = 0;
		$LastAmtByRow       = 0;
		$ShortageAmtByRow   = 0;
		$AverageChgByRow    = 0;
		$LastChgByRow       = 0;
		$ShortageChgByRow   = 0;
		$AverageSubByRow    = 0;
		$LastSubByRow       = 0;
		$ShortageSubByRow   = 0;
	
		for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

			if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo - 1; }
			else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
			else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo - 1; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				if ($prtqty == 1) {
					echo "<td align='center'  valign='top' >". number_format($rows[$i], $InventoryRMaskqty) ."</td>";
				}	
				if ($prtamt == 1) {
					echo "<td align='center' valign='top' >". format_currency($rows[$i + 1], $DecimalBase) ."</td>";
				}
				
				if($prtcharges == 1){
					echo "<td align='center' valign='top' >". format_currency($rows[$i + 2], $DecimalBase) ."</td>";
					echo "<td align='center' valign='top' >". format_currency($rows[$i + 3], $DecimalBase) ."</td>";
				}
				
				$TotalQtyByRow     	  = $TotalQtyByRow + $rows[$i];
				$TotalAmountByRow  	  = $TotalAmountByRow + $rows[$i + 1];
				$TotalChargesByRow    = $TotalChargesByRow + $rows[$i + 2];
				$TotalSubTotalByRow   = $TotalSubTotalByRow + $rows[$i + 3];
				
				$ArrayTotalByPeriod['Qty'][$y.$m]        = $ArrayTotalByPeriod['Qty'][$y.$m] + $rows[$i];
				$ArrayTotalByPeriod['Amount'][$y.$m]     = $ArrayTotalByPeriod['Amount'][$y.$m] + $rows[$i + 1];
				$ArrayTotalByPeriod['Charges'][$y.$m]    = $ArrayTotalByPeriod['Charges'][$y.$m] + $rows[$i + 2];
				$ArrayTotalByPeriod['SubTotal'][$y.$m]   = $ArrayTotalByPeriod['SubTotal'][$y.$m] + $rows[$i + 3];
				
				$ArrayTotalByMaster['Qty'][$y.$m]        = $ArrayTotalByMaster['Qty'][$y.$m] + $rows[$i];
				$ArrayTotalByMaster['Amount'][$y.$m]     = $ArrayTotalByMaster['Amount'][$y.$m] + $rows[$i + 1];
				$ArrayTotalByMaster['Charges'][$y.$m]    = $ArrayTotalByMaster['Charges'][$y.$m] + $rows[$i + 2];
				$ArrayTotalByMaster['SubTotal'][$y.$m]   = $ArrayTotalByMaster['SubTotal'][$y.$m] + $rows[$i + 3];
				
				$i = $i + 4;
				$j = $j + 1;
			}

		}
		
		$ArrayTotalByPeriod['Qty'][$y.$m]        = $ArrayTotalByPeriod['Qty'][$y.$m] + $rows[$i];
		$ArrayTotalByPeriod['Amount'][$y.$m]     = $ArrayTotalByPeriod['Amount'][$y.$m] + $rows[$i + 1];
		$ArrayTotalByPeriod['Charges'][$y.$m]    = $ArrayTotalByPeriod['Charges'][$y.$m] + $rows[$i + 2];
		$ArrayTotalByPeriod['SubTotal'][$y.$m]   = $ArrayTotalByPeriod['SubTotal'][$y.$m] + $rows[$i + 3];
				
		$ArrayTotalByMaster['Qty'][$y.$m]        = $ArrayTotalByMaster['Qty'][$y.$m] + $rows[$i];
		$ArrayTotalByMaster['Amount'][$y.$m]     = $ArrayTotalByMaster['Amount'][$y.$m] + $rows[$i + 1];
		$ArrayTotalByMaster['Charges'][$y.$m]    = $ArrayTotalByMaster['Charges'][$y.$m] + $rows[$i + 2];
		$ArrayTotalByMaster['SubTotal'][$y.$m]   = $ArrayTotalByMaster['SubTotal'][$y.$m] + $rows[$i + 3];
		
		if ($j > 0)	$AverageQtyByRow = ($TotalQtyByRow / $j);
		if ($j > 0)	$AverageAmtByRow = ($TotalAmountByRow / $j);
		if ($j > 0)	$AverageChgByRow = ($TotalChargesByRow / $j);
		if ($j > 0)	$AverageSubByRow = ($TotalSubTotalByRow / $j);
		$LastQtyByRow = $rows[$i];
		$LastAmtByRow = $rows[$i + 1];
		$LastChgByRow = $rows[$i + 2];
		$LastSubByRow = $rows[$i + 3];
		$ShortageQtyByRow = $AverageQtyByRow - $LastQtyByRow;
		$ShortageAmtByRow = $AverageAmtByRow - $LastAmtByRow;
		$ShortageChgByRow = $AverageChgByRow - $LastChgByRow;
		$ShortageSubByRow = $AverageSubByRow - $LastSubByRow;
		
	}	
	
	else if ($period == 3 ) {
		$i = 23;
		
		if ($prtqty == 1) {
			echo "<td align='center'  valign='top' >". number_format($rows[$i], $InventoryRMaskqty) ."</td>";
		}	
		if ($prtamt == 1) {
			echo "<td align='center' valign='top' >". format_currency($rows[$i + 1], $DecimalBase) ."</td>";
		}
		if($prtcharges == 1){
			echo "<td align='center' valign='top' >". format_currency($rows[$i + 2], $DecimalBase) ."</td>";
			echo "<td align='center' valign='top' >". format_currency($rows[$i + 3], $DecimalBase) ."</td>";
		}
				
		$ArrayTotalByPeriod['Qty']        = $ArrayTotalByPeriod['Qty'] + $rows[$i];
		$ArrayTotalByPeriod['Amount']     = $ArrayTotalByPeriod['Amount'] + $rows[$i + 1];
		$ArrayTotalByPeriod['Charges']    = $ArrayTotalByPeriod['Charges'] + $rows[$i + 2];
		$ArrayTotalByPeriod['SubTotal']   = $ArrayTotalByPeriod['SubTotal'] + $rows[$i + 3];
				
		$ArrayTotalByMaster['Qty']        = $ArrayTotalByMaster['Qty'] + $rows[$i];
		$ArrayTotalByMaster['Amount']     = $ArrayTotalByMaster['Amount'] + $rows[$i + 1];
		$ArrayTotalByMaster['Charges']    = $ArrayTotalByMaster['Charges'] + $rows[$i + 2];
		$ArrayTotalByMaster['SubTotal']   = $ArrayTotalByMaster['SubTotal'] + $rows[$i + 3];
	}
	
		
	if ($period == 1 || $period == 2) {
		if ($prtqty == 1 && $prtamt == 1) {
			if ($prtavg == 1) {
				echo "<td align='center'  valign='top' >". number_format($AverageQtyByRow, $InventoryRMaskqty) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($AverageAmtByRow, $DecimalBase) ."</td>";
				
				if($prtcharges == 1){
					echo "<td align='center'  valign='top' >". format_currency($AverageChgByRow, $DecimalBase) ."</td>";
					echo "<td align='center'  valign='top' >". format_currency($AverageSubByRow, $DecimalBase) ."</td>";
				}
			}	
			
			echo "<td align='center'  valign='top' >". number_format($LastQtyByRow, $InventoryRMaskqty) ."</td>";
			echo "<td align='center'  valign='top' >". format_currency($LastAmtByRow, $DecimalBase) ."</td>";
			if($prtcharges == 1){
				echo "<td align='center'  valign='top' >". format_currency($LastChgByRow, $DecimalBase) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($LastSubByRow, $DecimalBase) ."</td>";
			}
			
			if ($prtshortage == 1) {
				echo "<td align='center'  valign='top' >". number_format($ShortageQtyByRow, $InventoryRMaskqty) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($ShortageAmtByRow, $DecimalBase) ."</td>";
				if($prtcharges == 1){
					echo "<td align='center'  valign='top' >". format_currency($ShortageChgByRow, $DecimalBase) ."</td>";
					echo "<td align='center'  valign='top' >". format_currency($ShortageSubByRow, $DecimalBase) ."</td>";
				}
			}	
		}
		else {
			if ($prtqty == 1) {
				if ($prtavg == 1)
					echo "<td align='center'  valign='top' >". number_format($AverageQtyByRow, $InventoryRMaskqty) ."</td>";
					
				echo "<td align='center'  valign='top' >". number_format($LastQtyByRow, $InventoryRMaskqty) ."</td>";
				
				if ($prtshortage == 1)
					echo "<td align='center'  valign='top' >". number_format($ShortageQtyByRow, $InventoryRMaskqty) ."</td>";
			}
			if ($prtamt == 1) {
				if ($prtavg == 1)
					echo "<td align='center'  valign='top' >". format_currency($AverageAmtByRow, $DecimalBase) ."</td>";
					
				echo "<td align='center'  valign='top' >". format_currency($LastAmtByRow, $DecimalBase) ."</td>";
				
				if ($prtshortage == 1)
					echo "<td align='center'  valign='top' >". format_currency($ShortageAmtByRow, $DecimalBase) ."</td>";
			}
		}	
	}


	if ($prtqtyPO == 1)
		echo "<td align='center' valign='top' >". number_format($rows[9], $InventoryRMaskqty) ."</td>";
		
	if ($showdetail == 1) {		
		if ($prtcost == 1 && $fi_showcostprice == 1)
			echo "<td align='center' valign='top' >". format_currency($rows[11], $DecimalBase) ."</td>";
			
		$priceoptions = explode(',', $sellprices);
		$j = 12;
		foreach($priceoptions as $price) {
			
			$priceaccess = 0;
			if (($price == 1 && $FI_ItemSelling1 == 1) || ($price == 2 && $FI_ItemSelling2 == 1) || 
				($price == 3 && $FI_ItemSelling3 == 1) || ($price == 4 && $FI_ItemSelling4 == 1) ||
				($price == 5 && $FI_ItemSelling5 == 1) ) $priceaccess = 1;

			if ($prtprice == 1 && $priceaccess == 1 && $price != 0)
				echo "<td align='center' valign='top' >". format_currency($rows[$j], $DecimalBase) ."</td>";
			
		if($price != 0)
			$j = $j + 1;	
		}	
	}

	echo "	  </tr>";
		
echo"	</tr></td>"; 
}
//echo"	</table>";

// Display Totals By Group	
if ($MasterByCode != '' && $showdetail == 1) {
		    
	echo "<tr>";
	echo "   <td colspan='3'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	echo "  <tr><td colspan='3'>";

	
	$StyleClass  = 'totals';
	$TotalsLabel = 'Total by '.$MasterByLabel;
	
	DisplayTotals($period, $vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $fromdate, $todate, $prtqtyexist, $prtqtySO, $prtqtyPO, $prtqty, $prtprice, $prtamt, $fi_showcostprice, $prtcost, $sellprices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $showdetail, $prtavg, $prtshortage, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass, $prtgroup, $prtsubgroup, $prtcategory, $prtcolor, $prtsize, $prtcharges);		

	echo"	</td></tr>";
	echo "<tr><td colspan='3'>&nbsp;</td></tr>";	
			
}


// Display Totals By Report			
echo "<tr>";
echo "   <td colspan='29'><hr width='100%' color='black' size='1'></td>";
echo "</tr>";
echo "  <tr style='background-color: #F0F0F0;'><td colspan='3'>";


$StyleClass  = 'totals';
$TotalsLabel = 'Totals';
DisplayTotals($period, $vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $fromdate, $todate, $prtqtyexist, $prtqtySO, $prtqtyPO, $prtqty, $prtprice, $prtamt, $fi_showcostprice, $prtcost, $sellprices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $showdetail, $prtavg, $prtshortage, $ArrayTotalByPeriod, $DecimalBase, $TotalsLabel, $StyleClass, $prtgroup, $prtsubgroup, $prtcategory, $prtcolor, $prtsize, $prtcharges);	

echo"	</td></tr>";
echo "</td></tr>";

echo "</table>";
	


function CreateTableStructure($PPeriod, $PFromYear, $PToYear, $PFromMonth, $PToMonth, $PFromDate, $PToDate, $PPrtQtyExist, $PPrtQtySO, $PPrtQtyPO, $PPrtQty, $PPrtPrice, $PPrtAmt, $FI_ShowCostPrice, $PPrtCost, $PSellPrices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $PShowDetail, $PPrtAvg, $PPrtShortage, $PPrtGroup, $PPrtSubGroup, $PPrtCategory, $PPrtColor, $PPrtSize, $PPrtCharges) {

	echo "    
				<col width=120>
				<col width=300>
				<col width=50>";
	
	if ($PPrtGroup == 1)
		echo "<col width=100>";	
	if ($PPrtSubGroup == 1)
		echo "<col width=120>";	
	if ($PPrtCategory == 1)
		echo "<col width=100>";	
	if ($PPrtColor == 1)
		echo "<col width=80>";	
	if ($PPrtSize == 1)
		echo "<col width=80>";
				
	if ($PPrtQtyExist == 1)
		echo "<col width=80>";	
	if ($PPrtQtySO == 1)
		echo "<col width=120>";		 
	if ($PPrtQtyExist == 1 && $PPrtQtySO == 1)	
		echo "<col width=90>";			

	if ($PPeriod == 1 ) {
		$dayscount = dateDiff($PFromDate, $PToDate);
		for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
			if ($PPrtQty == 1)    echo" <col width=100> ";
			if ($PPrtAmt == 1)    echo" <col width=120>";
			if ($PPrtCharges == 1) {
				echo" <col width=120>";
				echo" <col width=120>";
			}
		}
	}
	else if ($PPeriod == 2 ) {
		for ( $y = $PFromYear; $y <= $PToYear; $y += 1) {

			if ($y == $PFromYear && $y == $PToYear) { $vMFrom = $PFromMonth; $vMTo = $PToMonth - 1; }
			else if ($y == $PFromYear) { $vMFrom = $PFromMonth; $vMTo = 12; }
			else if ($y == $PToYear) { $vMFrom = 1; $vMTo = $PToMonth - 1; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				if ($PPrtQty == 1)    echo" <col width=100> ";
				if ($PPrtAmt == 1)    echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}
		}
	}
	else if ($PPeriod == 3 ) {
		if ($PPrtQty == 1)  echo"<col width=100>";
		if ($PPrtAmt == 1)  echo"<col width=120>";
		if ($PPrtCharges == 1) {
			echo" <col width=120>";
			echo" <col width=120>";
		}
	}

	if ($PPeriod == 1 || $PPeriod == 2) {
		if ($PPrtQty == 1 && $PPrtAmt == 1) {
			if ($PPrtAvg == 1) {
				echo" <col width=100>";
				echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}
			
			echo" <col width=100>";
			echo" <col width=120>";
			if ($PPrtCharges == 1) {
				echo" <col width=120>";
				echo" <col width=120>";
			}
			
			if ($PPrtShortage == 1) {
				echo" <col width=100>";
				echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}	
		} else {
			if ($PPrtAvg == 1)
				echo" <col width=80>";
				
			echo" <col width=120>";
			
			if ($PPrtShortage == 1)
				echo" <col width=100>";
		}	
	}


	if ($PPrtQtyPO == 1)
		echo "<col width=120>";
		
	if ($PShowDetail == 1) {		
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)
			echo "<col width=90>";	

		$priceoptions = explode(',', $PSellPrices);
		foreach($priceoptions as $price) {
			$priceaccess = 0;
			if (($price == 1 && $FI_ItemSelling1 == 1) || ($price == 2 && $FI_ItemSelling2 == 1) || 
				($price == 3 && $FI_ItemSelling3 == 1) || ($price == 4 && $FI_ItemSelling4 == 1) ||
				($price == 5 && $FI_ItemSelling5 == 1) || ($price == 6 && $FI_ItemSelling6 == 1)) $priceaccess = 1;

			if ($PPrtPrice == 1 && $priceaccess == 1 && $price != 0)
				echo "<col width=90>";
		}		
	}	

}

function DisplayTotals($PPeriod, $PFromYear, $PToYear, $PFromMonth, $PToMonth, $PFromDate, $PToDate, $PPrtQtyExist, $PPrtQtySO, $PPrtQtyPO, $PPrtQty, $PPrtPrice, $PPrtAmt, $FI_ShowCostPrice, $PPrtCost, $PSellPrices, $FI_ItemSelling1, $FI_ItemSelling2, $FI_ItemSelling3, $FI_ItemSelling4, $FI_ItemSelling5, $FI_ItemSelling6, $PShowDetail, $PPrtAvg, $PPrtShortage, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass, $PPrtGroup, $PPrtSubGroup, $PPrtCategory, $PPrtColor, $PPrtSize, $PPrtCharges) {

	echo "  
				<col width=120>
				<col width=250>
				<col width=50>";
	
	if ($PPrtGroup == 1)
		echo "<col width=100>";	
	if ($PPrtSubGroup == 1)
		echo "<col width=120>";	
	if ($PPrtCategory == 1)
		echo "<col width=100>";	
	if ($PPrtColor == 1)
		echo "<col width=80>";	
	if ($PPrtSize == 1)
		echo "<col width=80>";
		
	if ($PPrtQtyExist == 1)
		echo "<col width=80>";	
	if ($PPrtQtySO == 1)
		echo "<col width=120>";		 
	if ($PPrtQtyExist == 1 && $PPrtQtySO == 1)	
		echo "<col width=90>";			

	if ($PPeriod == 1 ) {
		$dayscount = dateDiff($PFromDate, $PToDate);
		for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
			if ($PPrtQty == 1)    echo" <col width=100> ";
			if ($PPrtAmt == 1)    echo" <col width=120>";
			if ($PPrtCharges == 1) {
				echo" <col width=120>";
				echo" <col width=120>";
			}
		}
	}
	else if ($PPeriod == 2 ) {
		for ( $y = $PFromYear; $y <= $PToYear; $y += 1) {

			if ($y == $PFromYear && $y == $PToYear) { $vMFrom = $PFromMonth; $vMTo = $PToMonth - 1; }
			else if ($y == $PFromYear) { $vMFrom = $PFromMonth; $vMTo = 12; }
			else if ($y == $PToYear) { $vMFrom = 1; $vMTo = $PToMonth - 1; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				if ($PPrtQty == 1)    echo" <col width=100> ";
				if ($PPrtAmt == 1)    echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}
		}
	}
	else if ($PPeriod == 3 ) {
		if ($PPrtQty == 1)  echo"<col width=100>";
		if ($PPrtAmt == 1)  echo"<col width=120>";
		if ($PPrtCharges == 1) {
			echo" <col width=120>";
			echo" <col width=120>";
		}
	}

	if ($PPeriod == 1 || $PPeriod == 2) {
		if ($PPrtQty == 1 && $PPrtAmt == 1) {
			if ($PPrtAvg == 1) {
				echo" <col width=100>";
				echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}
			
			echo" <col width=100>";
			echo" <col width=120>";
			if ($PPrtCharges == 1) {
				echo" <col width=120>";
				echo" <col width=120>";
			}
			
			if ($PPrtShortage == 1) {
				echo" <col width=100>";
				echo" <col width=120>";
				if ($PPrtCharges == 1) {
					echo" <col width=120>";
					echo" <col width=120>";
				}
			}	
		} else {
			if ($PPrtAvg == 1)
				echo" <col width=80>";
				
			echo" <col width=120>";
			
			if ($PPrtShortage == 1)
				echo" <col width=100>";
		}	
	}	

	if ($PPrtQtyPO == 1)
		echo "<col width=120>";
		
	if ($PShowDetail == 1) {	
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)
			echo "<col width=90>";	

		$priceoptions = explode(',', $PSellPrices);
		foreach($priceoptions as $price) {
			$priceaccess = 0;
			if (($price == 1 && $FI_ItemSelling1 == 1) || ($price == 2 && $FI_ItemSelling2 == 1) || 
				($price == 3 && $FI_ItemSelling3 == 1) || ($price == 4 && $FI_ItemSelling4 == 1) ||
				($price == 5 && $FI_ItemSelling5 == 1) || ($price == 6 && $FI_ItemSelling6 == 1)) $priceaccess = 1;

			if ($PPrtPrice == 1 && $priceaccess == 1 && $price != 0)
				echo "<col width=90>";
		}		
	}

	echo"<tr>";
	echo "  <td align='center' valign='top' >&nbsp;</td>";
	echo "  <td align='center' colspan='2' valign='top' >".$PTotalsLabel."</td>";
	
	if ($PPrtGroup == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtSubGroup == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtCategory == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtColor == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtSize == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
		
	if ($PPrtQtyExist == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtQtySO == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
	if ($PPrtQtyExist == 1 && $PPrtQtySO == 1)	
		echo "  <td align='center' valign='top' >&nbsp;</td>";
		
	$j = 0;
	$PTotalQtyByRow      = 0;
	$PTotalAmountByRow   = 0;
	$PTotalChargesByRow  = 0;
	$PTotalSubTotalByRow = 0;
	$PAverageQtyByRow    = 0;
	$PLastQtyByRow       = 0;
	$PShortageQtyByRow   = 0;
	$PAverageAmtByRow    = 0;
	$PLastAmtByRow       = 0;
	$PShortageAmtByRow   = 0;
	$PAverageChgByRow    = 0;
	$PLastChgByRow       = 0;
	$PShortageChgByRow   = 0;
	$PAverageSubByRow    = 0;
	$PLastSubByRow       = 0;
	$PShortageSubByRow   = 0;
		
	if ($PPeriod == 1 ) {
		$dayscount = dateDiff($PFromDate, $PToDate);
		for ( $d = 0; $d <= $dayscount - 1; $d += 1) {
			if ($PPrtQty == 1) {
				echo "<td align='center'  valign='top' >". $PArrayTotal['Qty'][$d] ."</td>";
			}	
			if ($PPrtAmt == 1) {
				echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Amount'][$d], $PDecimalBase) ."</td>";
			}
			
			if ($PPrtCharges == 1) {
				echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Charges'][$d], $PDecimalBase) ."</td>";
				echo "<td align='center' valign='top' >". format_currency($PArrayTotal['SubTotal'][$d], $PDecimalBase) ."</td>";
			}
			
			$PTotalQtyByRow     	  = $PTotalQtyByRow + $PArrayTotal['Qty'][$d];
			$PTotalAmountByRow  	  = $PTotalAmountByRow + $PArrayTotal['Amount'][$d];
			$PTotalChargesByRow  	  = $PTotalChargesByRow + $PArrayTotal['Charges'][$d];
			$PTotalSubTotalByRow  	  = $PTotalSubTotalByRow + $PArrayTotal['SubTotal'][$d];
			
			$j = $j + 1;
		}
		if ($j > 0)	$PAverageQtyByRow = ($PTotalQtyByRow / $j);
		if ($j > 0)	$PAverageAmtByRow = ($PTotalAmountByRow / $j);
		if ($j > 0)	$PAverageChgByRow = ($PTotalChargesByRow / $j);
		if ($j > 0)	$PAverageSubByRow = ($PTotalSubTotalByRow / $j);
		$PLastQtyByRow = $PArrayTotal['Qty'][$d];
		$PLastAmtByRow = $PArrayTotal['Amount'][$d];
		$PLastChgByRow = $PArrayTotal['Charges'][$d];
		$PLastSubByRow = $PArrayTotal['SubTotal'][$d];
		$PShortageQtyByRow = $PAverageQtyByRow - $PLastQtyByRow;
		$PShortageAmtByRow = $PAverageAmtByRow - $PLastAmtByRow;
		$PShortageChgByRow = $PAverageChgByRow - $PLastChgByRow;
		$PShortageSubByRow = $PAverageSubByRow - $PLastSubByRow;
		
	}
	else if ($PPeriod == 2 ) {
		for ( $y = $PFromYear; $y <= $PToYear; $y += 1) {

			if ($y == $PFromYear && $y == $PToYear) { $vMFrom = $PFromMonth; $vMTo = $PToMonth - 1; }
			else if ($y == $PFromYear) { $vMFrom = $PFromMonth; $vMTo = 12; }
			else if ($y == $PToYear) { $vMFrom = 1; $vMTo = $PToMonth - 1; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				if ($PPrtQty == 1) {
					echo "<td align='center'  valign='top' >". $PArrayTotal['Qty'][$y.$m] ."</td>";
				}	
				if ($PPrtAmt == 1) {
					echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Amount'][$y.$m], $PDecimalBase) ."</td>";
				}	
				
				if ($PPrtCharges == 1) {
					echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Charges'][$y.$m], $PDecimalBase) ."</td>";
					echo "<td align='center' valign='top' >". format_currency($PArrayTotal['SubTotal'][$y.$m], $PDecimalBase) ."</td>";
				}
				
				$PTotalQtyByRow     	  = $PTotalQtyByRow + $PArrayTotal['Qty'][$y.$m];
				$PTotalAmountByRow  	  = $PTotalAmountByRow + $PArrayTotal['Amount'][$y.$m];
				$PTotalChargesByRow  	  = $PTotalChargesByRow + $PArrayTotal['Charges'][$y.$m];
				$PTotalSubTotalByRow  	  = $PTotalSubTotalByRow + $PArrayTotal['SubTotal'][$y.$m];
			
				$j = $j + 1;
			}
		}
		
		if ($j > 0)	$PAverageQtyByRow = ($PTotalQtyByRow / $j);
		if ($j > 0)	$PAverageAmtByRow = ($PTotalAmountByRow / $j);
		if ($j > 0)	$PAverageChgByRow = ($PTotalChargesByRow / $j);
		if ($j > 0)	$PAverageSubByRow = ($PTotalSubTotalByRow / $j);
		$PLastQtyByRow = $PArrayTotal['Qty'][$y.$m];
		$PLastAmtByRow = $PArrayTotal['Amount'][$y.$m];
		$PLastChgByRow = $PArrayTotal['Charges'][$y.$m];
		$PLastSubByRow = $PArrayTotal['SubTotal'][$y.$m];
		$PShortageQtyByRow = $PAverageQtyByRow - $PLastQtyByRow;
		$PShortageAmtByRow = $PAverageAmtByRow - $PLastAmtByRow;
		$PShortageChgByRow = $PAverageChgByRow - $PLastChgByRow;
		$PShortageSubByRow = $PAverageSubByRow - $PLastSubByRow;
	}
	else if ($PPeriod == 3 ) {
		if ($PPrtQty == 1) {
			echo "<td align='center'  valign='top' >". $PArrayTotal['Qty'] ."</td>";
		}	
		if ($PPrtAmt == 1) {
			echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Amount'], $PDecimalBase) ."</td>";
		}
		
		if ($PPrtCharges == 1) {
			echo "<td align='center' valign='top' >". format_currency($PArrayTotal['Charges'], $PDecimalBase) ."</td>";
			echo "<td align='center' valign='top' >". format_currency($PArrayTotal['SubTotal'], $PDecimalBase) ."</td>";
		}
	}

	if ($PPeriod == 1 || $PPeriod == 2) {
		if ($PPrtQty == 1 && $PPrtAmt == 1) {
			if ($PPrtAvg == 1) {
				echo "<td align='center'  valign='top' >". number_format($PAverageQtyByRow, 0) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($PAverageAmtByRow, $PDecimalBase) ."</td>";
				if($PPrtCharges == 1){
					echo "<td align='center'  valign='top' >". format_currency($PAverageChgByRow, $PDecimalBase) ."</td>";
					echo "<td align='center'  valign='top' >". format_currency($PAverageSubByRow, $PDecimalBase) ."</td>";
				}
			}
			
			echo "<td align='center'  valign='top' >". number_format($PLastQtyByRow, 0) ."</td>";
			echo "<td align='center'  valign='top' >". format_currency($PLastAmtByRow, $PDecimalBase) ."</td>";
			if($PPrtCharges == 1){
				echo "<td align='center'  valign='top' >". format_currency($PLastChgByRow, $PDecimalBase) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($PLastSubByRow, $PDecimalBase) ."</td>";
			}
			
			if ($PPrtShortage == 1) {
				echo "<td align='center'  valign='top' >". number_format($PShortageQtyByRow, 0) ."</td>";
				echo "<td align='center'  valign='top' >". format_currency($PShortageAmtByRow, $PDecimalBase) ."</td>";
				if($PPrtCharges == 1){
					echo "<td align='center'  valign='top' >". format_currency($PShortageChgByRow, $PDecimalBase) ."</td>";
					echo "<td align='center'  valign='top' >". format_currency($PShortageSubByRow, $PDecimalBase) ."</td>";
				}
			}	
		}
		else {
			if ($PPrtQty == 1) {
				if ($PPrtAvg == 1)
					echo "<td align='center'  valign='top' >". number_format($PAverageQtyByRow, 0) ."</td>";
					
				echo "<td align='center'  valign='top' >". number_format($PLastQtyByRow, 0) ."</td>";
				
				if ($PPrtShortage == 1)
					echo "<td align='center'  valign='top' >". number_format($PShortageQtyByRow, 0) ."</td>";
			}
			if ($PPrtAmt == 1) {
				if ($PPrtAvg == 1)
					echo "<td align='center'  valign='top' >". format_currency($PAverageAmtByRow, $PDecimalBase) ."</td>";
					
				echo "<td align='center'  valign='top' >". format_currency($PLastAmtByRow, $PDecimalBase) ."</td>";
				
				if ($PPrtShortage == 1)
					echo "<td align='center'  valign='top' >". format_currency($PShortageAmtByRow, $PDecimalBase) ."</td>";
			}
		}
	}	

	if ($PPrtQtyPO == 1)
		echo "  <td align='center' valign='top' >&nbsp;</td>";
		
	if ($PShowDetail == 1) {	
		if ($PPrtCost == 1 && $FI_ShowCostPrice == 1)
			echo "  <td align='center' valign='top' >&nbsp;</td>";

		$priceoptions = explode(',', $PSellPrices);
		foreach($priceoptions as $price) {
			$priceaccess = 0;
			if (($price == 1 && $FI_ItemSelling1 == 1) || ($price == 2 && $FI_ItemSelling2 == 1) || 
				($price == 3 && $FI_ItemSelling3 == 1) || ($price == 4 && $FI_ItemSelling4 == 1) ||
				($price == 5 && $FI_ItemSelling5 == 1) || ($price == 6 && $FI_ItemSelling6 == 1)) $priceaccess = 1;

			if ($PPrtPrice == 1 && $priceaccess == 1 && $price != 0)
				echo "  <td align='center' valign='top' >&nbsp;</td>";
		}
	}	

	echo"     </tr>";	
	//echo"	</table>";


}


function format_currency($amount, $DecimalBase) { 

    if($amount < 0) 
        return "(".number_format(abs($amount),$DecimalBase).")"; 
 
    else return number_format($amount, $DecimalBase); 
} 


function getMonth($month){
     return date('M', mktime(0,0,0,$month,1));
}

function showMonthYear($month, $year){
	$vMonthYear = date('M', mktime(0,0,0,$month,1)).'-'.$year;
	
    return $vMonthYear;
}

function showDays($startdate, $numdays, $format='d-M-Y') {
	return date($format, strtotime($startdate) + $numdays*60*60*24);
}

function getMonthDisp($month){
     return date('F', mktime(0,0,0,$month,1));
}
function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}
function addDays($startdate, $numdays, $format='dMY') {
	return date($format, strtotime($startdate) + $numdays*60*60*24 + 10000);
}

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;
}

function GetSQLValueString($theValue, $theType) 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "Null";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;
  }
  return $theValue;
}



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

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

?>