<?php
include("config.inc.php");
require_once('Spreadsheet/Excel/Writer.php');

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




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

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


$querysetup="select grid_color1,grid_color2, DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, Company_Name As CompanyName, ifNull(ListOfProductionMaskQty,2) as ListOfProductionMaskQty 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);
}


$querymodule=" Select ifNull(Module_NewProduction,0) As Module_NewProduction From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

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

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

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


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

$now=current_server_time($connection);
$dt=split(" ",$now[0]);
$printdate=split("-",$dt[0]);

if ($listby == 1) $ReportTitle = 'List of Finished Goods';
else $ReportTitle = 'List of Raw Materials'; 


//Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();
 
//Sending HTTP headers
$workbook->send('Exp_ProductionReport.xls');
 
//Creating a worksheet
$worksheet=&$workbook->addWorksheet('Production');
$worksheet->setLandscape();
 
//set all columns same width
$columnWidth = 10;


//Title Format 
$sheetTitleFormat =& $workbook->addFormat(array('bold'=>1,
  'size'=>10));

//Column Title Format  
$columnTitleFormat =& $workbook->addFormat(array('bold'=>1,
  'top'=>1,
  'bottom'=>1 ,
  'size'=>15,
  'color'=>0x0A,
  ));
  
 
  
// Regular Format
$regularleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
$regularrightFormatNum =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  )); 
$regularcenterFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'center'  ));  
  
$TitleFormat =& $workbook->addFormat(array('size'=>11,
  'align'=>'left',
  'bold'=>1
  ));

$boldleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ,
  'valign'=>'top'  ,
  'bold'=>1
  ));  
$boldrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ,
  'bold'=>1
  )); 
$boldrightFormatNum =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ,
  'bold'=>1
  ));
$boldcenterFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'center'  ,
  'valign'=>'top'  ,
  'bold'=>1
  ));      
  
$grouplevel1Format =& $workbook->addFormat(array('size'=>10,
  'align'=>'left',
  'bold'=>1,
  'color'=>0x0C
  )); 
$grouplevel2Format =& $workbook->addFormat(array('size'=>10,
  'align'=>'left',
  'bold'=>0,
  'color'=>0x0A
  )); 
$grouplevel3Format =& $workbook->addFormat(array('size'=>9,
  'align'=>'left',
  'italic'=>1,
  'color'=>0x11
  ));   
$grouplevel1totalFormat =& $workbook->addFormat(array('size'=>10,
  'align'=>'right',
  'bold'=>1,
  'color'=>0x0C
  ));  
$grouplevel2totalFormat =& $workbook->addFormat(array('size'=>10,
  'align'=>'right',
  'bold'=>0,
  'color'=>0x0A
  ));  
$grouplevel3totalFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right',
  'italic'=>1,
  'color'=>0x11
  ));   

$seloptionFormat =& $workbook->addFormat(array('size'=>9,
  'align'=> 'left'  ,
  'valign'=> 'top'  ,
  'bold'=> 1
  ));
$seloptionFormat->setTextWrap();

$regularrightFormatNum->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$boldrightFormatNum->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
   	
$worksheet->setColumn (0, 0, 20); 
$worksheet->setColumn (1, 1, 40); 
$worksheet->setColumn (2, 200, 12); 
//$worksheet->setRow (3, 100);

//Display Report Header
$worksheet->write(1,0,$CompanyName, $TitleFormat);
$worksheet->write(1,2,$ReportTitle, $TitleFormat);
               
$worksheet->write(1,6,"Printed Date:", $boldleftFormat);
$worksheet->write(1,7,$printdate[2]."/".$printdate[1]."/".$printdate[0], $regularleftFormat);
$worksheet->write(2,6,"Time:", $boldleftFormat);		
$worksheet->write(2,7,$dt[1]." ".$dt[2], $regularleftFormat);
				
$SelectedOptions = "Filter by: \n";
if ($fromdate != '')  $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."\n";	
if ($curr != '')      $SelectedOptions .= "-> Currency: ". $curr ."\n";	
				
				
				
if (empty($curr))  $curr = $Base1;
  
