<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php
header("Content-type: text/html; charset=windows-1256");
session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}


print <<< HERE
<HTML>
<HEAD>
<TITLE> Production Template Report </TITLE>

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

.dtitalic {
			font-style: italic;
		}
		
.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);
}


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, ifNull(ListOfProductionMaskQty,2) as ListOfProductionMaskQty from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  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);
}

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


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


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

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


$ReportTitle = 'Production Template List'; 

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

if ($prtheader == 1){
	ShowReportHeader('Productions Template','portrait', $connection);
} else {
	ShowReportTitle('Productions Template','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;

$dispfromitem = $fromitem;
$disptoitem   = $toitem;
$dispcurr     = $curr;

$dispfromdate = $fromdate;
$disptodate   = $todate;
  
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($fromwarehouse))  $fromwarehouse = 'null';
else  $fromwarehouse = "'".$fromwarehouse."'";      

if (empty($qtyprod)) $qtyprod = 1;
if (empty($showqtyexists)) $showqtyexists = 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($showlastprice)) $showlastprice = 0;

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

<tr><td>
<table class='params' width='1050' border='0' align='left' style='table-layout:fixed' >
<tr>
  <td width="12%"><b>Date From/To:</b></td>
  <td width="88%">$dispfromdate - $disptodate </td>
</tr>
<tr>
  <td width="12%"><b>Item From/To:</b></td>
  <td width="88%">$dispfromitem - $disptoitem </td>
</tr>
<tr>
  <td width="12%"><b>Currency:</b></td>
  <td width="88%">$curr</td>
</tr>
<tr height='5'><td colspan=2><h4></td></tr>
</table>
</td></tr>

<tr><td><br>
HERE;


echo "<table width='1050' border='0' align='left' class='master' style='table-layout:fixed'>
	  <col width=150>
	  <col width=300>
	  <col width=100>
	  ";
if($showlastprice == 1)
	echo "<col width=100><col width=110><col width=110>"; 
else echo "<col width=310>";

echo"  <tr>";
echo"	<th colspan='2' align='left'>Item Code / Description</th>";
echo"	<th>From Qty </th>";
echo"	<th>To Qty </th>";
if($showlastprice == 1) {
		echo"	<th>Cost</th>";
		echo"	<th>Cost per Unit</th>";
	}
echo"  </tr>";

if($showlastprice == 1) $colsp = '7';
else $colsp = '5';

echo"<tr height='5'><td colspan='$colsp'><h5></td></tr>";
echo"<tr height='20'><td colspan='$colsp'>";
echo "<table width='1000' border='0' align='left' class='detail' style='table-layout:fixed'>
		<col width=20>
		<col width=130>
		<col width=300>
		<col width=110>
		<col width=110>
		<col width=110>
		<col width=110>
		<col width=110>
		<tr>";
	echo"	<th >&nbsp;</th>";
	echo"	<th align='left'>Item Code</th>";
	echo"	<th align='left'>Description</th>";
	echo"	<th align='right'>From Qty</th>";
	echo"	<th align='right'>To Qty</th>";
	if($showlastprice == 1) 
		echo"	<th align='right'>Last Price</th>";
	else echo"	<th align='right'>Cost</th>";
	echo"	<th align='right'>From Total</th>";
	echo"	<th align='right'>To Total</th>";
	echo"</tr>";
		
echo"</table>";
echo"</td></tr>";		
echo"<tr height='5'><td colspan=$colsp><h4></td></tr>";

		 


