<?php

session_start();

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

include("config.inc.php");
include("Functions_Purchase.php");

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



$querylog="select ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."') ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2 from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_RestrictMachine,0) As Module_RestrictMachine ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


/*
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<script type="text/javascript" language="javascript">


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='insertproduction' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SPrdId' value='$SPrdId'>
<input type='text' name='SPrdDtId' value='$SPrdDtId'>
<input type='text' name='SItemType' value='$SItemType'>

HERE;
*/
$message='';

//Submit Record Mode

if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if(empty($PPrdActive)) $PPrdActive = 0;
	
	$vPrdDate         = $PPrdDate;
	$vPrdRemark       = $PPrdRemark;
	$vPrdActive       = $PPrdActive;
	
	if ($SPrdId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$vPrdId = get_nextsequence('ProdRecipe_Id','',$connection);
		fcommit();
			
		
		fbegin();
		$query = " INSERT INTO ProdRecipe (ProdRecipe_Id, ProdRecipe_Reference, ProdRecipe_Date, ProdRecipe_Remark, ProdRecipe_Active, ProdRecipe_BelongsToGroup, User_Account )".
				 " VALUES ( ".$vPrdId.", Null, '".insertMySQLDate($vPrdDate)."', '".ereg_replace("'", "\'", trim($vPrdRemark))."', $vPrdActive, $FI_BelongsToGrp, ".
				 "          '".$HTTP_SESSION_VARS['useraccount']."' )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdId = $vPrdId;
			$PPrdId = $vPrdId;
			fcommit();
			
		}else{
			$PPrdId = "";
			$SPrdId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}

	
	//Insert Detail Tables
	if ($SPrdId != "" && $SPrdDtId == "" && $ErrorExists == 0){
	
		if (empty($txtPrdDtQtyF))	$txtPrdDtQtyF = 0;
		if (empty($txtPrdDtQty))	$txtPrdDtQty = 0;
		if (empty($txtCostOption))	$txtCostOption = 1;
		
		if (empty($txtPrdDtCost))	   $txtPrdDtCost = 0;
		if (empty($txtWasteRate))	   $txtWasteRate = 0;
		if (empty($txtWastePerBillet)) $txtWastePerBillet = 0;
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		// Case Not Pack Item
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
		if ($ItemPack != 1) {
		
			$vPrdDtQty   = 0;
			$vPrdDtQty   = $txtPrdDtQty;
			$vPrdDtQtyF  = $txtPrdDtQtyF;
			$vPrdDtCost  = $txtPrdDtCost;
			$vWasteRate  = $txtWasteRate;
			$vWastePerBillet = $txtWastePerBillet;
						
			$vPrdDtCostBase1    = ConvertCurrency($txtCurr, $base1, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
			$vPrdDtCostBase2    = ConvertCurrency($txtCurr, $base2, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
				
			if ($SItemType == 'RM') {
							
				fbegin();
				$vPrdDtId = get_nextsequence('ProdRecipeRM_Id','',$connection);
				fcommit();			
						 
				fbegin();	 
				$query = " INSERT INTO ProdRecipeRM (ProdRecipeRM_Id, ProdRecipe_Id, ProdRecipe_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
						 " Warehouse_Code, ProdRecipeRM_QuantityFrom, ProdRecipeRM_Quantity, ProdRecipeRM_Remark, Item_UnitCoef, Item_Unit2Qty, ".
						 " ProdRecipeRM_DistOption, Currency_Code, ProdRecipeRM_Cost, ProdRecipeRM_CostBase1, ProdRecipeRM_CostBase2, ".
						 " ProdRecipeRM_WasteRate, ProdRecipeRM_WastePerBillet ) ".
						 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$txtItemCode."',  Null, 0, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
						 "          $vPrdDtQtyF, $vPrdDtQty, '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', 0, 0, $txtCostOption, '".$txtCurr."', ".
						 "          $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, $vWasteRate, $vWastePerBillet ) ";
			}
			else if ($SItemType == 'FG') {
				fbegin();
				$vPrdDtId = get_nextsequence('ProdRecipeFG_Id','',$connection);
				fcommit();			
						 
				fbegin();	 
				$query = " INSERT INTO ProdRecipeFG (ProdRecipeFG_Id, ProdRecipe_Id, ProdRecipe_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
						 " Warehouse_Code, ProdRecipeFG_QuantityFrom, ProdRecipeFG_Quantity, ProdRecipeFG_Remark, Item_UnitCoef, Item_Unit2Qty, ProdRecipeFG_DistOption ) ".
						 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$txtItemCode."',  Null, 0, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
						 "          $vPrdDtQtyF, $vPrdDtQty, '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', 0, 0, $txtCostOption ) ";
			}
				
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;
				
			if ($result){
				fcommit();
			}else{
				$txtPrdDtId  = "";
				$ErrorExists = 1;
				$message  = mysql_error($connection); 
				frollback();
			}
			
			
									
		}	// End Case Not Pack Item
		else {
								
			fbegin();	 
					
			$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
							" FROM PackDt ".
							" WHERE Item_Code = '".$txtItemCode."'  ";
										   
			$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
			while($packdt_rows=mysql_fetch_array($packdt_result)){
					
				$vItemCodePacked = $packdt_rows[0];
				$vItemCode 		 = $packdt_rows[1];
				$vPackDtQty 	 = $packdt_rows[2];
				$vPackDtCostPer  = $packdt_rows[3];
						
				$vPrdDtQty    = 0;
				$vPrdDtQty    = $txtPrdDtQty;
				$vPrdDtQty    = $vPrdDtQty*$vPackDtQty;
				
				$vPrdDtQtyF   = $txtPrdDtQtyF;
				$vPrdDtQtyF   = $vPrdDtQtyF*$vPackDtQty;
				
				$vPrdDtCost  = $txtPrdDtCost*$vPackDtCostPer/100;
				$vWasteRate  = $txtWasteRate;
				$vWastePerBillet = $txtWastePerBillet;
				
				$vPrdDtCostBase1    = ConvertCurrency($txtCurr, $base1, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
				$vPrdDtCostBase2    = ConvertCurrency($txtCurr, $base2, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
						
				if ($SItemType == 'RM') {
							
					fbegin();
					$vPrdDtId = get_nextsequence('ProdRecipeRM_Id','',$connection);
					fcommit();			
								 
					fbegin();	 
					$query = " INSERT INTO ProdRecipeRM (ProdRecipeRM_Id, ProdRecipe_Id, ProdRecipe_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
							 " Warehouse_Code, ProdRecipeRM_QuantityFrom, ProdRecipeRM_Quantity, ProdRecipeRM_Remark, Item_UnitCoef, Item_Unit2Qty, ".
							 " ProdRecipeRM_DistOption, Currency_Code, ProdRecipeRM_Cost, ProdRecipeRM_CostBase1, ProdRecipeRM_CostBase2, ".
							 " ProdRecipeRM_WasteRate, ProdRecipeRM_WastePerBillet ) ".
							 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$vItemCode."', '".$vItemCodePacked."', $vPackDtQty, ".
							 "          '".ereg_replace("'", "\'", trim($lstWarehouse))."', $vPrdDtQtyF, $vPrdDtQty, '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', ".
							 "          0, 0, $txtCostOption, '".$txtCurr."', $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, $vWasteRate, $vWastePerBillet ) ";
						 
				}
				else if ($SItemType == 'FG') {
					fbegin();
					$vPrdDtId = get_nextsequence('ProdRecipeFG_Id','',$connection);
					fcommit();			
								 
					fbegin();	 
					$query = " INSERT INTO ProdRecipeFG (ProdRecipeFG_Id, ProdRecipe_Id, ProdRecipe_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
							 " Warehouse_Code, ProdRecipeFG_QuantityFrom, ProdRecipeFG_Quantity, ProdRecipeFG_Remark, Item_UnitCoef, Item_Unit2Qty, ProdRecipeFG_DistOption ) ".
							 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$vItemCode."',  '".$vItemCodePacked."', $vPackDtQty, ".
							 "          '".ereg_replace("'", "\'", trim($lstWarehouse))."', $vPrdDtQtyF, $vPrdDtQty, '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', 0, 0, $txtCostOption ) ";
				}		
				$result=mysql_query($query,$connection);
				//echo $query."<br>";
						
						
			} // End Loop Of Packdt
					
			//echo $ErrorExists; echo $message; exit;
			if ($result){
				fcommit();
			}else{
				$txtPrdDtId = "";
				$message  = mysql_error(); 
				frollback();
			}	
			
		} // End CasePack Item
		
	} // End Case Insert In Detail Tables

} 


//Edit Detail Tables
else if (($mode == "editdt" || $mode == "editdt-ajax") && $SPrdId != "" && $SPrdDtId != ""){


	if (empty($txtPrdDtQty))		$txtPrdDtQty = 0;
	if (empty($txtPrdDtQtyF))		$txtPrdDtQtyF = 0;
	if (empty($txtCostOption))	    $txtCostOption = 1;
	if (empty($txtPrdDtCost))	    $txtPrdDtCost = 0;
	if (empty($txtWasteRate))	    $txtWasteRate = 0;
	if (empty($txtWastePerBillet))  $txtWastePerBillet = 0;
		
	$vPrdDate    = $PPrdDate;			
	$vPrdDtQty   = 0;
	$vPrdDtQty   = $txtPrdDtQty;
	$vPrdDtQtyF  = 0;
	$vPrdDtQtyF  = $txtPrdDtQtyF;
	$vPrdDtCost  = $txtPrdDtCost;
	$vWasteRate  = $txtWasteRate;
	$vWastePerBillet = $txtWastePerBillet;
	
	$vPrdDtCostBase1    = ConvertCurrency($txtCurr, $base1, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
	$vPrdDtCostBase2    = ConvertCurrency($txtCurr, $base2, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
		
			
	fbegin();	
					
	if ($SItemType == 'RM') {
		$query = " UPDATE ProdRecipeRM SET  ".
				 " ProdRecipeRM_QuantityFrom = $vPrdDtQtyF, ProdRecipeRM_Quantity = $vPrdDtQty, ".
				 " Warehouse_Code = '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
				 " ProdRecipeRM_Remark = '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', ".
				 " ProdRecipeRM_DistOption =  $txtCostOption, ".
				 " Currency_Code = '".$txtCurr."', ProdRecipeRM_Cost = $vPrdDtCost, ".
				 " ProdRecipeRM_CostBase1 = $vPrdDtCostBase1, ProdRecipeRM_CostBase2 = $vPrdDtCostBase2, ".
				 " ProdRecipeRM_WasteRate = $vWasteRate, ProdRecipeRM_WastePerBillet = $vWastePerBillet ".
				 " Where ProdRecipeRM_Id = '".$SPrdDtId."'";
	}
	else if ($SItemType == 'FG') {
		$query = " UPDATE ProdRecipeFG SET  ".
				 " ProdRecipeFG_QuantityFrom = $vPrdDtQtyF, ProdRecipeFG_Quantity = $vPrdDtQty, ".
				 " Warehouse_Code = '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
				 " ProdRecipeFG_Remark = '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', ".
				 " ProdRecipeFG_DistOption =  $txtCostOption ".
				 " Where ProdRecipeFG_Id = '".$SPrdDtId."'";
	}
							 
	//echo $query; exit;
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();
			
	}else{
		$message  = mysql_error(); 
		frollback();
	}				

}

//Delete Raw Materials
else if ($mode == "deletedtRM" && $SPrdDtId != ""){

	$AllowDelete = 1;
	$message  = '';
	
	/*if ($AllowDelete == 1) {
		//Check Each ProdRecipeRM If Has Related ID In ProductionRM
		$query = " Select Count(*) ".
				 " From ProductionRM ".
				 " Where ProductionRM.RelatedDt_Id = '".$SPrdDtId."' ";
 
		$result = selectData($connection, $query);
		$RelatedIDExists = $result[0];
		
		if ($RelatedIDExists > 0 ){
			$message  = 'Delete not allowed, item is used in production.';
			$AllowDelete = 0;
		}
	
	}*/

	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		$ErrorExists    = 0;

		$querypack = " SELECT ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Item_Code ".
					 " FROM ProdRecipeRM ".
					 " Where ProdRecipeRM.ProdRecipeRM_ID = '".$SPrdDtId."'";
					 
								   
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
			
			// Delete From ProdRecipeRM For Selected Record
			$query = " DELETE FROM ProdRecipeRM ".
					 " WHERE ProdRecipeRM_ID = '".$SPrdDtId."'";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select ProdRecipeRM_ID, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Item_Code  ".
					   " From ProdRecipeRM  ".
					   " Where ProdRecipeRM.ProdRecipe_ID = '".$SPrdId."' ".
					   " And ProdRecipeRM.Item_CodePacked =  '".$vItemCodePacked."'  ";
					
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vPrdDtId =	$rowsdt[0];
					
				// Delete From ProdRecipeRM For Selected Record
				$query = " DELETE FROM ProdRecipeRM ".
						 " WHERE ProdRecipeRM_ID = ".$vPrdDtId;
						 
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
	} // End If No Constraints Found On Delete
	
}

//Delete Finished Good
else if ($mode == "deletedtFG" && $SPrdDtId != ""){

	$AllowDelete = 1;
	$message  = '';
	
	/*if ($AllowDelete == 1) {
		//Check Each ProdRecipeFG If Has Related ID In ProductionFG
		$query = " Select Count(*) ".
				 " From ProductionFG ".
				 " Where ProductionFG.RelatedDt_Id = '".$SPrdDtId."' ";
 
		$result = selectData($connection, $query);
		$RelatedIDExists = $result[0];
		
		if ($RelatedIDExists > 0 ){
			$message  = 'Delete not allowed, item is used in production.';
			$AllowDelete = 0;
		}
	
	}*/

	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		$ErrorExists    = 0;

		$querypack = " SELECT ProdRecipeFG.Item_CodePacked, ProdRecipeFG.Item_Code ".
					 " FROM ProdRecipeFG ".
					 " Where ProdRecipeFG.ProdRecipeFG_ID = '".$SPrdDtId."'";
					 
								   
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
			
			// Delete From ProdRecipeFG For Selected Record
			$query = " DELETE FROM ProdRecipeFG ".
					 " WHERE ProdRecipeFG_ID = '".$SPrdDtId."'";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select ProdRecipeFG_ID, ProdRecipeFG.Item_CodePacked, ProdRecipeFG.Item_Code  ".
					   " From ProdRecipeFG  ".
					   " Where ProdRecipeFG.ProdRecipe_ID = '".$SPrdId."' ".
					   " And ProdRecipeFG.Item_CodePacked =  '".$vItemCodePacked."'  ";
					
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vPrdDtId =	$rowsdt[0];
					
				// Delete From ProdRecipeFG For Selected Record
				$query = " DELETE FROM ProdRecipeFG ".
						 " WHERE ProdRecipeFG_ID = ".$vPrdDtId;
						 
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
	} // End If No Constraints Found On Delete	
	
}


//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SPrdId != ''){

	$AllowDelete = 1;
	$message  = '';
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
	    $query = " DELETE FROM ProdRecipeRM ".
				 " WHERE ProdRecipe_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		$query = " DELETE FROM ProdRecipeFG ".
				 " WHERE ProdRecipe_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		$query = " DELETE FROM ProdRecipe ".
				 " WHERE ProdRecipe_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error();   
		
	}
	
}