if (empty($fromitem))  $fromitem = 'null';
else  $fromitem = "'".$fromitem."'";   
if (empty($toitem))  $toitem = 'null';
else  $toitem = "'".$toitem."'";      

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

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

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


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($showdetail))   $showdetail = 0;
if (empty($showcost))     $showcost = 0;
if (empty($showunit2qty)) $showunit2qty = 0;
if (empty($showlastprice)) $showlastprice = 0;
if($showlastprice == 1) $showcost=1;   


if ($showdetail == 1) $masterclass = 'master1';
else $masterclass = 'master';

$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  ";

if ($listby == 1){
$query = $query." Select distinct Production.warehouse_code as warehouse_code ".
				" 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,'%') ";		 
$query = $query.  " Where Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ".
				  " And ifNull(Production.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Production.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Production.Project_Code,'-1')) ".
				  " And ifNull(Production.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Production.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Production.Costcenter_Code,'-1')) ".
				  " And ifNull(Production.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(Production.Warehouse_Code,'-1')) ".
				  " 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 ($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.  " group by Production.warehouse_code ";

$query = $query." union Select ProductionFG.warehouse_code As warehouse_code ".
				" From ProductionFG ".
				" Inner Join Items on ProductionFG.Item_code = Items.Item_code ".
				" Where Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ".
				" And ifNull(ProductionFG.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionFG.Warehouse_Code,'-1')) ".
				" And Date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d'))  ";
					  
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.  " group by ProductionFG.warehouse_code ";
} 
else if ($listby == 2){
		 
	$query = " Select ProductionDt.Warehouse_Code as Warehouse_Code
				From ProductionDt ".
			  " Inner Join Items on ProductionDt.Item_code = Items.Item_code ";
		 
	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
		$query= $query.$QueryRestrictPrj." on ProductionDt.project_code like concat(Q4.project_code,'%') ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$query= $query.$QueryRestrictCst." on ProductionDt.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
			 

	$query = $query.  " Where ProductionDt.Item_Code Between ifNull(".$fromitemRM.", ProductionDt.Item_Code) and ifNull(". $toitemRM.", ProductionDt.Item_Code) ".
						" And ifNull(ProductionDt.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(ProductionDt.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(ProductionDt.Project_Code,'-1')) ".
						" And ifNull(ProductionDt.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(ProductionDt.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(ProductionDt.Costcenter_Code,'-1')) ".
						" And ifNull(ProductionDt.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionDt.Warehouse_Code,'-1')) ".
						" And Date_format(ProductionDt.Production_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionDt.Production_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionDt.Production_Date,'%Y-%m-%d'))  ";

	$query = $query." Group By ProductionDt.Warehouse_Code ";
	
	$query = $query." Union ";  
	$query = $query." Select ProductionRM.Warehouse_Code as Warehouse_Code
						From ProductionRM ".
					  " Inner Join Items on ProductionRM.Item_code = Items.Item_code ";
		 
	$query = $query.  " Where ProductionRM.Item_Code Between ifNull(".$fromitemRM.", ProductionRM.Item_Code) and ifNull(". $toitemRM.", ProductionRM.Item_Code) ".
						" And Date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d'))  ".
						" And ifNull(ProductionRM.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionRM.Warehouse_Code,'-1')) ";
	 
	$query = $query." Group By ProductionRM.Warehouse_Code ";

} 
$queryWh = "select distinct warehouse_code from ( ".$query.") as QQ order by warehouse_code";
$resWh = mysql_query($queryWh,$connection);
$numWh = mysql_num_rows($resWh);

//Displaying Selected Options	
// Merge cells from row 3, col 0 to row 3, col 0
$worksheet->setMerge(3, 0, 8, 3);
$worksheet->write(3,0,$SelectedOptions, $seloptionFormat);  

$RowNum    = 10;
$ColumnNum = 0;


$worksheet->write($RowNum,$ColumnNum,"Item Code / Description", $boldcenterFormat);
$ColumnNum += 2;
$worksheet->write($RowNum,$ColumnNum,"Unit1", $boldcenterFormat);
$ColumnNum += 1;