$query = "select prodrecipefg.item_code as item_code, itemsFG.item_description as descriptionfg, ProdRecipeFG_QuantityFrom,ProdRecipeFG_Quantity,
		prodreciperm.item_code as item_codedt, itemsRM.item_description as descriptionrm, ProdRecipeRM_QuantityFrom, ProdRecipeRM_Quantity,
		if('$curr'='$Base1',ifNull(GetLastValuesFunc('$Base1','$Base1',prodreciperm.Item_code), ProdRecipeRM_CostBase1),
		if('$curr'='$Base2',ifNull(GetLastValuesFunc('$Base2','$Base2',prodreciperm.Item_code),ProdRecipeRM_CostBase2)
		,ifNull(GetLastValuesFunc('$Base1','$Base1',prodreciperm.Item_code),ProdRecipeRM_CostBase1 ))), prodrecipefg.ProdRecipe_Id as ProdRecipe_Id,itemsRM.item_production
		from prodreciperm
		left join prodrecipefg on prodrecipefg.ProdRecipe_Id = prodreciperm.ProdRecipe_Id
		inner join items as itemsRM on itemsRM.item_code = prodreciperm.item_code
		inner join items as itemsFG on itemsFG.item_code = prodrecipefg.item_code
		where date_format(prodrecipefg.ProdRecipe_Date,'%Y-%m-%d') between $fromdate and $todate 
		and prodrecipefg.item_code Between ifNull(".$fromitem.", prodrecipefg.item_code) and ifNull(". $toitem.", prodrecipefg.item_code)
		order by ProdRecipe_Id, item_code, item_codedt";

//echo $query;exit;		

$MasterItemCode = '';
$totcost=0;
$result=mysql_query($query,$connection) or die(mysql_error());
$col=0;
$fromsum = 0;
$tosum = 0;

$totrm=0;