//Post Mode	
else if($mode == "post" && $SPrdId != ''){  

	if(empty($txtActive)) $txtActive = 0;
	
	$vPrdDate         = $txtDate;
	$vPrdRemark       = $txtRemark;
	$vPrdActive       = $txtActive;
	
    $SaveAllow   = 1;
	$ErrorExists = 0;
	
	
	$sub_query = " Select Count(*) FROM ProdRecipeFG ".
				 " WHERE ProdRecipe_Id = ".$SPrdId;
	$result = selectData($connection, $sub_query);
	$vPrdCountFG = $result[0];
	if($vPrdCountFG == '') $vPrdCountFG = 0;
	
	if ($vPrdCountFG == 0) {
		$ErrorExists = 1;
		$message = "Save not allowed. Please add at least one item (Finished Good).";
	}
	
	if ($ErrorExists == 0) {
		$sub_query = " Select Count(*) FROM ProdRecipeRM ".
					 " WHERE ProdRecipe_Id = ".$SPrdId;
		$result = selectData($connection, $sub_query);
		$vPrdCountRM = $result[0];
		if($vPrdCountRM == '') $vPrdCountRM = 0;
		
		if ($vPrdCountRM == 0) {
			$ErrorExists = 1;
			$message = "Save not allowed. Please add at least one item (Raw Material).";
		}
	}
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From ProdRecipeRM ".
				 " Where ProdRecipe_Id = '".$SPrdId."' ".
				 " And (Item_CodePacked Is Not Null and Item_CodePacked != '') ";
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$sub_rowcount = mysql_num_rows ($sub_result);
	
	if ($sub_rowcount > 0) {
		while($sub_row=mysql_fetch_array($sub_result)){
			$ItemQty = 0;
			$ItemPackQty = 0;
			
			$CheckQty = 0;
			$PackDtCode = '';
			$PackDtQty  = 0;
			
			$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
						  " From PackDt ".
						  " Where Item_Code = '".$sub_row[0]."' ";
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
			while($sub_row1=mysql_fetch_array($sub_result1)){
				// PackDt Items Should Be Different And Have Same Qty
				if ($PackDtCode != '' && $PackDtCode != $sub_row1[1] && $PackDtQty  == $sub_row1[2])
					$CheckQty = 1;
				
				$PackDtCode = $sub_row1[1];
				$PackDtQty  = $sub_row1[2];
			}
			
			// If PackDt Items Are Different And Have Same Qty Then Check For Qty Differences
			if ($CheckQty == 1) {
				$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
							  " From PackDt ".
							  " Where Item_Code = '".$sub_row[0]."' ";
				$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
				while($sub_row1=mysql_fetch_array($sub_result1)){
					$sub_query2 = " Select Item_CodePacked, Item_Code, Sum(ifNull(ProdRecipeRM_Quantity,0)) As ProdRecipeRM_Quantity ".
								  " From ProdRecipeRM ".
								  " Where ProdRecipe_Id = '".$SPrdId."' ".
								  " And Item_CodePacked = '".$sub_row1[0]."' ".
								  " And Item_Code = '".$sub_row1[1]."' ".
								  " Group by Item_CodePacked, Item_Code ";
								  
					$sub_result2 = selectData($connection, $sub_query2);
					$ItemPackQty = $sub_result2[2] / $sub_row1[2];
					if (empty($sub_result2[2])) $ItemPackQty = -1;
					
					if ($ItemQty == 0) $ItemQty = $ItemPackQty;
					if ($ItemQty != $ItemPackQty) $SaveAllow = 0;
					
					
				}
			}		  
			
		}
	}
	
		
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$HTTP_SESSION_VARS['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$HTTP_SESSION_VARS['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$HTTP_SESSION_VARS['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($vPrdDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($vPrdDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;
	

	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
		$sub_query2 = " UPDATE ProdRecipeRM SET ".
					  " ProdRecipe_Date = '".insertMySQLDate($vPrdDate)."' ".
					  " WHERE ProdRecipe_Id = $SPrdId ";
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
			
		$sub_query2 = " UPDATE ProdRecipeFG SET ".
					  " ProdRecipe_Date = '".insertMySQLDate($vPrdDate)."' ".
					  " WHERE ProdRecipe_Id = $SPrdId ";
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 	

			
		$query = " UPDATE ProdRecipe SET ".
				 " ProdRecipe_Date = '".insertMySQLDate($vPrdDate)."' ,  ".
				 " ProdRecipe_Remark = '".ereg_replace("'", "\'", trim($vPrdRemark))."', ".
				 " ProdRecipe_Active = '".$vPrdActive."' ".
				 " WHERE ProdRecipe_Id = $SPrdId ";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
			fcommit();
						
			$query   = " SELECT ProdRecipe_Reference FROM ProdRecipe WHERE ProdRecipe_Id = $SPrdId ";
			$result  = selectData($connection, $query);
			$vPrdRef = $result[0];
					
			if ($vPrdRef == ''){
							
				$vProjCostCent = '';
							
				fbegin();
				$vPrdRef = get_nextsequence('ProdRecipe_Reference',$vProjCostCent,$connection);	
				fcommit();
							
				$query = " UPDATE ProdRecipe SET ".
						 " ProdRecipe_Reference = $vPrdRef ".
						 " WHERE ProdRecipe_Id = $SPrdId ";
							
				if (!updateData($connection, $query, true)) 
					$message  = mysql_error();
						
			}

		} else{
			$message  = mysql_error(); 
			frollback();
		}	
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllow == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';			
			
		frollback();
	}	
}