while($rWh = mysql_fetch_row($resWh)){
	$worksheet->write($RowNum,$ColumnNum,$rWh[0], $boldcenterFormat);
	$ColumnNum += 1;
}
$worksheet->write($RowNum,$ColumnNum,"Total Qty", $boldcenterFormat);
$ColumnNum += 1;
$worksheet->write($RowNum,$ColumnNum,"Currency", $boldcenterFormat);
$ColumnNum += 1;
$worksheet->write($RowNum,$ColumnNum,"Cost Per Unit", $boldcenterFormat);
$ColumnNum += 1;
$worksheet->write($RowNum,$ColumnNum,"Total Cost", $boldcenterFormat);
$ColumnNum += 1;

 	  
	

$query = '';


		 
$query = "";


$query = " Select Q1.ItemCode, ItemDescription, Unit1FG, ";
$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query = $query. " ProductionQuantity$i,  ";
	$i++;
}

 $query = $query." ProductionQuantity, Currency_Code,  CostPerUnitBase1, CostPerUnitBase2, ProductionTotalBase1, ProductionTotalBase2  ";		

$query = $query." From ( ";
$query = $query." Select Production.Item_code As ItemCode, Items.Item_Description As ItemDescription, ";

$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query = $query. " if(Production.warehouse_code='$rWh[0]',Sum(ifNull(Production_Quantity,0)),0) As ProductionQuantity$i,  ";
$i++;
}
$query = $query." Sum(ifNull(Production_Quantity,0)) As ProductionQuantity,  ".
				" Production.Currency_Code, Round(Sum(ifNull(Production_TotalBase1,0)), ".$DecimalBase.") As ProductionTotalBase1, ".
				" Round(Sum(ifNull(Production_TotalBase2,0)), ".$DecimalBase.") As ProductionTotalBase2, ".
				" Round(Sum(ifNull(Production_TotalBase1,0))/Sum(ifNull(Production_Quantity,0)), ".$DecimalBase.") As CostPerUnitBase1, ".
				" Round(Sum(ifNull(Production_TotalBase2,0))/Sum(ifNull(Production_Quantity,0)), ".$DecimalBase.") As CostPerUnitBase2, ".
				" Item_UnitSalesDesc As Unit1FG ".
				" 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,'%') ";		 
		 

$query = $query.  " Where Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ".
				  " And ifNull(Production.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(Production.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(Production.Project_Code,'-1')) ".
				  " And ifNull(Production.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(Production.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(Production.Costcenter_Code,'-1')) ".
				  " And ifNull(Production.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(Production.Warehouse_Code,'-1')) ".
				  " 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 ($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." Group By ItemCode, ItemDescription  ";	
$query = $query." ) as Q1  ";



$query = $query." Union "; 

$query = $query." Select Q1.ItemCode, ItemDescription, Unit1FG, ";
$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query = $query. " ProductionQuantity$i,  ";
	$i++;
}

 $query = $query. "ProductionQuantity, Currency_Code, CostPerUnitBase1, CostPerUnitBase2, ProductionTotalBase1, ProductionTotalBase2  ";

$query = $query." From ( ";
$query = $query." Select ProductionFG.Item_code As ItemCode, Items.Item_Description As ItemDescription, ";

$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query = $query. " if(ProductionFG.warehouse_code='$rWh[0]',Sum(ifNull(ProductionFG_Quantity,0)),0) As ProductionQuantity$i,  ";
$i++;
}
$query = $query." Sum(ifNull(ProductionFG_Quantity,0)) As ProductionQuantity, ProductionFG.Currency_Code, Round(Sum(ifNull(ProductionFG_CostBase1,0)*ifNull(ProductionFG_Quantity,1)), ".$DecimalBase.") As ProductionTotalBase1, ".
				" Round(Sum(ifNull(ProductionFG_CostBase2,0)*ifNull(ProductionFG_Quantity,1)), ".$DecimalBase.") As ProductionTotalBase2, ".
				" Round(Sum(ifNull(ProductionFG_CostBase1,0)*ifNull(ProductionFG_Quantity,0))/Sum(ifNull(ProductionFG_Quantity,0)), ".$DecimalBase.") As CostPerUnitBase1, ".
				" Round(Sum(ifNull(ProductionFG_CostBase2,0)*ifNull(ProductionFG_Quantity,0))/Sum(ifNull(ProductionFG_Quantity,0)), ".$DecimalBase.") As CostPerUnitBase2, ".
				" Item_UnitSalesDesc As Unit1FG ".
				" From ProductionFG ".
				" Inner Join Items on ProductionFG.Item_code = Items.Item_code ".
				" Where Items.Item_Code Between ifNull(".$fromitem.", Items.Item_Code) and ifNull(". $toitem.", Items.Item_Code) ".
				" And ifNull(ProductionFG.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionFG.Warehouse_Code,'-1')) ".
				" And Date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d')) 
				and ifNull(". $todate.",date_format(ProductionFG.ProductionHD_Date,'%Y-%m-%d'))  ";
					  
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." Group By ItemCode, ItemDescription  ";	
$query = $query." ) as Q1  ";

