<?php


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

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

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

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

$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//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_NewProduction,0) As Module_NewProduction					
				From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$queryPurchaseSetup="Select PurchaseTTC From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}

$querysetup="select grid_color1,grid_color2, DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2,report_color1, report_color2, 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);
}

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

//Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();

//Sending HTTP headers
$workbook->send('Exp_ListofFactoryProduction.xls');

//Creating a worksheet
$worksheet=&$workbook->addWorksheet('List Of Factory 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,
  ));
  
//Elie Format

$regularleftFormatNum1 =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormatNum1 =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
  
$grouplevel1FormatNum1  =& $workbook->addFormat(array('size'=>10,
  'align'=>'left',
  'bold'=>1,
  'color'=>0x0C
  )); 
$grouplevel2FormatNum1  =& $workbook->addFormat(array('size'=>10,
  'align'=>'left',
  'bold'=>0,
  'color'=>0x0A
  )); 
$grouplevel3FormatNum1  =& $workbook->addFormat(array('size'=>9,
  'align'=>'left',
  'italic'=>1,
  'color'=>0x11
  ));   
$grouplevel1totalFormatNum1  =& $workbook->addFormat(array('size'=>10,
  'align'=>'right',
  'bold'=>1,
  'color'=>0x0C
  ));  
$grouplevel2totalFormat =& $workbook->addFormat(array('size'=>10,
  'align'=>'right',
  'bold'=>0,
  'color'=>0x0A
  ));  
$grouplevel3totalFormatNum1  =& $workbook->addFormat(array('size'=>9,
  'align'=>'right',
  'italic'=>1,
  'color'=>0x11
  ));  
$summaryFormatNum1  =& $workbook->addFormat(array('size'=>10,
  'align'=>'right'  ,
  'bold'=>1
  ));   
  
  
  

$regularleftFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$regularrightFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel1FormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel2FormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel3FormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel1totalFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel2totalFormat->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$grouplevel3totalFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$summaryFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
//Elie format   
  
  
 

// Regular Format
$regularleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
  
$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
  )); 
$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
  ));  
$summaryFormat =& $workbook->addFormat(array('size'=>10,
  'align'=>'right'  ,
  'bold'=>1
  ));   

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


if (empty($curr))  $curr = $Base1;

$dispfromdate = $fromdate;
$disptodate   = $todate;

$dispcurr     = $curr;


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

$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($fromcategory))  $fromcategory = 'null';
else  $fromcategory = "'".$fromcategory."'";    
if (empty($tocategory))  $tocategory = 'null';
else  $tocategory = "'".$tocategory."'";  

if (empty($showlastprice)) $showlastprice = 0;

$fromwarehouse1=$fromwarehouse;
   




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

$query=" select  warehouse_name ".
         " from warehouse where warehouse_code = $fromwarehouse" ;
		 
$result = mysql_query($query,$connection) or die(mysql_error());
$rows=mysql_fetch_row($result);
$warehousename = $rows[0];

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; 

 
$SelectedOptions = ' ';
 if ($fromdate != '')      $SelectedOptions .= " Date From/To: ". $fromdate . " - ". $todate ." \n ";	
if ($dispcurr != '')    $SelectedOptions .= " Currency: ". $dispcurr ." \n  ";	
if ($fromwarehouse != 'null') $SelectedOptions .= " Warehouse From/To:  $fromwarehouse1 - $warehousename \n ";
 $SelectedOptions .= " $dispheat \n ";

//Display Report Header
$worksheet->write(1,0,$CompanyName, $TitleFormat);
$worksheet->write(1,4,"List Of Production", $TitleFormat);
               
$worksheet->write(1,9,"Printed Date:", $boldleftFormat);
$worksheet->write(1,10,$printdate[2]."/".$printdate[1]."/".$printdate[0], $regularleftFormat);
$worksheet->write(2,9,"Time:", $boldleftFormat);		
$worksheet->write(2,10,$dt[1]." ".$dt[2], $regularleftFormat);

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

$RowNum    = 10;
$ColumnNum = 0;	

	$worksheet->setColumn ($ColumnNum, $ColumnNum, 20);
	$worksheet->write($RowNum,$ColumnNum,"Date", $boldleftFormat);
	$ColumnNum += 1;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
	$worksheet->write($RowNum,$ColumnNum,"Reference", $boldcenterFormat);
	$ColumnNum += 1;
	
	$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum+3);
	$worksheet->write($RowNum,$ColumnNum,"Item Code / Description", $boldcenterFormat);
	$ColumnNum += 4;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"RM Net Weight", $boldcenterFormat);
	$ColumnNum += 1;
	
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"SF Net Weight", $boldcenterFormat);
	$ColumnNum += 1;
	
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"Waste", $boldcenterFormat);
	$ColumnNum += 1;
	
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"Qty", $boldcenterFormat);
	$ColumnNum += 1;