$message = ereg_replace(' ','%20',$message);
$WarningMsg = ereg_replace(' ','%20',$WarningMsg);

$PPrdRemark = ereg_replace(' ','%20',$PPrdRemark);
$PPrdWhCode = ereg_replace(' ','%20',$PPrdWhCode);

$lstWarehouse  = ereg_replace('#','%23',$lstWarehouse);
$PPrdRemark    = ereg_replace('#','%23',$PPrdRemark);
$PPrdWhCode    = ereg_replace('#','%23',$PPrdWhCode);

$lstWarehouse  = ereg_replace('&','%26',$lstWarehouse);
$PPrdRemark    = ereg_replace('&','%26',$PPrdRemark);
$PPrdWhCode    = ereg_replace('&','%26',$PPrdWhCode);


if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_ProductionTemplate.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPrdId=".$SPrdId."&PrPrdRef=".$vPrdRef."&message=".$message);
	else
		header ("Location: ./Form_ProductionTemplate.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_ProductionTemplateSearch.php?message=".$message);
//else if ($mode == "deletedtRM" || $mode == "deletedtFG")		
//	header ("Location: ./Form_ProductionTemplate.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);
else if ($mode == "editdt")		
	header ("Location: ./Form_ProductionTemplateDetail.php?PItemType=".$SItemType."&actionmode=".$mode."&mainaction=".$mainmode."&PPrdId=".$SPrdId."&PPrdDate=".$PPrdDate."&PPrdDtId=".$SPrdDtId."&message=".$message);	
else if($mode == "submitrecord") {
    header ("Location: ./Form_ProductionTemplateDetail.php?PItemType=".$SItemType."&actionmode=".$mode."&mainaction=".$mainmode."&PPrdId=".$PPrdId."&PPrdDate=".$PPrdDate.
			"&PPrdActive=".$PPrdActive."&PPrdRemark=".$PPrdRemark."&message=".$message);
}


$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SPrdId;
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);



/*
print <<<HERE
</form>
</body>

HERE;
*/

?>