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

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


print <<< HERE
<HTML>
<HEAD>
<TITLE> List of Factory Production Report </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">

<style type="text/css">
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                      }				 
table.master td { font-size: 13px; 
                  font-family:Times-New-Roman;
                 }
				 
table.master1 th { font-size: 14px; 
                   font-weight: bold;
                   font-family:Times-New-Roman;
                 }				 
table.master1 td { font-size: 13px; 
				   font-weight: bold;
                   font-family:Times-New-Roman;
                 }				 

table.detail th { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }				 			   
table.detail td { font-size: 11px; 
				  font-weight: normal;
		          font-family:Times-New-Roman;
                 }			   
				 
.totals { font-size: 12px; 
          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']);

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

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


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

$queryPurchaseSetup="Select PurchaseTTC From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}
$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]);

print <<< HERE
<table width="100%" border="0" align="center">
<tr><td>
<table width='100%' border='0' align='left' style='table-layout:fixed'>
HERE;

if ($prtheader == 1){
	ShowReportHeader('List of Factory Productions','portrait', $connection);
} else {
	ShowReportTitle('List of Factory Productions','portrait', $connection);
}

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

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."'";  

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

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


print <<<HERE
</font></td>
</tr>
<tr height='4'><td colspan=5><h5></td></tr>
</table>
</td></tr>

<tr><td>
<table class='params' width='100%' border='0' align='left' style='table-layout:fixed' >
<tr>
  <td width="12%"><b>Date From/To:</b></td>
  <td width="18%">$dispfromdate - $disptodate </td>

HERE;
 
  
 echo "  <td width='8%' valign='top'><b>Currency:</b></td>
  <td width='8%'>$dispcurr</td>";

 if($fromwarehouse1!='')
  echo"<td width='24%' valign='top'><b>Warehouse:</b> $fromwarehouse1 - $warehousename</td>";
  else  echo"<td width='24%' valign='top'></td>";
  echo "<td width='25%' valign='top'>$dispheat</td>";
print <<<HERE

</tr>
<tr height='5'><td colspan=7><h4></td></tr>
</table>
</td></tr>

<tr><td>
HERE;

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

echo "<table width='100%' border='0' align='left' cellpadding='0' cellspacing='0' class=$masterclass style='table-layout:fixed'>
	  <col width=70><col width=70><col width=250>
	  <col width=100><col width=100><col width=100>
	  <col width=80>";
if ($showcost == 1) echo "<col width=80><col width=120><col width=120>";	  
echo"  <tr>
		<th >Date</th>
		<th >Reference</th>
		<th  align='left'>Item Code / Description</th>
		<th >RM Net Weight</th>
		<th >SF Net Weight</th>
		<th >Waste</th>
		<th >Qty</th>";

if ($showcost == 1) {
echo"  	<th >Currency</th>
		<th >Cost Per Unit </th>
		<th >Total Cost </th>";
} 		  
echo "</tr>";

$colsp = 7;
if ($showcost == 1) $colsp = $colsp + 3;		  
if ($showdetail == 1) {
	echo"<tr height='5'><td colspan='$colsp'><h5></td></tr>";
	echo"<tr height='20'><td colspan='".($colsp)."'>";
	echo "<table width='100%' border='0' align='left' cellpadding='0' cellspacing='0' class='detail' style='table-layout:fixed'>
			<col width=40>
			<col width=100>
			<col width=250>
			<col width=100>
			<col width=80>
			<col width=80>";
if ($showcost == 1 )
	echo "	<col width=120>
			<col width=120>";
			
	echo "<tr>
			<th >&nbsp;</th>
			<th >Item Code</th>
			<th align='left'>Description</th>
			<th >Warehouse</th>
			<th >Weight</th>
			<th >Qty</th>";
if ($showcost == 1) {
	echo"<th >Cost Price </th>";
	echo"<th >Total Cost</th>";
}	
		
	echo"	</tr>";
		
	echo"</table>";
	echo"</td></tr>";		
}

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


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

while($rw = mysql_fetch_array($result)){
	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
	
	$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];
	}
	
	echo"  <tr $color>
			<td >$rw[3]</td>
			<td >$rw[2]</td>
			<td  align='left'>$rw[4] - $rw[5]</td>
			<td >".number_format($rw[6], $DecimalBase)."</td>
			<td >".number_format($rw[7], $DecimalBase)."</td>
			<td >".number_format($rw[8], $DecimalBase)."</td>
			<td >".number_format($rw[9], $DecimalBase)."</td>";

	if ($showcost == 1) {
	echo"  	<td >$rw[10]</td>
			<td >".number_format($ProductionUnitCost, $DecimalBase)." </td>
			<td >".number_format($ProductionTotalCost, $DecimalBase)." </td>";
	} 	
	
	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 ";
		
		echo "<tr><td colspan='$colsp'>"; 
		echo"<tr height='20'><td colspan='".($colsp)."'>";
		echo "<table width='100%' border='0' align='left' cellpadding='0' cellspacing='0' class='detail' style='table-layout:fixed'>
			<col width=40><col width=100><col width=250><col width=100><col width=80><col width=80>";
		if ($showcost == 1)
		echo "	<col width=120><col width=120>";
			  
		$resultdt = mysql_query($querydt, $connection);
		while($rwdt = mysql_fetch_array($resultdt)){
			
			if($col1%2==0){
				$color1 = "style='background-color:".$report_color1."'";
			}else{
				$color1 = "style='background-color:".$report_color2."'";
			}
			
			if($curr == '' or $curr == $Base1) {
				$ProductionDtUnitCost  = $rwdt[5];
				$ProductionDtTotalCost = $rwdt[7];
			} else {
				$ProductionDtUnitCost  = $rwdt[6];
				$ProductionDtTotalCost = $rwdt[8];
			}
			
			echo "<tr $color1>"; 
			echo "	<td align='left' valign='top' >&nbsp;</td>";
			echo "	<td align='left' valign='top' style='border-right:1px solid black; '>". $rwdt[0] ."</td>";
			echo "	<td align='left' valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rwdt[1] ."</td>";
			echo "	<td align='center' valign='top' style='border-right:1px solid black; '>". $rwdt[2] ."</td>";
			echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rwdt[3], $DecimalBase) ."</td>";
			echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rwdt[4], $DecimalBase) ."</td>";
			
			if ($showcost == 1 ) {
				echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>".number_format($ProductionDtUnitCost, $DecimalBase)."</td>";
				echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>".number_format($ProductionDtTotalCost, $DecimalBase)."</td>";
			}	
			
			echo "</tr>";
		}
		
		echo "</table></td></tr>";
	}
	$TotalAmount = $TotalAmount + $ProductionTotalCost;	
	echo "</tr>";
}	
// Report Totals

if ($showcost == 1) {
	echo "<tr height='5'><td colspan='$colsp'><h4></td></tr>"; 
	echo "<tr height='10'><td colspan='$colsp'>&nbsp;</td></tr>"; 
	echo "<tr class='totals'>"; 
	echo "  <td align='right' colspan='9'>Total &nbsp;</td>";
	echo "	<td align='center' valign='top' >". number_format($TotalAmount, $DecimalBase) ."</td>";
	echo "</tr>";	
}	

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



function current_server_time($connection){

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

  return $now;
}

function explodeword($date)
{

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


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

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

?>