if ($showcost == 1) {
	
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"Currency", $boldcenterFormat);
	$ColumnNum += 1;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"Cost Per Unit", $boldcenterFormat);
	$ColumnNum += 1;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
	$worksheet->write($RowNum,$ColumnNum,"Total Cost", $boldcenterFormat);
	$ColumnNum += 1;
}	
 
 
if ($showdetail == 1) {
	$ColumnNum = 1;
	$RowNum += 1;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
	$worksheet->write($RowNum,$ColumnNum," ", $boldleftFormat);
	$ColumnNum += 1;
	$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
	$worksheet->write($RowNum,$ColumnNum,"Item Code", $boldleftFormat);
	$ColumnNum += 1;
	$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum+2);
	$worksheet->write($RowNum,$ColumnNum,"Description", $boldleftFormat);
	$ColumnNum += 3;
	
	$worksheet->write($RowNum,$ColumnNum,"Warehouse", $boldleftFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum,$ColumnNum,"Weight", $boldleftFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum,$ColumnNum,"Qty", $boldleftFormat);
	$ColumnNum += 1;
	
	if ($showcost == 1) {
		$worksheet->write($RowNum,$ColumnNum,"Cost Price", $boldleftFormat);
		$ColumnNum += 1;	
		$worksheet->write($RowNum,$ColumnNum,"Total Cost", $boldleftFormat);
		$ColumnNum += 1;	
	}			
	 
} 
	

$query = '';

$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 = "select productionfactoryFG.productionFactory_id, productionfactoryFG.productionFactoryfg_id,productionFactory_reference,
		date_format(productionFactory_date, '%d-%m-%Y'), productionfactoryFG.item_code, item_description,totnetweightrm, totnetweightsf, totwaste,
		productionFactoryfg_qty, productionfactory.Currency_Code, Round(ifNull(productionFactoryfg_price1,0), ".$DecimalBase.") as price1,Round(ifNull(productionFactoryfg_price2,0), ".$DecimalBase.") as price2,
		Round(ifNull(productionFactoryfg_net1,0), ".$DecimalBase.") as totprice1, Round(ifNull(productionFactoryfg_net2,0), ".$DecimalBase.") as totprice2
		from productionfactoryFG
		inner join productionfactory on productionfactory.productionFactory_id = productionfactoryFG.productionFactory_id
		inner join items on items.item_code = productionfactoryFG.item_code
		Left Join Warehouse on Warehouse.Warehouse_Code = productionfactoryFG.warehouse_code
		Left Join grouping on grouping.Group_Code = Items.Group_code
		Left Join subgroup on subgroup.Group_Code = Items.SubGroup_Code
		Left Join category on category.Category_Code = Items.Category_code ";	

				 
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	$query= $query.$QueryRestrictPrj." on productionfactoryFG.project_codedt like concat(Q4.project_code,'%') ";
							 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	$query= $query.$QueryRestrictCst." on productionfactoryFG.costcent_codedt like concat(Q5.costcent_code,'%') ";		 

$query = $query.  " Where Items.Item_Code Between ifNull(".$fromitemRM.", Items.Item_Code) and ifNull(". $toitemRM.", Items.Item_Code) ".
				  " And ifNull(productionfactoryFG.project_codedt,'-1') between ifNull(".$fromproject.",ifNull(productionfactoryFG.project_codedt,'-1')) and ifNull(". $toproject.",ifNull(productionfactoryFG.project_codedt,'-1')) ".
				  " And ifNull(productionfactoryFG.costcent_codedt,'-1') between ifNull(".$fromcostcent.",ifNull(productionfactoryFG.costcent_codedt,'-1')) and ifNull(". $tocostcent.",ifNull(productionfactoryFG.costcent_codedt,'-1')) ".
				  " And ifNull(productionfactoryFG.Warehouse_Code,'-1') = ifNull(". $fromwarehouse .", ifNull(productionfactoryFG.Warehouse_Code,'-1')) ".
				  " And Date_format(productionFactory_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(productionFactory_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(productionFactory_date,'%Y-%m-%d'))  ".
				  " 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(". $fromcategory.",ifNull(Items.Category_code,'-1')) ";
				  	
					  
if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
	$query = $query." And productionfactoryFG.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 productionFactory_date, productionFactory_reference ";		
$result = mysql_query($query, $connection);

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

$col=0;
$ColumnNum=0;
$RowNum += 1;
$result=mysql_query($query,$connection) or die(mysql_error()); 

