<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}
 function logHtml($content){
     ////////////Debuging purpose //////////////////////////////////////
	 
 
  echo '<script type="text/javascript">console.log("' . $content . '")</script>';
 
 
                           
}	

print <<< HERE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<TITLE> Statement of Items Report </TITLE>
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<style type="text/css">

@page {
	
	
	/* by rod 20/12/2018 remove this section if error occured */
	
	
	
	/*nb remove @page section if not working */

    	size: A4 landscape;

      
	  table {page-break-inside: avoid;} 
	  
	   body {
		  -webkit-transform: scale(1.5);
    -moz-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5);
    transform: scale(1.5);
	 }
	  
}

/*
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: 13px; 
                  font-family:Times-New-Roman;
                }
table.master td.grouplevel1 { font-size: 14px; 
							  font-weight: bold;
                              font-family:Times-New-Roman;
                            }				 									  

h4 { border-top-style: solid; 
	 border-top-color: black; 
	 border-top-width: 2px;
   }
h5 { border-top-style: solid; 
	 border-top-color: black; 
	 border-top-width: 1px;
   }				 
			*/	 

</style>




</HEAD>


HERE;



include("config.inc.php");
include("function.inc.php");
//Set Time Execution For the Report
//ini_set('max_execution_time', $config['ReportTimeExecution']);
set_time_limit(0);

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


if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$querylog="SELECT print as printaccess, language 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);
}


$querylang="select ReportStatementofItemsTitle, PrintedDate, PrintedTime, ReportUser, ReportFilterBy, ReportDate, ReportFrom, ReportTo, ReportExpireDate, ReportCurrency, 
			ReportItem, ReportHeat, ReportGroup, ReportSubGroup, ReportCategory, ReportProject, ReportCostcent, ReportWarehouse, ReportTransferWarehouse, ReportBatchNo,
			ReportTransfer, ReportMovement, ReportRefShortened, ReportDescription, ReportIn, ReportOut, ReportQty, ReportCurr,ReportPrice, ReportTransactionVal, ReportRemainingVal,
			ReportSerial, ReportPrevious
			from ".$_SESSION['dbLabel'].".reportPreview_label 
			where language='$language'";

$resultlang=mysql_query($querylang,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlang)){
   extract($rows);
}

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


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

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

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

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


$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]);

$Language_Session = array();
$Language_Session['PrintedDate'] = $PrintedDate;
$Language_Session['PrintedTime'] = $PrintedTime;
$Language_Session['ReportUser'] = $ReportUser;

$queryLoginStk = "select ifnull(costcent_code,'') costCentCodeStk,strictcostcent strictcostcentStk from ".$config['dbName_log'].".loginstk where user_account = '".$_SESSION['useraccount']."'";
$resultStk=mysql_query($queryLoginStk,$connection) or die(mysql_error());
$rowsStk=mysql_fetch_assoc($resultStk);
extract($rowsStk);


// echo mysql_num_rows($resultStk)."\n";
// echo $queryLoginStk."\n";
// echo $costCentCodeStk."\n";
// echo $strictcostcentStk."\n";
	
print <<< HERE
<table width="100%" border="0" align="left" >

HERE;

	echo "<thead><tr><td align='left'>";
	
	ShowReportHeader($ReportStatementofItemsTitle,'landscape', $connection, $Language_Session);
	
	echo"</td></tr></thead><tbody>";
 



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


$SelectedOptions = "$ReportFilterBy: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> $ReportDate $ReportFrom: ". $fromdate . "  $ReportTo: ". $todate ."<br>";	
if($Module_expiredate==1 && $edatechk == 1)
if ($fromedate != '')      $SelectedOptions .= "-> $ReportExpireDate $ReportFrom: ". $fromedate . "  $ReportTo: ". $toedate ."<br>";	
if ($displaycur != '')    $SelectedOptions .= "-> $ReportCurrency: ". $displaycur ."<br>";	
if ($fromitem != '')      $SelectedOptions .= "-> $ReportItem $ReportFrom: ". $fromitem . "  $ReportTo: ". $toitem ."<br>";

if($Module_Heatno==1 and $vShowHeatno==1)
if ($fromheatno != '')      $SelectedOptions .= "-> $ReportHeat $ReportFrom: ". $fromheatno . "  $ReportTo: ". $toheatno ."<br>";

if ($fromgroup != '')     $SelectedOptions .= "-> $ReportGroup $ReportFrom: ". $fromgroup . "  $ReportTo: ". $togroup ."<br>";
if ($fromsubgroup != '')  $SelectedOptions .= "-> $ReportSubGroup $ReportFrom: ". $fromsubgroup . "  $ReportTo: ". $tosubgroup ."<br>";
if ($fromcategory != '')  $SelectedOptions .= "-> $ReportCategory $ReportFrom: ". $fromcategory . "  $ReportTo: ". $tocategory ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> $ReportProject $ReportFrom: ". $fromproject . "  $ReportTo: ". $toproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> $ReportCostcent $ReportFrom: ". $fromcostcent . "  $ReportTo: ". $tocostcent . "<br>";
if ($fromwarehouse != '') $SelectedOptions .= "-> $ReportWarehouse $ReportFrom: ". $fromwarehouse . "<br>";
if ($towarehouse != '') $SelectedOptions .= "-> $ReportWarehouse $ReportTo: ". $towarehouse . "<br>";
if ($fromtranswh != '')   $SelectedOptions .= "-> $ReportTransferWarehouse $ReportFrom: ". $fromtranswh . "  $ReportTo: ". $totranswh ."<br>";
if ($Module_BatchNo == 1 && $frombatchno != '')
	$SelectedOptions .= "-> $ReportBatchNo $ReportFrom: ". $frombatchno . "  $ReportTo: ". $tobatchno ."<br>";


   
if (empty($fromitem))  $fromitem = 'null';
else   $fromitem = "'".$fromitem."'";   
if (empty($toitem))   $toitem = 'null';
else  $toitem = "'".$toitem."'";    

if (empty($fromheatno))  $fromheatno = 'null';
else   $fromheatno = "'".$fromheatno."'";   
if (empty($toheatno))   $toheatno = 'null';
else  $toheatno = "'".$toheatno."'";      

$fromproject = "".$fromproject;
$toproject = "".$toproject;

if ($fromproject == '')   $fromproject = 'null';
else  $fromproject = "'".$fromproject."'";    
if ($toproject == '')   $toproject = 'null';
else  $toproject = "'".$toproject."'";    

$fromcostcent = "".$fromcostcent;
$tocostcent = "".$tocostcent;

if ($fromcostcent == '')   $fromcostcent = 'null';
else  $fromcostcent = "'".$fromcostcent."'";       
if ($tocostcent == '')   $tocostcent = 'null';
else  $tocostcent = "'".$tocostcent."'";       
   
if (empty($fromgroup))   $fromgroup = 'null';
else  $fromgroup = "'".$fromgroup."'";    
if (empty($togroup))   $togroup = 'null';
else  $togroup = "'".$togroup."'";   
   
if (empty($fromsubgroup))   $fromsubgroup = 'null';
else   $fromsubgroup = "'".$fromsubgroup."'";    
if (empty($tosubgroup))   $tosubgroup = 'null';
else   $tosubgroup = "'".$tosubgroup."'";      


if (empty($fromwarehouse))   $fromwarehouse = 'null';
else   $fromwarehouse = "'".$fromwarehouse."'";    

if (empty($towarehouse))   $towarehouse = 'null';
else   $towarehouse = "'".$towarehouse."'";   
   
if (empty($fromcategory))    $fromcategory = 'null';
else   $fromcategory = "'".$fromcategory."'";     
if (empty($tocategory))    $tocategory = 'null';
else   $tocategory = "'".$tocategory."'";        

if (empty($fromtranswh))    $fromtranswh = 'null';
else   $fromtranswh = "'".$fromtranswh."'";     
if (empty($totranswh))    $totranswh = 'null';
else   $totranswh = "'".$totranswh."'";        
   
if ($frombatchno == '' || $Module_BatchNo != 1)   $frombatchno = 'null';
else  $frombatchno = "'".$frombatchno."'";       
if ($tobatchno == '' || $Module_BatchNo != 1)   $tobatchno = 'null';
else  $tobatchno = "'".$tobatchno."'";  

if (empty($todate))    $lastdate = insertMySQLDate(displayToday());
else   $lastdate = insertMySQLDate($todate);

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


if (empty($fromdate))    $fromdate = 'null';
else   $fromdate = "'".$fromdate."'"; 
if (empty($todate))    $todate = 'null';
else   $todate = "'".$todate."'";
   
if (!empty($fromedate))   $fromedate = explodeword($fromedate);
if (!empty($toedate))     $toedate = explodeword($toedate);  

if (empty($fromedate))    $fromedate = 'null';
else   $fromedate = "'".$fromedate."'"; 
if (empty($toedate))    $toedate = 'null';
else   $toedate = "'".$toedate."'";	
	
if (empty($prtprice))     $prtprice = 0;
if (empty($prtcost))      $prtcost = 0;
if (empty($updmeancost))  $updmeancost = 0;
if (empty($searchserial)) $searchserial = 0;

if ($showTransValue == '') $showTransValue = 0;

if ($Module_BatchNo != 1)
	$showbatch = 0;

print <<<HERE


<tr><Td><table class="report-master" width="100%" border="0" align="center" ><col width=100>
<tr><td>&nbsp;</td>
  <td  valign='top'><b>$SelectedOptions</b></td>