$query = $query." Order By ItemCode ";
	 

//echo $query;

//echo $query;
//exit;


		 
$query1 = " Select ProductionDt.Item_code As ItemCode, Items.Item_Description As ItemDescription,  Item_UnitSalesDesc As Unit1RM,  ";
$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query1 = $query1. " if(ProductionDt.warehouse_code='$rWh[0]',Round(Sum(ifNull(ProductionDt_Quantity,0)), ".$DecimalBase."),0) As ProductionDtQuantity$i,  ";
$i++;
}
$query1 = $query1." Round(Sum(ifNull(ProductionDt_Quantity,0)), ".$DecimalBase.") As ProductionDtQuantity, ProductionDt.Currency_Code,  ".
		  " Round(Sum(ifNull(ProductionDt_Quantity,0)*ifNull(ProductionDt_CostBase1,0))/Sum(ifNull(ProductionDt_Quantity,0)), ".$DecimalBase.")  As ProductionDtCostBase1, ".
      	  " Round(Sum(ifNull(ProductionDt_Quantity,0)*ifNull(ProductionDt_CostBase2,0))/Sum(ifNull(ProductionDt_Quantity,0)), ".$DecimalBase.")  As ProductionDtCostBase2, ".
		  " Round((Sum(ifNull(ProductionDt_Quantity,0)* ifNull(ProductionDt_CostBase1,0))), ".$DecimalBase.") As ProductionDtTotalCostBase1, ".
		  " Round((Sum(ifNull(ProductionDt_Quantity,0)* ifNull(ProductionDt_CostBase2,0) )), ".$DecimalBase.") As ProductionDtTotalCostBase2 ";
		 

$query1 = $query1." From ProductionDt ".
			      " Inner Join Items on ProductionDt.Item_code = Items.Item_code ";
	 
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	$query1= $query1.$QueryRestrictPrj." on ProductionDt.project_code like concat(Q4.project_code,'%') ";
							 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	$query1= $query1.$QueryRestrictCst." on ProductionDt.Costcenter_Code like concat(Q5.costcent_code,'%') ";		 
		 

$query1 = $query1.  " Where ProductionDt.Item_Code Between ifNull(".$fromitemRM.", ProductionDt.Item_Code) and ifNull(". $toitemRM.", ProductionDt.Item_Code) ".
					" And ifNull(ProductionDt.Project_Code,'-1') between ifNull(".$fromproject.",ifNull(ProductionDt.Project_Code,'-1')) and ifNull(". $toproject.",ifNull(ProductionDt.Project_Code,'-1')) ".
				    " And ifNull(ProductionDt.Costcenter_Code,'-1') between ifNull(".$fromcostcent.",ifNull(ProductionDt.Costcenter_Code,'-1')) and ifNull(". $tocostcent.",ifNull(ProductionDt.Costcenter_Code,'-1')) ".
					" And ifNull(ProductionDt.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionDt.Warehouse_Code,'-1')) ".
				    " And Date_format(ProductionDt.Production_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionDt.Production_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionDt.Production_Date,'%Y-%m-%d'))  ";

$query1 = $query1." Group By ItemCode, ItemDescription ";