while($rows=mysql_fetch_row($result)){
	
	
	$fromtotal = 0;
	$tototal = 0;
	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
	
	
		
	if ($MasterItemCode == '' || $MasterItemCode != $rows[0]) {
		
		
		$querycost = "select sum(ProdRecipeRM_QuantityFrom*GetLastValuesFunc('$Base1','$Base1',prodreciperm.Item_code)) as TotalCostRM
		from prodreciperm
		left join prodrecipefg on prodrecipefg.ProdRecipe_Id = prodreciperm.ProdRecipe_Id
		inner join items as itemsRM on itemsRM.item_code = prodreciperm.item_code
		inner join items as itemsFG on itemsFG.item_code = prodrecipefg.item_code
		where itemsRM.item_production=0 and  prodrecipefg.item_code Between ifNull('".$rows[0]."', prodrecipefg.item_code) and ifNull('". $rows[0]."', prodrecipefg.item_code)";

		$resultcost=mysql_query($querycost,$connection) or die(mysql_error());
        while($rowcost=mysql_fetch_array($resultcost)){
	    extract($rowcost);
        }	
		
		
		$query2 = " select A.item_code as Itemcoderm,A.ProdRecipeRM_QuantityFrom,A.prodrecipe_id from prodreciperm A,items B ,prodrecipefg C 
		where A.prodrecipe_id=C.prodrecipe_id and A.item_code=B.item_code and B.item_production=1 and C.prodrecipe_id=$rows[9] ";
		
		//echo $query2;

		$result2=mysql_query($query2,$connection) or die(mysql_error());
		while($rows2=mysql_fetch_row($result2)){
			
		$query3 = " select A.item_Code,B.prodrecipefg_quantityfrom,A.prodreciperm_quantityfrom,
		            GetLastValuesFunc('$Base1','$Base1',A.Item_code),
					(A.prodreciperm_quantityfrom*GetLastValuesFunc('$Base1','$Base1',A.Item_code)) as TotalCostWIP,C.item_production from prodreciperm A,prodrecipefg B,items C
                    where A.prodrecipe_id=B.prodrecipe_id and  A.item_Code=C.item_code and B.item_Code='$rows2[0]'	";
					
		//echo $query3;exit;			
		
		$result3=mysql_query($query3,$connection) or die(mysql_error());
		while($rows3=mysql_fetch_row($result3)){
			
		
		
        $totrm= $totrm+$rows3[4];		
		$prodqty=$rows3[1];	
		
	
			
		}	
		 
        //echo $rows2[1];//exit;
        		 
         $TotalCostRM=$TotalCostRM+($totrm/$prodqty*$rows2[1]);	
         //echo $TotalCostRM;// exit;		
		 $totrm=0;	
		 
		}	
		
		
        //echo $totrm;exit;
		echo "<tr>"; 
		echo "	<th align='left' valign='top' >". $rows[0] ."</th>";
		echo "	<th align='left' valign='top'>". $rows[1] ."</th>";
		echo "	<th align='center' valign='top'>". number_format($rows[2], $ListOfProductionMaskQty) ." </th>";
		echo "	<th align='center' valign='top'>". number_format($rows[3], $ListOfProductionMaskQty) ." </th>";
		echo "	<th align='center' valign='top'>".number_format($TotalCostRM, $DecimalBase)."</th><th align='center' valign='top'>".number_format($TotalCostRM/$rows[3], $DecimalBase)."</th>";		
	
		echo "</tr>";

		$MasterItemCode = $rows[0];
	}
	
	echo "<tr><td colspan='$colsp'>"; 
	echo "<table width='1000' border='0' align='left' class='detail' style='table-layout:fixed'>
			<col width=20><col width=130><col width=300>
			<col width=110><col width=110>
			<col width=110><col width=110>
			<col width=110>";
	
	$fromtotal = $rows[8]*$rows[6];
	$tototal = $rows[8]*$rows[7];
	$unitcost=$rows[8];
	
	//echo $fromtotal;
	
	    if ($rows[10]==1) {
			
			
		$querySemi = " select A.item_Code,C.item_production,A.prodrecipefg_quantityfrom,
		               sum(B.prodreciperm_quantityfrom*ifNull(GetLastValuesFunc('NGN','NGN',B.Item_code),0))/A.prodrecipefg_quantityfrom as CostUnit 
					   from prodrecipefg A,prodreciperm B,items C where  A.prodrecipe_id=B.prodrecipe_id and  C.item_code=B.item_code and A.item_code='$rows[4]' group by A.item_code ";  
                       
		//echo $querySemi;///exit;
		
		$resultSemi=mysql_query($querySemi,$connection) or die(mysql_error());
        while($rowSemi=mysql_fetch_array($resultSemi)){
	    extract($rowSemi);
        }	
			
			//echo $rows[7];exit;
			
			$fromtotal = $CostUnit*$rows[7];
			$tototal = $CostUnit*$rows[7];
			$unitcost=$CostUnit;
		}

	
	echo "<tr $color>";
	echo "	<td align='left' valign='top' >&nbsp;</td>";
	echo "	<td align='left' valign='top' >". $rows[4] ."</td>";
	echo "	<td align='left' valign='top' >". $rows[5] ."</td>";
	echo "	<td align='right' valign='top'>". number_format($rows[6], $ListOfProductionMaskQty) ."</td>";//from Qty
	echo "	<td align='right' valign='top'>". number_format($rows[7], $ListOfProductionMaskQty) ."</td>";//to Qty
	echo "	<td align='right' valign='top' >". number_format($unitcost, $DecimalBase) ."</td>";
	echo "	<td align='right' valign='top'>". number_format($fromtotal, $DecimalBase) ."</td>";
	echo "	<td align='right' valign='top' >". number_format($tototal, $DecimalBase) ."</td>";
	echo "</tr>";
	
	$fromsum = $fromsum + $fromtotal ;
	$tosum = $tosum + $tototal ;
	
	$col+=1;
	echo "</table>";	
	echo "</td></tr>";
}	
echo "<tr $color>"; 
echo "	<td align='right' valign='top' colspan='4'>From Total Sum: &nbsp;&nbsp;&nbsp;". number_format($fromsum, $ListOfProductionMaskQty) ."</td>";
echo "</tr>";
echo "<tr $color>"; 
echo "	<td align='right' valign='top' colspan='4'>To Total Sum: &nbsp;&nbsp;&nbsp;". number_format($tosum, $ListOfProductionMaskQty) ."</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;
}

function insertMySQLDate($data){
	$data = insertDate($data);
	return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");;
}

function insertDate($data){
	return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
}

function selectData($conn, $query){
	$result = mysql_query($query, $conn);
	$cur = mysql_fetch_row($result);		
	return $cur;
}


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

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

?>