</tr>
<tr height='5'><td colspan='2'><h5></td></tr>
</table></td></tr>
HERE;

echo "<tr><td><table  border='0' width='100%' align='center' class='report-master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
      <col width=80>
	  <col width=70>
      <col width=230>
      <col width=80>
      <col width=60>";
  if($Module_BatchNo == 1 && $showbatch == 1)
	echo "<col width=60>";	  
  if($Module_Heatno==1 and $vShowHeatno==1)
	echo"<col width=60>";
      echo"<col width=60>
	  <col width=60>
	  <col width=60>
	  <col width=60>
	  <col width=50>
	  <col width=100>
	  <col width=20>";
	  if ($showTransValue == 1) echo "<col width=100><col width=100>";
	 if($vShowProject == 1 && $Module_Project == 1)
	  echo"<col width=70>";
	 
	 if($vShowCostcenter == 1 && $Module_Costcenter == 1)
	 echo"<col width=70>";
	 
	 
	echo"<tr>";

	$colspan=4;
	if($vShowProject == 1 && $Module_Project == 1)
		$colspan+= 1;
	if($vShowCostcenter == 1 && $Module_Costcenter == 1)
		$colspan+= 1;
	if ($showTransValue==1) $colspan = $colspan + 2;
	
	echo"<th colspan='4'>&nbsp;</th>
		 <th colspan='2'>$ReportTransfer</th>
		 <th colspan='2'>$ReportMovement</th>
		 <th colspan='$colspan'>&nbsp;</th>
	</tr>";

	
	//moni
	
	if($Module_expiredate==1 && $edatechk == 1)	
	
	echo"<thead><tr><th align='left'>$ReportExpireDate</th>
		 <th >$ReportRefShortened</th>
		 <th >$ReportDescription</th>
		 <th >$ReportWarehouse</th>";
	
	else 
	
	echo"<thead><tr><th align='left'>$ReportDate</th>
		 <th >$ReportRefShortened</th>
		 <th >$ReportDescription</th>
		 <th >$ReportWarehouse</th>";
	if($Module_BatchNo == 1 && $showbatch == 1)	 
		echo"<th>$ReportBatchNo</th>";
	if($Module_Heatno==1 and $vShowHeatno==1)
		echo"<th>$ReportHeat</th>";
			 
		 echo"<th >$ReportFrom</th>
		 <th >$ReportTo</th>
		 <th >$ReportIn</th>
		 <th >$ReportOut</th>
		 <th >$ReportQty</th>";
		 
	if ($prtcost == 1) {	 
		echo" <th >$ReportCurr</th>
			  <th >$ReportPrice</th>
			  <th >&nbsp;</th>";
	} else {
		echo" <th colspan='3'>&nbsp;</th>";
	}
	if ($showTransValue == 1) {
		echo" <th>$ReportTransactionVal</th>";
		echo" <th>$ReportRemainingVal</th>";
	}
	if($vShowProject == 1 && $Module_Project == 1)
		echo" <th >$ReportProject</th> ";	

	if($vShowCostcenter == 1 && $Module_Costcenter == 1)
		echo" <th >$ReportCostcent</th> ";	
$colsp = 12;

if ($Module_Heatno==1 and $vShowHeatno==1) $colsp = $colsp + 1;
if ($Module_BatchNo == 1 && $showbatch == 1) $colsp = $colsp + 1;
if ($showTransValue==1) $colsp = $colsp + 2;
if ($vShowProject==1 and $Module_Project==1) $colsp = $colsp + 1;
if ($vShowCostcenter==1 and $Module_Costcenter==1) $colsp = $colsp + 1;

echo"</tr>
	 <tr height='5'><td colspan=$colsp><h5></td></tr></thead>";
	
 

 
$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 = '';
$SelectedTransaction = 0;

$query = $query." Select upper(ItemCode) as ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
				" QtyOut, QtyIn, ifNull(QtyPrev,0), CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId, ProjectCode, CostCenterCode, Purchasedt_Heatno,ExpireDate, RemainVal, TransVal, batchno, TransId, useracc  ".
				" From ( ";