$query1 = $query1." Union ";  
$query1 = $query1." Select ProductionRM.Item_code As ItemCode, Items.Item_Description As ItemDescription, Item_UnitSalesDesc As Unit1RM, ";
$i=0;
$resWh = mysql_query($queryWh,$connection);
while($rWh = mysql_fetch_row($resWh)){
	$query1 = $query1. " if(ProductionRM.warehouse_code='$rWh[0]',Round(Sum(ifNull(ProductionRM_Quantity,0)), ".$DecimalBase."),0) As ProductionDtQuantity$i,  ";
$i++;
}
$query1 = $query1." Round(Sum(ifNull(ProductionRM_Quantity,0)), ".$DecimalBase.") As ProductionDtQuantity, ProductionRM.Currency_Code,  ".
				  " Round(Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_CostBase1,0))/Sum(ifNull(ProductionRM_Quantity,0)), ".$DecimalBase.")  As ProductionDtCostBase1, ".
				  " Round(Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_CostBase2,0))/Sum(ifNull(ProductionRM_Quantity,0)), ".$DecimalBase.")  As ProductionDtCostBase2, ".
				  " Round((Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_CostBase1,0))), ".$DecimalBase.")  As ProductionDtTotalCostBase1, ".
				  " Round((Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_CostBase2,0))), ".$DecimalBase.")  As ProductionDtTotalCostBase2 ";

$query1 = $query1." From ProductionRM ".
			      " Inner Join Items on ProductionRM.Item_code = Items.Item_code ";

$query1 = $query1.  " Where ProductionRM.Item_Code Between ifNull(".$fromitemRM.", ProductionRM.Item_Code) and ifNull(". $toitemRM.", ProductionRM.Item_Code) ".
					" And Date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(ProductionRM.ProductionHD_Date,'%Y-%m-%d'))  ".
					" And ifNull(ProductionRM.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(ProductionRM.Warehouse_Code,'-1')) ";
 
$query1 = $query1." Group By ItemCode, ItemDescription ";
  
$query1 = $query1." Order By ItemCode ";



$RowNum    = 13;
$ColumnNum = 0;

$TotalAmount  = 0;
$ProductionUnitCost     = 0;
$ProductionTotalCost    = 0;
$ProductionDtUnitCost   = 0;
$ProductionDtTotalCost  = 0;

$MasterItemCode = '';

if ($listby == 1)
	$result=mysql_query($query,$connection) or die(mysql_error());
else 
	$result=mysql_query($query1,$connection) or die(mysql_error());
	
while($rows=mysql_fetch_row($result)){

	if($curr == '' or $curr == $Base1) {
		$ProductionUnitCost  = $rows[$numWh+5];
		$ProductionTotalCost = $rows[$numWh+7];
	} else {
		$ProductionUnitCost  = $rows[$numWh+6];
		$ProductionTotalCost = $rows[$numWh+8];
	}	
		

			 
		$worksheet->write($RowNum, $ColumnNum, $rows[0], $regularleftFormat);
		$ColumnNum += 1;
		$worksheet->write($RowNum, $ColumnNum, $rows[1], $regularleftFormat);
		$ColumnNum += 1;
		$worksheet->write($RowNum, $ColumnNum, $rows[2], $regularcenterFormat);
		$ColumnNum += 1;
		for($t=0;$t<$numWh;$t++){
		$worksheet->write($RowNum, $ColumnNum, number_format($rows[$t+3], $ListOfProductionMaskQty), $regularrightFormat);
		$ColumnNum += 1;
		}
		$worksheet->write($RowNum, $ColumnNum, number_format($rows[$numWh+3], $ListOfProductionMaskQty), $regularrightFormat);
		$ColumnNum += 1;
		$worksheet->write($RowNum, $ColumnNum,$curr, $regularrightFormat);
		$ColumnNum += 1;
		$worksheet->write($RowNum, $ColumnNum, number_format($ProductionUnitCost, $ListOfProductionMaskQty), $regularrightFormat);
		$ColumnNum += 1;
		$worksheet->write($RowNum, $ColumnNum, number_format($ProductionTotalCost, $ListOfProductionMaskQty), $regularrightFormat);
		$ColumnNum += 1;
		
	
	$TotalAmount = $TotalAmount +  $ProductionTotalCost;
		
		
	//Increment the Rows Counter By 1 and Reset the Columns Counter
	$RowNum += 1;
	$ColumnNum = 0;
	
	
}


// Report Totals

$RowNum += 2;
$ColumnNum = $numWh+5;

$worksheet->write($RowNum, $ColumnNum, "Total", $boldleftFormat);
$ColumnNum += 1;
$worksheet->writeNumber($RowNum, $ColumnNum, $TotalAmount, $boldrightFormatNum);
$ColumnNum += 1;


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

$workbook->close();

?>