while($rw = mysql_fetch_array($result)){
	
	$factory_id = $rw[0];
	$factoryFG_id = $rw[1];
	
	if($curr == '' or $curr == $Base1) {
		$ProductionUnitCost  = $rw[11];
		$ProductionTotalCost = $rw[13];
	} else {
		$ProductionUnitCost  = $rw[12];
		$ProductionTotalCost = $rw[14];
	}
	
	
	$ColumnNum = 0;
	$worksheet->write($RowNum, $ColumnNum, $rw[3], $regularleftFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, $rw[2], $regularleftFormat);
	$ColumnNum += 1;
	
	$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum+3);
	$worksheet->write($RowNum, $ColumnNum, $rw[4]." - ".$rw[5], $regularleftFormat);
	$ColumnNum += 4;
	
	$worksheet->write($RowNum, $ColumnNum, $rw[6], $regularleftFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, $rw[7], $regularrightFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, $rw[8], $regularrightFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, $rw[9], $regularrightFormat);
	$ColumnNum += 1;	
	
	
	if ($showcost == 1) {
		$worksheet->write($RowNum, $ColumnNum, $curr, $regularrightFormat);
		$ColumnNum += 1;
		$worksheet->writeNumber($RowNum, $ColumnNum, $ProductionUnitCost, $regularrightFormatNum1);
		$ColumnNum += 1;
		$worksheet->writeNumber($RowNum, $ColumnNum, $ProductionTotalCost, $regularrightFormatNum1);
		$ColumnNum += 1;
	} 
	
	$RowNum += 1;
	
	if ($showdetail == 1) {
		$querydt = "select productionfactorySF.item_code, item_description, productionfactorySF.warehouse_code, productionFactorysf_weight,
					productionFactorysf_qty, Round(ifNull(productionFactorysf_price1,0), ".$DecimalBase.") as pricedt1, Round(ifNull(productionFactorysf_price2,0), ".$DecimalBase.") as pricedt2,
					Round(productionFactorysf_qty*ifNull(productionFactorysf_price1,0), ".$DecimalBase.") as totpricedt1,
					Round(productionFactorysf_qty*ifNull(productionFactorysf_price2,0), ".$DecimalBase.") as totpricedt2
					from productionfactorySF
					left join items on items.item_code = productionfactorySF.item_code
					Left Join Warehouse on Warehouse.Warehouse_Code = productionfactorySF.warehouse_code
					Left Join grouping on grouping.Group_Code = Items.Group_code
					Left Join subgroup on subgroup.Group_Code = Items.SubGroup_Code
					Left Join category on category.Category_Code = Items.Category_code ";
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$querydt= $querydt.$QueryRestrictPrj." on productionfactorySF.project_codedt like concat(Q4.project_code,'%') ";
								
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$querydt= $querydt.$QueryRestrictCst." on productionfactorySF.costcent_codedt like concat(Q5.costcent_code,'%') ";		
		
		$querydt= $querydt." where productionFactoryfg_id = 1 and productionFactory_id = 3 ";
		$querydt= $querydt." order by productionfactorySF.item_code ";
		
		$ColumnNum = 0;
		
		$resultdt = mysql_query($querydt, $connection);
		while($rwdt = mysql_fetch_array($resultdt)){
						
			if($curr == '' or $curr == $Base1) {
				$ProductionDtUnitCost  = $rwdt[5];
				$ProductionDtTotalCost = $rwdt[7];
			} else {
				$ProductionDtUnitCost  = $rwdt[6];
				$ProductionDtTotalCost = $rwdt[8];
			}
			
			
			$worksheet->write($RowNum, $ColumnNum, '', $regularrightFormat);
			$ColumnNum += 2;
			$worksheet->write($RowNum, $ColumnNum, $rwdt[0], $regularrightFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum+2);
			$worksheet->write($RowNum, $ColumnNum, $rwdt[1], $regularrightFormat);
			$ColumnNum += 3;
			$worksheet->write($RowNum, $ColumnNum, $rwdt[2], $regularrightFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum, $ColumnNum, $rwdt[3], $regularrightFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum, $ColumnNum, $rwdt[4], $regularrightFormat);
			$ColumnNum += 1;
			
			if ($showcost == 1 ) {
				$worksheet->write($RowNum, $ColumnNum, $ProductionDtUnitCost, $regularrightFormat);
				$ColumnNum += 1;
				$worksheet->writeNumber($RowNum, $ColumnNum, $ProductionDtTotalCost, $regularrightFormatNum1);
				$ColumnNum += 1;
			}
			$RowNum += 1;
			$ColumnNum = 0;			
			
		}
		
	}
	$TotalAmount = $TotalAmount +  $ProductionTotalCost;
	
	$RowNum += 1;
	$ColumnNum = 0;
} 

if ($showcost == 1) {
	$RowNum += 1;
	$ColumnNum = 11;
	
	$worksheet->write($RowNum, $ColumnNum, 'Total', $boldleftFormat);
	$ColumnNum += 1;
	$worksheet->writeNumber($RowNum, $ColumnNum, $TotalAmount, $regularrightFormatNum1);
	
} 


function current_server_time($connection){

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

  return $now;
}

function explodeword($date)
{

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

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

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

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



$workbook->close();

?>