if (($TransPI == 1 || $TransPR == 1) &&  $Module_Grn == 0) {
	
	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId , ProjectCode, CostCenterCode, Purchasedt_Heatno,ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId ,useracc".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select PurchasesDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Purchases.Purchase_Reference As TransReference, Date_Format(Purchases.Purchase_Date,'%d/%m/%Y') As TransDate, ".
					" Purchases.Purchase_Date As OrderDate, Concat(if(Purchases.Journal_Type='PI','PURCHASE :','RETURN PURCHASE :'), Suppliers.Ledger_Name, ' ', if(Purchases.Purchase_Remark is null,'',Purchases.Purchase_Remark)) As TransDescription, ".
					" Purchases.Journal_Type As TransType, PurchasesDt.PurchaseDt_ID As TransDtId, PurchasesDt.Warehouse_Code As WarehouseCode,PurchasesDt.Project_Code As ProjectCode,PurchasesDt.CostCent_Code As CostCenterCode, ".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" if(Purchases.Journal_Type='PI', ifNull(PurchasesDt.PurchaseDt_Quantity,0), (-1)*ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As TransQty, ".
					" if(Purchases.Journal_Type='PR', ifNull(Abs(PurchasesDt.PurchaseDt_Quantity),0), Null) As QtyOut, ".
					" if(Purchases.Journal_Type='PI', ifNull(PurchasesDt.PurchaseDt_Quantity,0), Null) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." if(Purchases.Journal_Type='PI', 1, 2) As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', Purchases.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(PurchasesDt.Item_Code, '".$lastdate."', 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) TransPrice ";
					else
						$query= $query." if($PurchaseTTC=1, if(upper($curr)='".$Base1."',PurchasesDt.PurchaseDt_PriceTTCBase1,if(upper($curr)='".$Base2."',PurchasesDt.PurchaseDt_PriceTTCBase2, PurchasesDt.PurchaseDt_PriceTTC)),  ".
										" if(upper($curr)='".$Base1."',PurchaseDt_PriceBase1 - (PurchaseDt_DiscountBase1/PurchaseDt_Quantity) - (PurchaseDt_PriceBase1*PurchaseDt_DiscountPer/100) + (PurchaseDt_ChargesBase1/PurchaseDt_Quantity),if(upper($curr)='".$Base2."',PurchaseDt_PriceBase2 - (PurchaseDt_DiscountBase2/PurchaseDt_Quantity) - (PurchaseDt_PriceBase2*PurchaseDt_DiscountPer/100) + (PurchaseDt_ChargesBase2/PurchaseDt_Quantity), PurchaseDt_Price - (PurchaseDt_DiscountAmount/PurchaseDt_Quantity) - (PurchaseDt_Price*PurchaseDt_DiscountPer/100) + (PurchaseDt_Charges/PurchaseDt_Quantity)))) As TransPrice  ";
									//    " if(upper($curr)='".$Base1."',PurchasesDt.PurchaseDt_PriceBase1+(PurchasesDt.PurchaseDt_ChargesBase1/PurchasesDt.PurchaseDt_Quantity),if(upper($curr)='".$Base2."',PurchasesDt.PurchaseDt_PriceBase2+(PurchasesDt.PurchaseDt_ChargesBase2/PurchasesDt.PurchaseDt_Quantity), PurchasesDt.PurchaseDt_Price+(PurchasesDt.PurchaseDt_Charges/PurchasesDt.PurchaseDt_Quantity)))) As TransPrice  ";

	$query= $query. " ,Purchasedt_Heatno,Date_Format(Purchasesdt.PurchaseDt_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(PurchasesDt.Item_Code, '".$lastdate."', 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) as meanPrice
					  , ifnull(QtyExistsWSorder(PurchasesDt.Item_Code, PurchasesDt.Warehouse_Code, '".$lastdate."', 0, 'PI', '', ''),0) QtyExists, PurchaseDt_BatchNo as batchno, Purchases.Purchase_ID as TransId,Purchases.user_account as useracc ";
	$query= $query. " From PurchasesDt  ".
					" Inner Join Purchases on PurchasesDt.Purchase_ID = Purchases.Purchase_ID ".
					" Inner Join Items on PurchasesDt.Item_Code = Items.Item_Code ".
					" Inner Join Suppliers on Purchases.Supplier_Code = Suppliers.Ledger_Number ";

	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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = PurchasesDt.PurchaseDt_ID And PurchasesSerialNo.Journal_Type = Purchases.Journal_Type ";
	
	if ($searchserial == 0) {
		$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(". $fromdate.",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')) ";
			if($strictcostcentStk == '1'){
				$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
			}
		 $query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) ".
  						"               And ifNull(". $towarehouse .",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 QQtyPrev on PurchasesDt.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (Purchases.Purchase_Reference Is Not Null And Purchases.Purchase_Reference != '')  ";
					//" 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'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(PurchaseDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(PurchaseDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(PurchaseDt_ExpireDate,'%Y-%m-%d'))  ";
    else $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'))  ";	

	
	if ($searchserial == 0)	
		$query= $query." And PurchasesDt.Item_Code between ifNull(".$fromitem.",PurchasesDt.Item_Code) and ifNull(". $toitem.",PurchasesDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";	
					
	
	$query= $query." And Ifnull(PurchasesDt.purchasedt_heatno,-1) between ifNull(".$fromheatno.",Ifnull(PurchasesDt.purchasedt_heatno,-1)) and ifNull(". $toheatno.",Ifnull(PurchasesDt.purchasedt_heatno,-1)) ";
	$query .= " and ifnull(PurchaseDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(PurchaseDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(PurchaseDt_BatchNo,'')) ";
	
	$query= $query. " 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.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'))  ";					
					//" And ifNull(PurchasesDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(PurchasesDt.warehouse_code,'-1')),'%')  ";
				
				//if ($Module_Grn == 0) {
					if ($TransPI==1 && $TransPR==1) $query= $query." 	And Purchases.Journal_Type in ('PI','PR') ";
					else if ($TransPI==1 && $TransPR==0) $query= $query."	And Purchases.Journal_Type in ('PI') ";
					else if ($TransPI==0 && $TransPR==1) $query= $query."	And Purchases.Journal_Type in ('PR') ";
				//} else {
					//if ($TransPR==1) $query= $query."	And Purchases.Journal_Type 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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}

if (($TransPI == 1 || $TransPR == 1) &&  $Module_Grn == 1) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";
	
	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId, ProjectCode, CostCenterCode, Purchasedt_Heatno,ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId ,useracc".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select GrnPurchasesDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, GrnPurchases.Purchase_Reference As TransReference, Date_Format(GrnPurchases.Purchase_Date,'%d/%m/%Y') As TransDate, ".
					" GrnPurchases.Purchase_Date As OrderDate, Concat(if(GrnPurchases.Journal_Type='PI','GRN :','RETURN GRN :'), Suppliers.Ledger_Name, ' ', if(GrnPurchases.Purchase_Remark is null,'',GrnPurchases.Purchase_Remark)) As TransDescription, ".
					" GrnPurchases.Journal_Type As TransType, GrnPurchasesDt.PurchaseDt_ID As TransDtId, GrnPurchasesDt.Warehouse_Code As WarehouseCode,GrnPurchasesDt.Project_Code As ProjectCode,GrnPurchasesDt.CostCent_Code As CostCenterCode, ".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" if(GrnPurchases.Journal_Type='PI', ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0), (-1)*ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0)) As TransQty, ".
					" if(GrnPurchases.Journal_Type='PR', ifNull(Abs(GrnPurchasesDt.PurchaseDt_Quantity),0), Null) As QtyOut, ".
					" if(GrnPurchases.Journal_Type='PI', ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0), Null) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." if(GrnPurchases.Journal_Type='PI', 1, 2) As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', GrnPurchases.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(GrnPurchasesDt.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), GrnPurchases.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) TransPrice ";
					else
						$query= $query." if($PurchaseTTC=1, if(upper($curr)='".$Base1."',GrnPurchasesDt.PurchaseDt_PriceTTCBase1,if(upper($curr)='".$Base2."',GrnPurchasesDt.PurchaseDt_PriceTTCBase2, GrnPurchasesDt.PurchaseDt_PriceTTC)),  ".
									   " if(upper($curr)='".$Base1."',GrnPurchasesDt.PurchaseDt_PriceBase1,if(upper($curr)='".$Base2."',GrnPurchasesDt.PurchaseDt_PriceBase2, GrnPurchasesDt.PurchaseDt_Price))) As TransPrice  ";

	$query= $query. " , Purchasedt_Heatno,Date_Format(GrnPurchasesDt.PurchaseDt_ExpireDate,'%d/%m/%Y') As ExpireDate ";
	$query= $query. " , ifNull(MeanCostCur(GrnPurchasesDt.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), GrnPurchases.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) as meanPrice
					  , ifnull(QtyExistsWSorder(GrnPurchasesDt.Item_Code, GrnPurchasesDt.Warehouse_Code, '".$lastdate."', 0, 'PI', '', ''),0) QtyExists, PurchaseDt_BatchNo as batchno, GrnPurchases.Purchase_ID as TransId ,GrnPurchases.user_account as useracc";
	$query= $query. " From GrnPurchasesDt  ".
					" Inner Join GrnPurchases on GrnPurchasesDt.Purchase_ID = GrnPurchases.Purchase_ID ".
					" Inner Join Items on GrnPurchasesDt.Item_Code = Items.Item_Code ".
					" Inner Join Suppliers on GrnPurchases.Supplier_Code = Suppliers.Ledger_Number ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on GrnPurchases.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on GrnPurchases.Costcent_Code like concat(Q5.costcent_code,'%') ";		 
		
	if ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = GrnPurchasesDt.PurchaseDt_ID And PurchasesSerialNo.Journal_Type = GrnPurchases.Journal_Type ";

	if ($searchserial == 0) {	
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1'))  ".
						"				And ifNull(". $towarehouse .",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 QQtyPrev on GrnPurchasesDt.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (GrnPurchases.Purchase_Reference Is Not Null And GrnPurchases.Purchase_Reference != '')  ";
					//" And Date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(PurchaseDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(PurchaseDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(PurchaseDt_ExpireDate,'%Y-%m-%d'))  ";
	else $query= $query." And Date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(GrnPurchases.Purchase_Date,'%Y-%m-%d'))  ";				
	
	if ($searchserial == 0)	
		$query= $query." And GrnPurchasesDt.Item_Code between ifNull(".$fromitem.",GrnPurchasesDt.Item_Code) and ifNull(". $toitem.",GrnPurchasesDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";	
	
	$query= $query." And Ifnull(GrnPurchasesDt.purchasedt_heatno,-1) between ifNull(".$fromheatno.",Ifnull(GrnPurchasesDt.purchasedt_heatno,-1)) and ifNull(". $toheatno.",Ifnull(GrnPurchasesDt.purchasedt_heatno,-1)) ";
	
	$query .= " and ifnull(PurchaseDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(PurchaseDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(PurchaseDt_BatchNo,'')) ";
				
	$query= $query.	" 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(GrnPurchases.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(GrnPurchases.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(GrnPurchases.Project_Code,'-1')) ".
					" And ifNull(GrnPurchases.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(GrnPurchases.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(GrnPurchases.Costcent_Code,'-1')) ".
					" And ifNull(GrnPurchasesDt.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(GrnPurchasesDt.warehouse_code,'-1')) and ifNull(". $towarehouse .",ifNull(GrnPurchasesDt.warehouse_code,'-1'))  ";
					//" And ifNull(GrnPurchasesDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(GrnPurchasesDt.warehouse_code,'-1')),'%')  ";
				
				
				if ($TransPI==1 && $TransPR==1) $query= $query." 	And GrnPurchases.Journal_Type in ('PI','PR') ";
				else if ($TransPI==1 && $TransPR==0) $query= $query."	And GrnPurchases.Journal_Type in ('PI') ";
				else if ($TransPI==0 && $TransPR==1) $query= $query."	And GrnPurchases.Journal_Type in ('PR') ";
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And GrnPurchasesDt.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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}

if ($TransSI == 1 || $TransSR == 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId, ProjectCode, CostCenterCode, DeliveryDt_heatNo  as Purchasedt_Heatno,ExpireDate,  meanPrice*QtyExists as RemainVal,  ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId ,  useracc ".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select DeliveryDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Deliveries.Delivery_Reference As TransReference, ".
					" Date_Format(Deliveries.Delivery_Date,'%d/%m/%Y') As TransDate, Deliveries.Delivery_Date As OrderDate,  ".
					" Concat(if(Deliveries.Journal_Type='DI',if($Module_Delivery=1,'DELIVERY :','SALES :'),if($Module_Delivery=1,'RETURN DELIVERY :','RETURN SALES :')), Clients.Ledger_Name, ' ', if(Deliveries.Delivery_Remark is null,'',Deliveries.Delivery_Remark)) As TransDescription, ".
					" Deliveries.Journal_Type As TransType, DeliveryDt.DeliveryDt_ID As TransDtId, DeliveryDt.Warehouse_Code As WarehouseCode,DeliveryDt.Project_Code As ProjectCode,DeliveryDt.CostCent_Code As CostCenterCode,  ".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" if(Deliveries.Journal_Type='DI', ifNull(DeliveryDt.DeliveryDt_Quantity,0), (-1)*ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As TransQty, ".
					" if(Deliveries.Journal_Type='DI', ifNull(DeliveryDt.DeliveryDt_Quantity,0), Null) As QtyOut, ".
					" if(Deliveries.Journal_Type='DR', ifNull(Abs(DeliveryDt.DeliveryDt_Quantity),0), Null) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." if(Deliveries.Journal_Type='DI', 5, 6) As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', Deliveries.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(DeliveryDt.Item_Code, '".$lastdate."', 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) TransPrice ";
					else
						$query= $query." if($Module_Delivery=0,if($SalesTTC=1, if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceTTCBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceTTCBase2, DeliveryDt.DeliveryDt_PriceTTC)),  ".
									   " if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceBase2, DeliveryDt.DeliveryDt_Price))), ".
									   " if(upper($curr)='".$Base1."',DeliveryDt.SaleDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.SaleDt_PriceBase2, DeliveryDt.SaleDt_Price))) As TransPrice  ";
					
	$query= $query. " , DeliveryDt_heatNo,Date_Format(Deliverydt.Deliverydt_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(DeliveryDt.Item_Code, '".$lastdate."', 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) as meanPrice
					  , ifnull(QtyExistsWSorder(DeliveryDt.Item_Code, DeliveryDt.Warehouse_Code, '".$lastdate."', 0, 'DI', '', ''),0) QtyExists, DeliveryDt_BatchNo as batchno, Deliveries.Delivery_ID as TransId,  Deliveries.user_account as useracc";
	$query= $query. " From DeliveryDt  ".
					" Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
					" Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
					" Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ";

	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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = DeliveryDt.DeliveryDt_ID And PurchasesSerialNo.Journal_Type = Deliveries.Journal_Type ";
					   
	if ($searchserial == 0) {				   
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on DeliveryDt.Item_Code = QQtyPrev.Item_Code   ";
	}				
	$query= $query.	" Where (Deliveries.Delivery_Reference Is Not Null And Deliveries.Delivery_Reference != '')  ";
					//" 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'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(DeliveryDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(DeliveryDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(DeliveryDt_ExpireDate,'%Y-%m-%d'))  ";
	else $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'))  ";	
	
	if ($searchserial == 0)	
		$query= $query." And DeliveryDt.Item_Code between ifNull(".$fromitem.",DeliveryDt.Item_Code) and ifNull(". $toitem.",DeliveryDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";
	
	$query= $query." And Ifnull(DeliveryDt.DeliveryDt_heatno,-1) between ifNull(".$fromheatno.",Ifnull(DeliveryDt.DeliveryDt_heatno,-1)) and ifNull(". $toheatno.",Ifnull(DeliveryDt.DeliveryDt_heatno,-1)) ";
	
	$query .= " and ifnull(DeliveryDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(DeliveryDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(DeliveryDt_BatchNo,'')) ";
				
	$query= $query.	" 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(Deliveries.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Deliveries.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Deliveries.Project_Code,'-1')) ";
			if($strictcostcentStk == '1'){
				$query= $query." And Deliveries.Costcent_Code = '".$costCentCodeStk."' ";
			}
	$query= $query." And ifNull(Deliveries.Costcent_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Deliveries.Costcent_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Deliveries.Costcent_Code,'-1')) ".
					" And ifNull(DeliveryDt.warehouse_code,'-1') = ifNull(". $fromwarehouse .",ifNull(DeliveryDt.warehouse_code,'-1'))  ";
					
				
				
				if ($TransSI==1 && $TransSR==1) $query= $query." 	And Deliveries.Journal_Type in ('DI','DR') ";
				else if ($TransSI==1 && $TransSR==0) $query= $query."	And Deliveries.Journal_Type in ('DI') ";
				else if ($TransSI==0 && $TransSR==1) $query= $query."	And Deliveries.Journal_Type 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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}


if ($TransTR == 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId, ProjectCode, CostcenterCode, TransferDt_heatNo  as Purchasedt_Heatno, ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId, useracc ".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select TransferDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Transfer.Transfer_Reference As TransReference, Date_Format(Transfer.Transfer_Date,'%d/%m/%Y') As TransDate, ".
					" Transfer.Transfer_Date As OrderDate, Concat('TRANSFER : ', if(Transfer.Transfer_Remark is null,'',Transfer.Transfer_Remark)) As TransDescription, ".
					" 'TR' As TransType, TransferDt.TransferDt_ID As TransDtId
					, Concat('F: ',TransferDt_WarehouseFrom,' T: ',TransferDt_WarehouseTo) As WarehouseCode
					, Concat('F: ',Transferdt.Project_Code1,' T: ',Transferdt.Project_Code2) As ProjectCode, Concat('F: ',Transferdt.COSTCENT_CODE,' T: ',Transferdt.ToCostcent_Code) As CostcenterCode, ".
					" if (($fromwarehouse Is Null) or (TransferDt_WarehouseFrom between $fromwarehouse and $towarehouse) ,ifNull(TransferDt.TransferDt_Quantity,0), 0) As QtyTransferFrom, ".
					" if (($fromwarehouse Is Null) or (TransferDt_WarehouseTo between $fromwarehouse and $towarehouse) , ifNull(TransferDt.TransferDt_Quantity,0), 0) As QtyTransferTo, ".
					" ifNull(TransferDt.TransferDt_Quantity,0) As TransQty, Null As QtyOut, Null As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 3 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', transfer.CurencyCode)) As CurrencyCode, 0 As TransPrice, TransferDt_heatNo,Null as ExpireDate ".
					" , 0 as meanPrice
					  , 0 as QtyExists, TransferDt_BatchNo as batchno, Transfer.Transfer_ID as TransId ,transfer.user_Account as useracc".
					" From TransferDt  ".
					" Inner Join Transfer on TransferDt.Transfer_ID = Transfer.Transfer_ID ".
					" Inner Join Items on TransferDt.Item_Code = Items.Item_Code ";

	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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = TransferDt.TransferDt_ID And PurchasesSerialNo.Journal_Type IN ('TR','TRT') ";
	
	if ($searchserial == 0) {
		$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(". $fromdate.",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')) ";
						
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on TransferDt.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (Transfer.Transfer_Reference Is Not Null And Transfer.Transfer_Reference != '')  ".
					" 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'))  ";
	//if($Module_expiredate==1 && $edatechk == 1)	
	//$query= $query." And Date_format(TransferDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(TransferDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(TransferDt_ExpireDate,'%Y-%m-%d'))  ";
					
	if ($searchserial == 0)	
		$query= $query." And TransferDt.Item_Code between ifNull(".$fromitem.",TransferDt.Item_Code) and ifNull(". $toitem.",TransferDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";
	

	$query= $query." And Ifnull(TransferDt.TransferDt_heatno,-1) between ifNull(".$fromheatno.",Ifnull(TransferDt.TransferDt_heatno,-1)) and ifNull(". $toheatno.",Ifnull(TransferDt.TransferDt_heatno,-1)) ";

	$query .= " and ifnull(TransferDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(TransferDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(TransferDt_BatchNo,'')) ";
	
	$query= $query.	" 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')) ";
			if($strictcostcentStk == '1'){
				$query= $query." And Transfer.Costcenter_Code = '".$costCentCodeStk."' ";
			}
	$query= $query.	" And ifNull(TransferDt.TransferDt_WarehouseFrom,'-1') = ifNull(". $fromtranswh .",ifNull(TransferDt.TransferDt_WarehouseFrom,'-1'))  ".
					" And ifNull(TransferDt.TransferDt_WarehouseTo,'-1') = ifNull(". $totranswh .",ifNull(TransferDt.TransferDt_WarehouseTo,'-1'))  ".
					
					" And (( ifNull(TransferDt.TransferDt_WarehouseFrom,'-1') between ifNull(". $fromwarehouse .",ifNull(TransferDt.TransferDt_WarehouseFrom,'-1')) and ifNull(". $towarehouse .",ifNull(TransferDt.TransferDt_WarehouseFrom,'-1')) ) or   ".
					" 	   ( ifNull(TransferDt.TransferDt_WarehouseTo,'-1') between ifNull(". $fromwarehouse .",ifNull(TransferDt.TransferDt_WarehouseTo,'-1')) and 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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}

if ($TransAD == 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId ,ProjectCode, CostcenterCode, AdjustmentDt_HeatNo  as Purchasedt_Heatno,ExpireDate,  meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId ,useracc".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select AdjustmentDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Adjustment.Adjustment_Reference As TransReference, Date_Format(Adjustment.Adjustment_Date,'%d/%m/%Y') As TransDate, ".
					" Adjustment.Adjustment_Date As OrderDate, Concat('ADJUSTMENT : ', if(Adjustment.Adjustment_Remak is null,'',Adjustment.Adjustment_Remak)) As TransDescription, ".
					" AdjustmentDt.Journal_Type As TransType, AdjustmentDt.AdjustmentDt_ID As TransDtId, AdjustmentDt.Warehouse_Code As WarehouseCode,AdjustmentDt.Project_Code As ProjectCode,AdjustmentDt.Costcent_Code As CostcenterCode, ".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" if(AdjustmentDt.Journal_Type='AI', ifNull(AdjustmentDt.AdjustmentDt_Quantity,0), ifNull(AdjustmentDt.AdjustmentDt_Quantity,0)) As TransQty, ".
					" if(AdjustmentDt.Journal_Type='AR', Abs(ifNull(AdjustmentDt.AdjustmentDt_Quantity,0)), Null) As QtyOut, ".
					" if(AdjustmentDt.Journal_Type='AI', ifNull(AdjustmentDt.AdjustmentDt_Quantity,0), Null) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 8 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', Adjustment.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(AdjustmentDt.Item_Code, '".$lastdate."', 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) TransPrice ";
					else
						$query= $query." if(upper($curr)='".$Base1."',AdjustmentDt.AdjustmentDt_PriceBase1,if(upper($curr)='".$Base2."',AdjustmentDt.AdjustmentDt_PriceBase2, AdjustmentDt.AdjustmentDt_Price)) As TransPrice ";
									   
				   
	$query= $query. " , AdjustmentDt_HeatNo ,Date_Format(adjustmentdt.adjustmentdt_ExpireDate,'%d/%m/%Y') As ExpireDate ";
	$query= $query. " , ifNull(MeanCostCur(AdjustmentDt.Item_Code, '".$lastdate."', 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)  as meanPrice
					  , ifnull(QtyExistsWSorder(AdjustmentDt.Item_Code, AdjustmentDt.Warehouse_Code, '".$lastdate."', 0, '', '', ''),0) QtyExists, AdjustmentDt_BatchNo as batchno, Adjustment.Adjustment_ID as TransId ,Adjustment.user_account as useracc";
	$query= $query. " From AdjustmentDt  ".
					" Inner Join Adjustment on AdjustmentDt.Adjustment_ID = Adjustment.Adjustment_ID ".
					" Inner Join Items on AdjustmentDt.Item_Code = Items.Item_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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = AdjustmentDt.AdjustmentDt_ID And PurchasesSerialNo.Journal_Type = AdjustmentDt.Journal_Type ";
		
	if ($searchserial == 0) {	
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on AdjustmentDt.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (Adjustment.Adjustment_Reference Is Not Null And Adjustment.Adjustment_Reference != '')  ";
					//" 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'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(AdjustmentDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(AdjustmentDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(AdjustmentDt_ExpireDate,'%Y-%m-%d'))  ";
	else $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'))  ";	
	
	if ($searchserial == 0)	
		$query= $query." And AdjustmentDt.Item_Code between ifNull(".$fromitem.",AdjustmentDt.Item_Code) and ifNull(". $toitem.",AdjustmentDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";	
	

	$query= $query." And ifnull(AdjustmentDt.AdjustmentDt_heatno,-1) between ifNull(".$fromheatno.",ifnull(AdjustmentDt.AdjustmentDt_heatno,-1)) and ifNull(". $toheatno.",ifnull(AdjustmentDt.AdjustmentDt_heatno,-1)) ";

	$query .= " and ifnull(AdjustmentDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(AdjustmentDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(AdjustmentDt_BatchNo,'')) ";
				
	$query= $query.	" 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')) ";
			if($strictcostcentStk == '1'){
			 $query= $query." And Adjustment.Costcent_Code = '".$costCentCodeStk."' ";
			}
	$query= $query.	" And ifNull(AdjustmentDt.warehouse_code,'-1') between  ifNull(". $fromwarehouse .",ifNull(AdjustmentDt.warehouse_code,'-1')) and  ifNull(". $towarehouse .",ifNull(AdjustmentDt.warehouse_code,'-1'))  ";
					//" And ifNull(AdjustmentDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(AdjustmentDt.warehouse_code,'-1')),'%')  ";
				
				
	  
				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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}



if ($TransPD == 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId, ProjectCode, CostcenterCode, ProductionDt_HeatNo as Purchasedt_Heatno,ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId, useracc ".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select ProductionDt.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Production.Production_Reference As TransReference, Date_Format(Production.Production_Date,'%d/%m/%Y') As TransDate, ".
					" Production.Production_Date As OrderDate, Concat('PRODUCTION OUT : ', if(Production.Production_Remark is null,'',Production.Production_Remark)) As TransDescription, ".
					" 'PDT' As TransType, ProductionDt.ProductionDt_ID As TransDtId, ProductionDt.Warehouse_Code As WarehouseCode,ProductionDt.Project_Code As ProjectCode,ProductionDt.Costcenter_Code As CostcenterCode, ".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" (-1)*ifNull(ProductionDt.ProductionDt_Quantity,0) As TransQty, ".
					" ifNull(ProductionDt.ProductionDt_Quantity,0) As QtyOut, Null As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 7 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', Production.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(ProductionDt.Item_Code, '".$lastdate."', 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) TransPrice ";
					else
						$query= $query." if(upper($curr)='".$Base1."',ProductionDt.ProductionDt_CostBase1,if(upper($curr)='".$Base2."',ProductionDt.ProductionDt_CostBase2, ProductionDt.ProductionDt_Cost)) As TransPrice ";
						
				   
	$query= $query. " ,ProductionDt_HeatNo,Date_Format(ProductionDt.ProductionDt_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(ProductionDt.Item_Code, '".$lastdate."', 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)  as meanPrice
				      , ifnull(QtyExistsWSorder(ProductionDt.Item_Code, ProductionDt.Warehouse_Code, '".$lastdate."', 0, 'DI', '', ''),0) QtyExists, ProductionDt_BatchNo as batchno, Production.Production_ID as TransId,production.user_account as useracc ";
	$query= $query. " From ProductionDt  ".
					" Inner Join Production on ProductionDt.Production_ID = Production.Production_ID ".
					" Inner Join Items on ProductionDt.Item_Code = Items.Item_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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = ProductionDt.ProductionDt_ID And PurchasesSerialNo.Journal_Type = 'PDT' ";
	
	if ($searchserial == 0) {	
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on ProductionDt.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (Production.Production_Reference Is Not Null And Production.Production_Reference != '')  ";
					//" 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'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(ProductionDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(ProductionDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(ProductionDt_ExpireDate,'%Y-%m-%d'))  ";
	else $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 .= " and ifnull(ProductionDt_BatchNo,'') between ifnull(".$frombatchno.",ifnull(ProductionDt_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(ProductionDt_BatchNo,'')) ";
				
	if ($searchserial == 0)	
		$query= $query." And ProductionDt.Item_Code between ifNull(".$fromitem.",ProductionDt.Item_Code) and ifNull(". $toitem.",ProductionDt.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";		
	
	
	$query= $query." And IfNull(ProductionDt.ProductionDt_heatno,-1) between ifNull(".$fromheatno.",IfNull(ProductionDt.ProductionDt_heatno,-1)) and ifNull(". $toheatno.",IfNull(ProductionDt.ProductionDt_heatno,-1)) ";

			if($strictcostcentStk == '1'){
			 $query= $query." And ProductionDt.Costcenter_Code = '".$costCentCodeStk."' ";
			}
	
	$query= $query.	" 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')) ";
	if($strictcostcentStk == '1'){
		$query= $query." And Production.Costcenter_Code = '".$costCentCodeStk."' ";
	}
	$query= $query.	" And ifNull(ProductionDt.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(ProductionDt.warehouse_code,'-1')) and ifNull(". $towarehouse .",ifNull(ProductionDt.warehouse_code,'-1'))  ";
					//" And ifNull(ProductionDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",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']."')  ";  
	
		
	$query= $query." Union ";
		
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select Production.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, Production.Production_Reference As TransReference, Date_Format(Production.Production_Date,'%d/%m/%Y') As TransDate, ".
					" Production.Production_Date As OrderDate, Concat('PRODUCTION IN : ', if(Production.Production_Remark is null,'',Production.Production_Remark)) As TransDescription, ".
					" 'PD' As TransType, Production.Production_ID As TransDtId, Production.Warehouse_Code As WarehouseCode,Production.Project_Code As ProjectCode,Production.Costcenter_Code As CostcenterCode,". 
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" ifNull(Production.Production_Quantity,0) As TransQty, ".
					" Null As QtyOut, ifNull(Production.Production_Quantity,0) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 4 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', Production.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(Production.Item_Code, '".$lastdate."', 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) TransPrice ";
					else
						$query= $query." if(upper($curr)='".$Base1."',Production.Production_TotalBase1,if(upper($curr)='".$Base2."',Production.Production_TotalBase2, Production.Production_Total))/ifNull(Production.Production_Quantity,1) As TransPrice  ";
						
	$query= $query. " , Null as ProductionDt_HeatNo,Date_Format(Production.production_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(Production.Item_Code, '".$lastdate."', 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)  as meanPrice
				      , ifnull(QtyExistsWSorder(Production.Item_Code, Production.Warehouse_Code, '".$lastdate."', 0, 'DI', '', ''),0) QtyExists, Production_BatchNo as batchno, Production.Production_id as TransId,Production.user_Account as useracc ";
	$query= $query. " From Production  ".
					" Inner Join Items on Production.Item_Code = Items.Item_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 ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = Production.Production_ID And PurchasesSerialNo.Journal_Type = 'PD' ";
		
	if ($searchserial == 0) {					   
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query.	"				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on Production.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (Production.Production_Reference Is Not Null And Production.Production_Reference != '')  ";
					//" 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'))  ";
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(Production_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(Production_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(Production_ExpireDate,'%Y-%m-%d'))  ";
	else $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'))  ";	
	
	if ($searchserial == 0)	
		$query= $query." And Production.Item_Code between ifNull(".$fromitem.",Production.Item_Code) and ifNull(". $toitem.",Production.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";		
	
	$query .= " and ifnull(Production_BatchNo,'') between ifnull(".$frombatchno.",ifnull(Production_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(Production_BatchNo,'')) ";
				
	$query= $query.	" 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')) ";
	if($strictcostcentStk == '1'){
		$query= $query." And Production.Costcenter_Code = '".$costCentCodeStk."' ";
	}
	
	$query= $query." And ifNull(Production.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Production.warehouse_code,'-1')) and  ifNull(". $towarehouse .",ifNull(Production.warehouse_code,'-1')) ";
					//" And ifNull(Production.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}

if ($TransPD == 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId , ProjectCode, CostcenterCode, ProductionRM_HeatNo  as Purchasedt_Heatno,ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId , useracc ".
					" From ( ";
					
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select ProductionRM.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, ProductionHD.ProductionHD_Reference As TransReference, Date_Format(ProductionHD.ProductionHD_Date,'%d/%m/%Y') As TransDate, ".
					" ProductionHD.ProductionHD_Date As OrderDate, Concat('PRODUCTION OUT : ', if(ProductionHD.ProductionHD_Remark is null,'',ProductionHD.ProductionHD_Remark)) As TransDescription, ".
					" 'PDT' As TransType, ProductionRM.ProductionRM_ID As TransDtId, ProductionRM.Warehouse_Code As WarehouseCode,ProductionRM.Project_Code As ProjectCode,ProductionRM.Costcenter_Code As CostcenterCode,".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" (-1)*ifNull(ProductionRM.ProductionRM_Quantity,0) As TransQty, ".
					" ifNull(ProductionRM.ProductionRM_Quantity,0) As QtyOut, Null As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 7 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', ProductionHD.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(ProductionRM.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), ProductionHD.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) TransPrice ";
					else
						$query= $query." if(upper($curr)='".$Base1."',ProductionRM.ProductionRM_CostBase1,if(upper($curr)='".$Base2."',ProductionRM.ProductionRM_CostBase2, ProductionRM.ProductionRM_Cost)) As TransPrice ";
						
				   
	$query= $query. " , ProductionRM_HeatNo,Date_Format(ProductionRm.productionrm_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(ProductionRM.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), ProductionHD.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0)  as meanPrice
				      , ifnull(QtyExistsWSorder(ProductionRM.Item_Code, ProductionRM.Warehouse_Code, '".$lastdate."', 0, 'DI', '', ''),0) QtyExists, ProductionRM_BatchNo as batchno, ProductionHD.ProductionHD_ID as TransId , ProductionHD.user_account as useracc";
	$query= $query. " From ProductionRM  ".
					" Inner Join ProductionHD on ProductionRM.ProductionHD_ID = ProductionHD.ProductionHD_ID ".
					" Inner Join Items on ProductionRM.Item_Code = Items.Item_Code ";

	/*if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on ProductionHD.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on ProductionHD.Costcenter_Code like concat(Q5.costcent_code,'%') ";	*/	 
		
	if ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = ProductionRM.ProductionRM_ID And PurchasesSerialNo.Journal_Type IN ('PDT','PDO') ";
	
	if ($searchserial == 0) {	
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query.	"				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on ProductionRM.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (ProductionHD.ProductionHD_Reference Is Not Null And ProductionHD.ProductionHD_Reference != '')  ";
					//" And Date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d'))  ";
	
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(ProductionRM_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(ProductionRM_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(ProductionRM_ExpireDate,'%Y-%m-%d'))  ";
	else $query= $query." And Date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d'))  ";	
	
	$query .= " and ifnull(ProductionRM_BatchNo,'') between ifnull(".$frombatchno.",ifnull(ProductionRM_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(ProductionRM_BatchNo,'')) ";
	
	if ($searchserial == 0)	
		$query= $query." And ProductionRM.Item_Code between ifNull(".$fromitem.",ProductionRM.Item_Code) and ifNull(". $toitem.",ProductionRM.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";		
	

	$query= $query." And Ifnull(ProductionRM.ProductionRM_heatno,-1) between ifNull(".$fromheatno.",Ifnull(ProductionRM.ProductionRM_heatno,-1)) and ifNull(". $toheatno.",Ifnull(ProductionRM.ProductionRM_heatno,-1)) ";
	
	$query= $query.	" 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(ProductionHD.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(ProductionHD.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(ProductionHD.Project_Code,'-1')) ".
					//" And ifNull(ProductionHD.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(ProductionHD.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(ProductionHD.Costcenter_Code,'-1')) ".
					//" And ifNull(ProductionRM.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(ProductionRM.warehouse_code,'-1')),'%')  ";
					" And ifNull(ProductionRM.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(ProductionRM.warehouse_code,'-1')) and ifNull(". $towarehouse .",ifNull(ProductionRM.warehouse_code,'-1')) ";
				
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And ProductionRM.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." Union ";
		
	if ($searchserial == 1) $query = $query." Select PurchasesSerialNo.SerialNo_Code As ItemCode, ";
	else $query = $query." Select ProductionFG.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, ProductionHD.ProductionHD_Reference As TransReference, Date_Format(ProductionHD.ProductionHD_Date,'%d/%m/%Y') As TransDate, ".
					" ProductionHD.ProductionHD_Date As OrderDate, Concat('PRODUCTION IN : ', if(ProductionHD.ProductionHD_Remark is null,'',ProductionHD.ProductionHD_Remark)) As TransDescription, ".
					" 'PD' As TransType, ProductionFG.ProductionFG_ID As TransDtId, ProductionFG.Warehouse_Code As WarehouseCode,ProductionFG.Project_Code As ProjectCode,ProductionFG.Costcenter_Code As CostcenterCode,".
					" Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" ifNull(ProductionFG.ProductionFG_Quantity,0) As TransQty, ".
					" Null As QtyOut, ifNull(ProductionFG.ProductionFG_Quantity,0) As QtyIn, ";
					
	if ($searchserial == 1) $query = $query." 0 As QtyPrev, ";
	else $query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 4 As TransOrder, ".
					" if(upper($curr)='".$Base1."', '".$Base1."',if(upper($curr)='".$Base2."', '".$Base2."', ProductionHD.Currency_Code)) As CurrencyCode, ";
					
					if ($updmeancost == 1)
						$query= $query." ifNull(MeanCostCur(ProductionFG.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), ProductionHD.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) TransPrice ";
					else
						$query= $query." if(upper($curr)='".$Base1."',ProductionFG.ProductionFG_CostBase1,if(upper($curr)='".$Base2."',ProductionFG.ProductionFG_CostBase2, ProductionFG.ProductionFG_Cost)) As TransPrice ";
						
				   
	$query= $query. " , productionfg_heatno as ProductionRM_HeatNo,Date_Format(ProductionFg.productionfg_ExpireDate,'%d/%m/%Y') As ExpireDate  ";
	$query= $query. " , ifNull(MeanCostCur(ProductionFG.Item_Code, '".$lastdate."', if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), ProductionHD.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) as meanPrice
				      , ifnull(QtyExistsWSorder(ProductionFG.Item_Code, ProductionFG.Warehouse_Code, '".$lastdate."', 0, 'DI', '', ''),0) QtyExists, ProductionFG_BatchNo as batchno, ProductionHD.ProductionHD_ID as TransId,null as useracc ";
	$query= $query. " From ProductionFG  ".
					" Inner Join ProductionHD on ProductionFG.ProductionHD_ID = ProductionHD.ProductionHD_ID ".
					" Inner Join Items on ProductionFG.Item_Code = Items.Item_Code ";

	/*if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on ProductionHD.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on ProductionHD.Costcenter_Code like concat(Q5.costcent_code,'%') ";	*/	 
		
	if ($searchserial == 1)
		$query= $query." Inner Join PurchasesSerialNo on PurchasesSerialNo.PurchaseDt_ID = ProductionFG.ProductionFG_ID And PurchasesSerialNo.Journal_Type = 'PD' ";

	if ($searchserial == 0) {					   
		$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(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
						//"				And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
		$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on ProductionFG.Item_Code = QQtyPrev.Item_Code   ";
	}
	
	$query= $query.	" Where (ProductionHD.ProductionHD_Reference Is Not Null And ProductionHD.ProductionHD_Reference != '')  ";
					//" And Date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d'))  ";
	
	if($Module_expiredate==1 && $edatechk == 1)	
	$query= $query." And Date_format(ProductionFG_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(ProductionFG_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(ProductionFG_ExpireDate,'%Y-%m-%d'))  ";
	else $query= $query." And Date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionHD.ProductionHD_Date,'%Y-%m-%d'))  ";	
	
	$query .= " and ifnull(ProductionFG_BatchNo,'') between ifnull(".$frombatchno.",ifnull(ProductionFG_BatchNo,''))
				and ifnull(".$tobatchno.",ifnull(ProductionFG_BatchNo,'')) ";
				
	if ($searchserial == 0)	
		$query= $query." And ProductionFG.Item_Code between ifNull(".$fromitem.",ProductionFG.Item_Code) and ifNull(". $toitem.",ProductionFG.Item_Code) ";
	else
		$query= $query." And PurchasesSerialNo.SerialNo_Code between ifNull(".$fromitem.",PurchasesSerialNo.SerialNo_Code) and ifNull(". $toitem.",PurchasesSerialNo.SerialNo_Code) ";		
	
	$query= $query." And Ifnull(ProductionFG.ProductionFG_heatno,-1) between ifNull(".$fromheatno.",Ifnull(ProductionFG.ProductionFG_heatno,-1)) and ifNull(". $toheatno.",Ifnull(ProductionFG.ProductionFG_heatno,-1)) ";

	
	$query= $query.	" 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(ProductionHD.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(ProductionHD.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(ProductionHD.Project_Code,'-1')) ".
					//" And ifNull(ProductionHD.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(ProductionHD.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(ProductionHD.Costcenter_Code,'-1')) ".
					//" And ifNull(ProductionFG.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(ProductionFG.warehouse_code,'-1')),'%')  ";
					" And ifNull(ProductionFG.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(ProductionFG.warehouse_code,'-1')) and ifNull(". $towarehouse .",ifNull(ProductionFG.warehouse_code,'-1')) ";
				
	  
				if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
					$query= $query." 	And ProductionFG.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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}



if ($TransPRT == 1 && $edatechk != 1 && $searchserial != 1 ) {

	if ($SelectedTransaction == 1 ) 
		$query = $query." Union ";

	$query = $query." Select ItemCode, ItemDescription, TransReference, TransDate, TransDescription, WarehouseCode, QtyTransferFrom, QtyTransferTo, ".
					" QtyOut, QtyIn, QtyPrev, CurrencyCode, TransPrice, TransOrder, OrderDate, TransType, TransDtId ,ProjectCode, CostcenterCode, AdjustmentDt_HeatNo  as Purchasedt_Heatno,ExpireDate, meanPrice*QtyExists as RemainVal, ".
					" abs((ifnull(QtyTransferFrom,0)-ifnull(QtyTransferTo,0))+(ifnull(QtyIn,0)-ifnull(QtyOut,0)))*meanPrice as TransVal, batchno, TransId, useracc ".
					" From ( ";
	
	
	$query = $query." Select productionreqfg.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, ProductionReq_Reference As TransReference, Date_Format(productionrequest.ProductionReq_Date,'%d/%m/%Y') As TransDate, ".
					" productionrequest.ProductionReq_Date As OrderDate, Concat('Production Request : ', if(productionrequest.ProductionReq_Remark is null,'',productionrequest.ProductionReq_Remark)) As TransDescription, ".
					" 'PRqst' As TransType, productionreqfg.ProductionReqFG_Id As TransDtId, productionreqfg.Warehouse_Code As WarehouseCode,productionrequest.Project_Code As ProjectCode,productionrequest.CostCenter_Code As CostcenterCode, ".
					" null as AdjustmentDt_HeatNo, Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" 0 As TransQty, ".
					" 0 As QtyOut, ".
					" ifnull(ProductionReqFG_Quantity,0) As QtyIn, ";
					
	$query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 10 As TransOrder, ".
					" upper($curr) As CurrencyCode, NULL as TransPrice ";
				   
	$query= $query. " , null ,null As ExpireDate ";
	$query= $query. " , 0 as meanPrice
				      , 0 QtyExists, '' as batchno, productionreqfg.ProductionReq_Id as TransId ,productionrequest.user_account as useracc ";
	$query= $query. " From productionreqfg  ".
					" Inner Join productionrequest on productionrequest.ProductionReq_Id = productionreqfg.ProductionReq_Id ".
					" Inner Join Items on productionreqfg.Item_Code = Items.Item_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on productionrequest.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on productionrequest.CostCenter_Code like concat(Q5.costcent_code,'%') ";		 
	
	$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum(ifNull(qt_productionrqst,0)) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') < ifNull(". $fromdate.",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')) ";
			if($strictcostcentStk == '1'){
				$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
			}
	$query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on productionreqfg.Item_Code = QQtyPrev.Item_Code   ";
	
	
	$query= $query.	" Where (ProductionReq_Reference Is Not Null And ProductionReq_Reference != '')  ";
					
	$query= $query." And Date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d'))  ";	
	
	$query= $query." And productionreqfg.Item_Code between ifNull(".$fromitem.",productionreqfg.Item_Code) and ifNull(". $toitem.",productionreqfg.Item_Code) ";
	
	$query= $query.	" 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(productionrequest.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(productionrequest.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(productionrequest.Project_Code,'-1')) ".
					" And ifNull(productionrequest.CostCenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(productionrequest.CostCenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(productionrequest.CostCenter_Code,'-1')) ".
					" And ifNull(productionreqfg.warehouse_code,'-1') between  ifNull(". $fromwarehouse .",ifNull(productionreqfg.warehouse_code,'-1')) and  ifNull(". $towarehouse .",ifNull(productionreqfg.warehouse_code,'-1'))  ";
	if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
		$query= $query." 	And productionreqfg.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." union Select productionreqrm.Item_Code As ItemCode, ";
	
	$query = $query." Items.Item_Description As ItemDescription, ProductionReq_Reference As TransReference, Date_Format(productionrequest.ProductionReq_Date,'%d/%m/%Y') As TransDate, ".
					" productionrequest.ProductionReq_Date As OrderDate, Concat('Production Request : ', if(productionrequest.ProductionReq_Remark is null,'',productionrequest.ProductionReq_Remark)) As TransDescription, ".
					" 'PRqst' As TransType, productionreqrm.ProductionReqFG_Id As TransDtId, productionreqrm.Warehouse_Code As WarehouseCode,productionrequest.Project_Code As ProjectCode,productionrequest.CostCenter_Code As CostcenterCode, ".
					" null as AdjustmentDt_HeatNo, Null As QtyTransferFrom, Null As QtyTransferTo, ".
					" 0 As TransQty, ".
					" 0 As QtyOut, ".
					" ifnull(ProductionReqRM_Quantity,0) As QtyIn, ";
					
	$query = $query." QQtyPrev.QuantityExists As QtyPrev, ";
	
	$query = $query." 10 As TransOrder, ".
					" upper($curr) As CurrencyCode, NULL as TransPrice ";
				   
	$query= $query. " , null ,null As ExpireDate ";
	$query= $query. " , 0 as meanPrice
				      , 0 as QtyExists, '' as batchno, productionreqrm.ProductionReq_Id as TransId , null as useracc ";
	$query= $query. " From productionreqrm  ".
					" Inner Join productionrequest on productionrequest.ProductionReq_Id = productionreqrm.ProductionReq_Id ".
					" Inner Join Items on productionreqrm.Item_Code = Items.Item_Code ";

	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on productionrequest.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on productionrequest.CostCenter_Code like concat(Q5.costcent_code,'%') ";		 
	
	$query= $query. " Left Join (  ".
						"               Select Stk.Item_Code, Sum(ifNull(qt_productionrqst,0)) As QuantityExists  ".
						"               From StkTransaction Stk ".
						"               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') < ifNull(". $fromdate.",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')) ";
		if($strictcostcentStk == '1'){
			$query= $query." And Stk.costcent_code = '".$costCentCodeStk."' ";
		}
		 $query= $query."				And ifNull(Stk.warehouse_code,'-1') between ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')) and ifNull(". $towarehouse .",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 QQtyPrev on productionreqrm.Item_Code = QQtyPrev.Item_Code   ";
	
	
	$query= $query.	" Where (ProductionReq_Reference Is Not Null And ProductionReq_Reference != '')  ";
					
	$query= $query." And Date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(productionrequest.ProductionReq_Date,'%Y-%m-%d'))  ";	
	
	$query= $query." And productionreqrm.Item_Code between ifNull(".$fromitem.",productionreqrm.Item_Code) and ifNull(". $toitem.",productionreqrm.Item_Code) ";
	
	$query= $query.	" 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(productionrequest.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(productionrequest.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(productionrequest.Project_Code,'-1')) ".
					" And ifNull(productionrequest.CostCenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(productionrequest.CostCenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(productionrequest.CostCenter_Code,'-1')) ".
					" And ifNull(productionreqrm.warehouse_code,'-1') between  ifNull(". $fromwarehouse .",ifNull(productionreqrm.warehouse_code,'-1')) and  ifNull(". $towarehouse .",ifNull(productionreqrm.warehouse_code,'-1'))  ";
	if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
		$query= $query." 	And productionreqrm.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 ItemCode, OrderDate, TransOrder, TransReference  ";				
	$query= $query." ) Q1 ";
	
	$SelectedTransaction = 1;
	
}


$query= $query." ) MainQuery ";
$query= $query." Order by ItemCode, OrderDate, TransOrder, TransReference  ";
	
echo $query; //exit;

$mastergroup  = '';
$GroupDesc   = '';
$SumQtyExists = 0;
$QtyIn	= 0;
$QtyOut = 0;
$QtyTrsFrom	= 0;
$QtyTrsTo = 0;

$SumQtyIn	= 0;
$SumQtyOut = 0;
$SumQtyTrsFrom	= 0;
$SumQtyTrsTo = 0;

$col=0;

//logHtml($query);

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

	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
    	
		
	if ($mastergroup == '' || $mastergroup != $rows[0])  {
		
		if ($searchserial == 1)	$GroupDesc = $ReportSerial.':  ';
		else $GroupDesc = $ReportItem.':  ';
			
		if ($mastergroup != '') {
			echo "<tr>";
			echo "  <td align='left' valign='top' colspan='4' >&nbsp;</td>";
			if ($Module_BatchNo == 1 && $showbatch == 1)
				echo "  <td align='left' valign='top' colspan='1' >&nbsp;</td>";
			if($Module_Heatno==1 and $vShowHeatno==1)
				echo "  <td align='left' valign='top' colspan='1' >&nbsp;</td>";
			echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyTrsFrom, $StmtOfItemRMaskQty) ."</td>";
			echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyTrsTo, $StmtOfItemRMaskQty) ."</td>";
			echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyIn, $StmtOfItemRMaskQty) ."</td>";
			echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyOut, $StmtOfItemRMaskQty) ."</td>";
			echo "  <td align='left' valign='top' colspan='4' >&nbsp;</td>";
			echo "</tr>"; 
			
			echo "<tr height='20'>";
			echo "   <td align='left' valign='top' colspan='12' >&nbsp;</td>";
			echo "</tr>"; 	
		}
		
		
		echo "<tr height='25' >";
		echo "   <td align='left'  valign='top' colspan='2' class='grouplevel1' >$GroupDesc ". $rows[0]."</td>";
		echo "   <td align='left'  valign='top' colspan='5' class='grouplevel1' >". $rows[1]."</td>";
		echo "   <td align='right' valign='top' colspan='3' class='grouplevel1' >$ReportPrevious:  ". number_format($rows[10], $StmtOfItemRMaskQty)."</td>";
		echo "   <td align='right' valign='top' colspan='2' class='grouplevel1' >&nbsp;</td>";
		echo "</tr>"; 
				
	
		$mastergroup   = $rows[0];
		$SumQtyExists  = $rows[10];
		
		$SumQtyIn	= 0;
		$SumQtyOut = 0;
		$SumQtyTrsFrom	= 0;
		$SumQtyTrsTo = 0;
		
	}
		
		
	$QtyIn		= $rows[9];
	$QtyOut 	= $rows[8];
	$QtyTrsFrom	= $rows[6];
	$QtyTrsTo 	= $rows[7];
	
	if (empty($QtyIn))  	 $QtyIn = 0;
	if (empty($QtyOut)) 	 $QtyOut = 0;
	if (empty($QtyTrsFrom))  $QtyTrsFrom = 0;
	if (empty($QtyTrsTo)) 	 $QtyTrsTo = 0;
	
	
	$SumQtyExists   = $SumQtyExists  +  $QtyIn  -  $QtyOut + $QtyTrsTo - $QtyTrsFrom;
	
	$SumQtyIn	+= $QtyIn;
	$SumQtyOut  += $QtyOut;
	$SumQtyTrsFrom	+= $QtyTrsFrom;
	$SumQtyTrsTo    += $QtyTrsTo;
	
	
	echo "<tr class='group' $color>"; 
	
	if($Module_expiredate==1 && $edatechk == 1) 
	echo "	<td align='left'   valign='top' style='border-right:1px solid black;'>". $rows[20] ."</td>";
	else echo "	<td align='left'   valign='top' style='border-right:1px solid black;'>". $rows[3] ."</td>";
	if($rows[15] == "DI"){
		$query_getId  = "select delivery_id as DeliveryId from deliveries where delivery_reference = '".$rows[2]."' and journal_type = '".$rows[15]."'";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$DeliveryId = $rows[24];
		$LinkToGo = "Form_DeliveryPreview.php?SalesId=$DeliveryId&PLang=EN&printlogo=0";
	}
	else
	if($rows[15] == "DR"){
		$query_getId  = "select delivery_id as DeliveryId from deliveries where delivery_reference = '".$rows[2]."' and journal_type = '".$rows[15]."'";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$DeliveryId = $rows[24];
		$LinkToGo = "Form_ReturnDeliveryPreview.php?ReturnSalesId=$DeliveryId&PLang=EN&printlogo=0";
	}
	else
	if(($rows[15] == "AI" || $rows[15] == "AR" || $rows[15] == "AD") && $FI_ShowCostPrice == 1){
		$query_getId  = "select adjustment_id as AdjustmentId from adjustment where adjustment_reference = '".$rows[2]."'";
		//echo $query_getId."<br>";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$AdjustmentId = $rows[24];
		$LinkToGo = "Form_AdjustmentPreview.php?AdjustmentId=$AdjustmentId&PrtSer=1";
	}
	else
	if(($rows[15] == "AI" || $rows[15] == "AR" || $rows[15] == "AD") && $FI_ShowCostPrice == 1){
		$query_getId  = "select adjustment_id as AdjustmentId from adjustment where adjustment_reference = '".$rows[2]."'";
		//echo $query_getId."<br>";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$AdjustmentId = $rows[24];
		$LinkToGo = "Form_AdjustmentPreview.php?AdjustmentId=$AdjustmentId&PrtSer=1";
	}
	else
		if($rows[15] == "PI" && $FI_ShowCostPrice == 1){ 
	
		if ($Module_Grn == 1) 
			$query_getId  = "select Purchase_id as PurchaseId from grnpurchases where Purchase_Reference = '".$rows[2]."' and purchase_type='GRN' ";
		else 	
		$query_getId  = "select Purchase_id as PurchaseId from purchases where Purchase_Reference = '".$rows[2]."' and journal_type = '".$rows[15]."'";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$PurchaseId = $rows[24];
		if ($Module_Grn == 1)
			$LinkToGo = "Form_GoodRecNotePreview.php?PurchaseId=$PurchaseId&PrtSer=1&PLang=EN";
		else	
			$LinkToGo = "Form_PurchasePreview.php?PurchaseId=$PurchaseId&PrtSer=1&PLang=EN";
	}
	else
		if($rows[15] == "PR" && $FI_ShowCostPrice == 1){
			if ($Module_Grn == 1) 
				$query_getId  = "select Purchase_id as PurchaseId from grnpurchases where Purchase_Reference = '".$rows[2]."' and purchase_type<>'GRN'  ";
			else
				$query_getId  = "select Purchase_id as PurchaseId from purchases where Purchase_Reference = '".$rows[2]."' and journal_type = '".$rows[15]."'";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$PurchaseId = $rows[24];
		if ($Module_Grn == 1)
			$LinkToGo = "Form_RetGoodRecNotePreview.php?PurchaseId=$PurchaseId&PrtSer=1";
		else
			$LinkToGo = "Form_ReturnPurchasePreview.php?PurchaseId=$PurchaseId&PrtSer=1";
	}
	else
		if(($rows[15] == "PD" || $rows[15] == "PDT") && $FI_ShowCostPrice == 1){
		$query_getId  = "select Production_id as ProductionId from production where Production_Reference = '".$rows[2]."'";
		$result_getId = mysql_query($query_getId, $connection); 
		$row_getId    = mysql_fetch_array($result_getId);
		extract($row_getId);
		$ProductionId = $rows[24];
		$LinkToGo = "Form_AssemblePreview.php?ProductionId=$ProductionId";
	}
	else{
		$LinkToGo = "";
	}
	echo "	<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px; cursor: pointer' onclick=\"window.open('$LinkToGo')\">". $rows[2] ." </td>";
	echo "	<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rows[4] ."</td>";
	echo "	<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rows[5] ." ";
	if($showUser==1) echo "(".$rows[25].")" ;
	echo "  </td>";
	
	if ($Module_BatchNo == 1 && $showbatch == 1)
		echo "	<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rows[23] ."</td>";
	if($Module_Heatno==1 and $vShowHeatno==1)
		echo "	<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rows[19] ."</td>";
	
	echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rows[6], $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rows[7], $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rows[9], $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rows[8], $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($SumQtyExists, $StmtOfItemRMaskQty) ."</td>";
	
	if ($prtcost == 1) {
		echo "	<td align='center' valign='top' style='border-right:1px solid black;'>". $rows[11] ."</td>";
		if($rows[15]=='TR'){
			$sub_query = "select transferdt_costbase1, transferdt_costbase2, transferdt_chargebase1, transferdt_chargebase2 from transferDt where transferDt_Id = '$rows[16]'";
			//echo $sub_query;exit;
			$result_sub_query = mysql_query($sub_query,$connection);
			$rows_sub_query = mysql_fetch_array($result_sub_query);
		
			if($rows[11]==$Base1)
				$total = $rows_sub_query[0] + $rows_sub_query[2];
			if($rows[11]==$Base2)
				$total = $rows_sub_query[1] + $rows_sub_query[3];
			//echo $rows_sub_query[1] + $rows_sub_query[3];exit;
			echo "	<td align='right'  valign='top' >". format_currency($total, $DecimalBase) ."</td>";
		}
		else
			echo "	<td align='right'  valign='top' >". format_currency($rows[12], $DecimalBase) ."</td>";
		echo "	<td align='center' valign='top' >&nbsp;</td>";
	} else {
		echo "	<td align='center' valign='top' colspan='3'>&nbsp;</td>";
	}
	if ($showTransValue == 1){
		echo "	<td align='center'  valign='top' >". format_currency($rows[22], $DecimalBase) ."</td>";
		echo "	<td align='center'  valign='top' >". format_currency($rows[21], $DecimalBase) ."</td>";
	}
	if($vShowProject == 1 && $Module_Project == 1)
		echo "	<td align='center' valign='top' colspan='1'>$rows[17]</td>";
	
	if($vShowCostcenter == 1 && $Module_Costcenter == 1)
		echo "	<td align='center' valign='top' colspan='1'>$rows[18]</td>"; 
	
	echo "</tr>";
	//echo"<tr><td>&nbsp;</td></tr>";
	$col+=1;
}

if ($mastergroup != '') {
	echo "<tr>";
	echo "  <td align='left' valign='top' colspan='4' >&nbsp;</td>";
	if ($Module_BatchNo == 1 && $showbatch == 1)
		echo "  <td align='left' valign='top' colspan='1' >&nbsp;</td>";
	if($Module_Heatno==1 and $vShowHeatno==1)
		echo "  <td align='left' valign='top' colspan='1' >&nbsp;</td>";
		
	echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyTrsFrom, $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyTrsTo, $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyIn, $StmtOfItemRMaskQty) ."</td>";
	echo "	<td align='right' valign='top' class='grouplevel1'>". number_format($SumQtyOut, $StmtOfItemRMaskQty) ."</td>";
	echo "  <td align='left' valign='top' colspan='4' >&nbsp;</td>";
	echo "</tr>"; 
}
	
	
echo "</table></td></tr></table>";

function format_currency($amount, $DecimalBase) { 

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

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

//Return Date in YYYY-MM-DD HH:MM:SS format. Supplied Format: DD/MM/YYYY
function insertMySQLDate($data){
	return substr($data, 6, 4) ."-". substr($data, 3, 2) ."-".substr($data, 0, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");;
}
//Return Today's Date in DD/MM/YYYY format
function displayToday(){
	return strftime("%d")."/".strftime("%m")."/".strftime("%Y");
}


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

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

?>