<?php

session_start();

if($_SESSION['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($_SESSION['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 ".$_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 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);
}

//Read From ProductionSetup Table 
$queryProductionSetup="Select ifNull(DisableIdeal,0) As DisableIdeal, ifNull(productionReq_packdt,0) As productionReq_packdt From ProductionSetup";
$resultProductionSetup=mysql_query($queryProductionSetup,$connection) or die(mysql_error());
while($rowProductionSetup=mysql_fetch_array($resultProductionSetup)){
	extract($rowProductionSetup);
}



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'>
<input type='text' name='SPrdTempId' value='$SPrdTempId'>
<input type='text' name='STabIndex' value='$STabIndex'>
<input type='text' name='SPrdDivId' value='$SPrdDivId'>

HERE;

$message='';

//Submit Record Mode

if ($mode == "submitrecord"){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (empty($txtConfirmed)) $txtConfirmed = 0;
	
						  
	$vPrdDate         = $txtDate;
	$vPrdRemark       = $txtRemark;
	$vPrdManager      = $txtManager;
	$vPrdShift        = $txtShift;
	$vPrdConfirmed    = $txtConfirmed;
	
	if (empty($txtCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";   
	
	
	
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code FG.';
		}
	}
	if ($txtWhCode != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$txtWhCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code FG.';
		}
	}
	if ($txtWhCodeRM != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$txtWhCodeRM."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code RM.';
		}
	}
	
	
	//Insert Master Table
	if ($SPrdId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$vPrdId = get_nextsequence('ProductionReq_Id','',$connection);
		fcommit();
			
		
		fbegin();
		$query = " INSERT INTO Temp_ProductionRequest (ProductionReq_Id, ProductionReq_Reference, ProductionReq_Date, ProductionReq_Remark, ".
				 " ProductionReq_Manager, ProductionReq_Shift, ProductionReq_BelongsToGroup, ProductionReq_Posted, ProductionReq_Confirmed, ".
				 " Project_Code, CostCenter_Code, User_Account, Logged_Code ) ".
				 " VALUES ( ".$vPrdId.", Null, '".insertMySQLDate($vPrdDate)."', '".ereg_replace("'", "\'", trim($vPrdRemark))."', ".
				 "          '".ereg_replace("'", "\'", trim($vPrdManager))."', '".ereg_replace("'", "\'", trim($vPrdShift))."', ".
				 "          $FI_BelongsToGrp, 0, $vPrdConfirmed, $ProjectCode, $CostCentCode, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdId = $vPrdId;
			fcommit();
			
			//Insert Divisions For Production
			//InsertDivisions($SPrdId, $connection, $HTTP_SESSION_VARS['dbLabel'], $HTTP_SESSION_VARS['useraccount']);
			
		}else{
			$SPrdId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	//Insert Detail Tables
	if ($SPrdId != "" && $SPrdDtId == "" && $SPrdTempId != "" && $ErrorExists == 0){
	
		if (empty($txtPrdDtQty)) $txtPrdDtQty = 0;
				
		$QtyExistExceeded   = 0;
			
			
		$vPrdDtQty     = $txtPrdDtQty;
		$vItemUnitCoef = 0;
		$vItemUnit2Qty = 0;
			
		$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), Currency_Code, ".
					 " ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0) ".
					 " FROM Items WHERE Item_Code = '".$txtItemCode."'"; 
		$sub_result = selectData($connection, $sub_query);
		$ItemVat 	     = $sub_result[0];
		$ItemGroupCode   = $sub_result[1];
		$ItemProd        = $sub_result[2];
		$ItemTTCInc      = $sub_result[3];
		$ItemCurr		 = $sub_result[4];
		$ItemCostMethod  = $sub_result[5];
		$ItemNonStock    = $sub_result[6];
			
			
			
				
							
		fbegin();
		$vPrdFGId = get_nextsequence('ProductionReqFG_Id','',$connection);
		fcommit();			
						 
		fbegin();	
		if($productionReq_packdt == 1)
		$query = " INSERT INTO Temp_ProductionReqFG (ProductionReqFG_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
				 " Warehouse_Code, ProductionReqFG_Quantity, Item_UnitCoef, Item_Unit2Qty, ProdRecipe_Id, Logged_Code ) ".
				 " VALUES ( ".$vPrdFGId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$txtItemCode."',  Null, 0, '".ereg_replace("'", "\'", trim($txtWhCode))."', ".
				 "          $vPrdDtQty, $vItemUnitCoef, $vItemUnit2Qty, '$SPrdTempId', '".$_SESSION['useraccount']."' ) ";
		else if($productionReq_packdt == 0)
		$query = " INSERT INTO Temp_ProductionReqFG (ProductionReqFG_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
				 " Warehouse_Code, ProductionReqFG_Quantity, Item_UnitCoef, Item_Unit2Qty, ProdRecipe_Id, Logged_Code ) ".
				 " VALUES ( ".$vPrdFGId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$txtItemCode."',  Null, 0, '".ereg_replace("'", "\'", trim($txtWhCode))."', ".
				 "          $vPrdDtQty, $vItemUnitCoef, $vItemUnit2Qty, '$SPrdTempId', '".$_SESSION['useraccount']."' ) ";
			
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
				
		if ($result){
			//fcommit();
			if($productionReq_packdt == 0){
			$sub_query = " Select ProdRecipeFG.ProdRecipe_Id, ProdRecipeFG.Item_Code, ProdRecipeFG.Warehouse_Code, ifNull(ProdRecipeFG_Quantity, 1), ifNull(ProdRecipeFG_QuantityFrom, ProdRecipeFG_Quantity) ".
						 " From ProdRecipeFG ".
						 " Where ProdRecipeFG.ProdRecipe_Id = '".$SPrdTempId."' ";
						 
			$sub_result  = selectData($connection, $sub_query);
			$vSelectdId  = $sub_result[0];
			$vPrdQtyFG   = $sub_result[3];
			$vPrdQtyFGFr = $sub_result[4];
						 
			
			//Load Raw Materials From Template
			$sub_query1 = " Select ProdRecipeRM.ProdRecipeRM_Id, ProdRecipeRM.Item_Code, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Warehouse_Code, ".
						  " ifNull(ProdRecipeRM_Quantity, 1), ProdRecipeRM_Remark, ifNull(ProdRecipeRM_DistOption, 1)  ".
						  " From ProdRecipeRM ".
						  " Where ProdRecipeRM.ProdRecipe_Id = '".$vSelectdId."' ";
					 
			$sub_result1=mysql_query($sub_query1, $connection) or die(mysql_error());
			while($sub_rows1=mysql_fetch_array($sub_result1)){			   
					
				$vItemCode       = $sub_rows1[1];
				$vItemCodePacked = $sub_rows1[2];
				$vPrdDtWhCode    = $sub_rows1[3];
				
				if ($vPrdDtQty >= $vPrdQtyFGFr && $vPrdDtQty <= $vPrdQtyFG)
					$vPrdQtyRM = $sub_rows1[4];
				else
					$vPrdQtyRM = ($vPrdDtQty*$sub_rows1[4])/$vPrdQtyFG;	
				
				
				$vItemUnitCoef   = 0;
				$vItemUnit2Qty   = 0;
				
				$QtyExistExceeded   = 0;
				
					
				fbegin();
				$vPrdRMId = get_nextsequence('ProductionReqRM_Id','',$connection);
				fcommit();			
							 
				fbegin();	 
				$query = " INSERT INTO Temp_ProductionReqRM (ProductionReqRM_Id, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
						 " Warehouse_Code, ProductionReqRM_Quantity, ProductionReqFG_Id, Item_CodeFinished, Item_UnitCoef, Item_Unit2Qty, Logged_Code ) ".
						 " VALUES ( ".$vPrdRMId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$vItemCode."',  '".$vItemCodePacked."', 0, '".ereg_replace("'", "\'", trim($txtWhCodeRM))."', ".
						 "          $vPrdQtyRM, $vPrdFGId, '".$txtItemCode."', $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."' ) ";
						
				$result=mysql_query($query,$connection);
				//echo $query."<br>";
						
				if ($result){
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
				
			} // End Loop Of ProdRecipeRM
		}else if($productionReq_packdt == 1){
			$sub_query1 = " select Item_CodePackDt, Warehouse_Code, PackDt_Quantity, ifNull(B.Item_QtyToBeProduced, 1),B.Item_UnitSalesDesc
							from packdt
							left join items A on A.item_code = packdt.Item_CodePackDt 
							left join items B on B.item_code = packdt.item_code
							where packdt.item_code = '$txtItemCode'";
					// echo $sub_query1;
			$sub_result1=mysql_query($sub_query1, $connection) or die(mysql_error());
			while($sub_rows1=mysql_fetch_array($sub_result1)){			   
					
				$vItemCode       = $sub_rows1[0];
				$vPrdDtWhCode    = $sub_rows1[1];
				
				
				$vPrdQtyRM = ($vPrdDtQty*$sub_rows1[2])/$sub_rows1[3];	
				
				
				$vItemUnitCoef   = 0;
				$vItemUnit2Qty   = 0;
				
				$QtyExistExceeded   = 0;
				
					
				fbegin();
				$vPrdRMId = get_nextsequence('ProductionReqRM_Id','',$connection);
				fcommit();			
							 
				fbegin();	 
				$query = " INSERT INTO Temp_ProductionReqRM (ProductionReqRM_Id, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
						 " Warehouse_Code, ProductionReqRM_Quantity, ProductionReqFG_Id, Item_CodeFinished, Item_UnitCoef, Item_Unit2Qty, Logged_Code ) ".
						 " VALUES ( ".$vPrdRMId.", ".$SPrdId.", '".insertMySQLDate($vPrdDate)."', '".$vItemCode."',  Null, 0, '".ereg_replace("'", "\'", trim($txtWhCodeRM))."', ".
						 "          $vPrdQtyRM, $vPrdFGId, '".$txtItemCode."', $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."' ) ";
						
				$result=mysql_query($query,$connection);
				//echo $query."<br>";
						
				if ($result){
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
				
			} 
		} 
		} else{
			$txtPrdDtId  = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
			

		
	} // End Case Insert In Detail Tables

} 



//Edit ItemQuantity
else if($mode == "editdt" && $SPrdId != "" && $SPrdDtId != ""){

	$QtyExistExceeded   = 0;
	
	if(empty($txtPrdDtQty)) $txtPrdDtQty = 0;
	$vPrdDtQty = $txtPrdDtQty;
	
	
	fbegin();	
		
	if ($SItemType == 'RM') {
		$query = " UPDATE Temp_ProductionReqRM SET  ".
				 " ProductionReqRM_Quantity = $vPrdDtQty ".
				 " ,warehouse_code = '$txtWhCode' ".
				 " Where ProductionReqRM_ID = ".$SPrdDtId;
	}
	else if ($SItemType == 'FG') {
		$query = " UPDATE Temp_ProductionReqFG SET  ".
				 " ProductionReqFG_Quantity = $vPrdDtQty ".
				 " ,warehouse_code = '$txtWhCode' ".
				 " Where ProductionReqFG_ID = ".$SPrdDtId;
	}
							 
	//echo $query; exit;
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();
		
		if ($SItemType == 'FG') {
			$sub_query = " Select ProductionReqFG.ProdRecipe_Id, ProductionReqFG.ProductionReqFG_Id ".
						 " From Temp_ProductionReqFG As ProductionReqFG ".
						 " Where ProductionReqFG.ProductionReqFG_ID = '".$SPrdDtId."' ";
						// echo $sub_query;exit;
			$sub_result = selectData($connection, $sub_query);
			$vProdRecipeId = $sub_result[0];
			$vProdReqFGId  = $sub_result[1];
			
			$sub_query = " Select ProdRecipeFG.Item_Code, ifNull(ProdRecipeFG_Quantity, 1) ".
						 " From ProdRecipeFG ".
						 " Where ProdRecipeFG.ProdRecipe_Id = '".$vProdRecipeId."' ";
						 
			$sub_result = selectData($connection, $sub_query);
			$vPrdQtyFG  = $sub_result[1];
			
			
			$sub_query1 = " Select ProdRecipeRM.ProdRecipeRM_Id, ProdRecipeRM.Item_Code, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Warehouse_Code, ".
						  " ifNull(ProdRecipeRM_Quantity, 1), ProdRecipeRM_Remark, ifNull(ProdRecipeRM_DistOption, 1)  ".
						  " From ProdRecipeRM ".
						  " Where ProdRecipeRM.ProdRecipe_Id = '".$vProdRecipeId."' ";

			$sub_result1 = mysql_query($sub_query1, $connection) or die(mysql_error());
			while($sub_rows1=mysql_fetch_array($sub_result1)){
				$vPrdQtyRM = 0;
				$vPrdQtyRM  = ($vPrdDtQty*$sub_rows1[4])/$vPrdQtyFG;
			
				$query = " UPDATE Temp_ProductionReqRM SET  ".
						 " ProductionReqRM_Quantity = $vPrdQtyRM ".
						 " Where ProductionReq_ID = '".$SPrdId."' ".
						 " And ProductionReqFG_Id = '".$vProdReqFGId."' ".
						 " And Item_Code = '".$sub_rows1[1]."' ";
				//echo $query ."<br>";		 
				$result=mysql_query($query,$connection);
			}
			
		}	
	} else{
		$message  = mysql_error(); 
		frollback();
	}				

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

	$AllowDelete = 1;
	$message  = '';
	

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

		$ErrorExists    = 0;
				
		$querypack = " SELECT ProductionReqRM.Item_CodePacked, ProductionReqRM.Item_Code ".
					 " FROM Temp_ProductionReqRM As ProductionReqRM ".
					 " Where ProductionReqRM.ProductionReqRM_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 TempProductionReqRM For Selected Record
			$query = " DELETE FROM Temp_ProductionReqRM ".
					 " WHERE ProductionReqRM_ID = ".$SPrdDtId;
					 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select ProductionReqRM_ID, ProductionReqRM.Item_CodePacked, ProductionReqRM.Item_Code  ".
					   " From Temp_ProductionReqRM As ProductionReqRM  ".
					   " Where ProductionReqRM.ProductionReq_ID = ".$SPrdId.
					   " And ProductionReqRM.Item_CodePacked =  '".$vItemCodePacked."'  ";
					
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vPrdDtId =	$rowsdt[0];
					
				// Delete From TempProductionReqRM For Selected Record
				$query = " DELETE FROM Temp_ProductionReqRM ".
						 " WHERE ProductionReqRM_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 No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		$ErrorExists    = 0;

		fbegin();
		
		// Delete From TempProductionReqRM For Selected Record
		$query = " DELETE FROM Temp_ProductionReqRM ".
				 " WHERE ProductionReqFG_Id = '".$SPrdDtId."'";
		//echo $query; exit;			 
		if (updateData($connection, $query, true)) {			 
			// Delete From TempProductionReqFG For Selected Record
			$query = " DELETE FROM Temp_ProductionReqFG ".
					 " WHERE ProductionReqFG_ID = ".$SPrdDtId;
				
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
		}
	
	} // End If No Constraints Found On Delete
	
	
}

//Confirm Production Request
else if(($mainmode == "confirmreq" || $mainmode == "unconfirmreq") && $SPrdId != ''){

	$sub_query = " Select ifNull(ProductionReq_Confirmed,0) ".
				 " From ProductionRequest ".
				 " Where ProductionRequest.ProductionReq_ID = ".$SPrdId;

	$sub_result = selectData($connection, $sub_query);
	$ProductionReqConfirmed = $sub_result[0];
	
	//Check Each ProductionReqFG If Has RelatedDtId In ProductionFG
	/*$sub_query = " Select Count(ProductionReqFG.ProductionReqFG_Id) ".
				 " From ProductionReqFG ".
				 " Inner Join ProductionFG on ProductionReqFG.ProductionReqFG_Id = ProductionFG.RelatedDt_id ".
				 " Where ProductionReqFG.ProductionReq_ID = ".$SPrdId;

	$sub_result = selectData($connection, $sub_query);
	$ProductionExists = $sub_result[0];*/
	
	
	if ($ProductionReqConfirmed == 0 && $mainmode == "confirmreq") {	
		$query = "UPDATE ProductionRequest SET ProductionReq_Confirmed = 1 WHERE ProductionReq_ID = ".$SPrdId."";

		if (updateData($connection, $query, true))
			$message = "Production Request Confirmed";
		else
			$message  = mysql_error();
	} 
	else if ($ProductionReqConfirmed == 1 && $mainmode == "unconfirmreq"){
		
		if ($ProductionExists > 0 ){
			$message  = 'Unconfirmation not allowed, Production Request Is Used.';
		} else {
			$query = "UPDATE ProductionRequest SET ProductionReq_Confirmed = 0 WHERE ProductionReq_ID = ".$SPrdId."";

			if (updateData($connection, $query, true))
				$message = "Production Request Unconfirmed";
			else
				$message  = mysql_error();
		}	
	}

}

else if ($mode == "adddivision" && $SPrdId != "" && $SPrdDivId == ""){
	$message  = '';
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
						  
	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;
	
	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Division Code.';
		}	
	}

	//Check For Division Type If Exists More Than Once For Production
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_ProductionReqDivisions As ProductionReqDivisions ".
					 " Inner Join Divisions on ProductionReqDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And ProductionReqDivisions.ProductionReq_Id = '".$SPrdId."'";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}	
	}	

	//Insert Master Table
	if ($SPrdDivId == "" && $ErrorExists == 0){
		fbegin();	
		$vPrdDivId = get_nextsequence('ProductionReqDivisions_Id','',$connection);
		fcommit();
			
		
		fbegin();
		$query = " INSERT INTO Temp_ProductionReqDivisions (ProductionReqDivisions_Id, ProductionReq_Id, Divisions_Id ) ".
				 " VALUES ( ".$vPrdDivId.", ".$SPrdId.", ".$vDivisionID.")";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdDivId = $vPrdDivId;
			fcommit();
			
		}else{
			$SPrdDivId = "";
			$message  = mysql_error(); 
			frollback();
		}
	}
	/*else {
		if ($ErrorExists == 1)	
			$message = 'Save not allowed. Please check for Division Code.';
		
	}*/

}

else if ($mode == "editdivision" && $SPrdId != "" && $SPrdDivId != ""){
	$message  = '';
	
	$ErrorExists = 0;
						  
	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;
	
	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Division Code.';
		}	
	}	
	
	//Check For Division Type If Exists More Than Once For Production
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_ProductionReqDivisions As ProductionReqDivisions ".
					 " Inner Join Divisions on ProductionReqDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And ProductionReqDivisions.ProductionReq_Id = '".$SPrdId."' ".
					 " And ProductionReqDivisions.ProductionReqDivisions_Id != '".$SPrdDivId."'";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}	
	}
	
	if ($SPrdDivId != "" && $ErrorExists == 0){
		fbegin();
		$query = " UPDATE Temp_ProductionReqDivisions Set Divisions_Id = '".$vDivisionID."' ".
				 " WHERE ProductionReqDivisions_Id = '".$SPrdDivId."'";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			fcommit();
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	/*else {
		if ($ErrorExists == 1)	
			$message = 'Save not allowed. Please check for Division Code.';
		
	}*/

}


else if ($mode == "deletedivision" && $SPrdId != "" && $SPrdDivId != ""){
	$message  = '';
	
	fbegin();
	
	$query = " DELETE FROM Temp_ProductionReqDivisions ".
			 " WHERE ProductionReqDivisions_Id = '".$SPrdDivId."'";
			
	if (!updateData($connection, $query, true)) {
		$message  = mysql_error();
		$ErrorExists = 1;
		frollback();
	}  
	else {
		fcommit();
	}

}

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

	$AllowDelete = 1;
	$message  = '';
	
	//Check If ProductionRequest Is Posted
	$sub_query = "SELECT ifNull(ProductionReq_Posted,0) As ProductionReqPosted FROM ProductionRequest WHERE ProductionReq_ID = '".$SPrdId."'";
	$sub_result = selectData($connection, $sub_query);
	$PrdPosted = $sub_result[0];
	
	if ($PrdPosted == 1 ){
		$message  = 'Delete not allowed, transaction posted.';
		$AllowDelete = 0;
	}
	
	if ($AllowDelete == 1) {
		//Check Each ProductionReqFG If Has RelatedId In ProductionFG
		$query = " Select Count(ProductionReqFG.ProductionReqFG_Id) ".
				 " From ProductionReqFG ".
				 " Inner Join ProductionFG on ProductionReqFG.ProductionReqFG_Id = ProductionFG.ProductionReqFG_Id ".
				 " Where ProductionReqFG.ProductionReq_Id = ".$SPrdId;

		$result = selectData($connection, $query);
		$ProductionExists = $result[0];
		
		if ($ProductionExists > 0 ){
			$message  = 'Delete not allowed, production request in use.';
			$AllowDelete = 0;
		}
	
	}
	
	

	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
	    $query = " DELETE FROM ProductionReqRM ".
				 " WHERE ProductionReq_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		$query = " DELETE FROM ProductionReqFG ".
				 " WHERE ProductionReq_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
			
		/*$query = " DELETE FROM ProductionReqDivisions ".
				 " WHERE ProductionReq_Id = '".$SPrdId."'";
		if (!updateData($connection, $query, true))
			$message  = mysql_error();	*/
		  
		$query = " DELETE FROM ProductionRequest ".
				 " WHERE ProductionReq_Id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error();   
		
		
	}
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SPrdId != ''){
	
	// Delete From Temp Tables For Selected Record
	$query = " DELETE FROM Temp_ProductionReqRM ".
			 " WHERE ProductionReq_Id = ".$SPrdId;

	if (!updateData($connection, $query, true))
		$message  = mysql_error(); 
	  
	$query = " DELETE FROM Temp_ProductionReqFG ".
			 " WHERE ProductionReq_Id = ".$SPrdId;

	if (!updateData($connection, $query, true))
		$message  = mysql_error(); 
		
	/*$query = " DELETE FROM Temp_ProductionReqDivisions ".
			 " WHERE ProductionReq_Id = '".$SPrdId."'";
	if (!updateData($connection, $query, true))
		$message  = mysql_error();*/		
		
	$query = " DELETE FROM Temp_ProductionRequest ".
			 " WHERE ProductionReq_Id = ".$SPrdId;

	if (!updateData($connection, $query, true))
		$message  = mysql_error();
	$querydel1 = "delete from temp_transferdt where transfer_id=$transferdone";
	$resdel1 = mysql_query($querydel1,$connection);
	$querydel2 = "delete from temp_transfer where transfer_id=$transferdone";
	$resdel2 = mysql_query($querydel2,$connection);
	$querydelFG1 = "delete from temp_transferdt where transfer_id=$transferdoneFG";
	$resdelFG1 = mysql_query($querydelFG1,$connection);
	$querydelFG2 = "delete from temp_transfer where transfer_id=$transferdoneFG";
	$resdelFG2 = mysql_query($querydelFG2,$connection);
	

}

//Search Mode	
else if($mainmode == "search" && $SPrdId != ''){
	
	$ErrorExists = 0;
	$AllowEdit = 1;
	$message  = '';
	
	
	if ($AllowEdit == 1) {
		//Check Each ProductionReqFG If Has RelatedId In ProductionFG
		$query = " Select Count(ProductionReqFG.ProductionReqFG_Id) ".
				 " From ProductionReqFG ".
				 " Inner Join ProductionFG on ProductionReqFG.ProductionReqFG_Id = ProductionFG.ProductionReqFG_Id ".
				 " Where ProductionReqFG.ProductionReq_Id = ".$SPrdId;

		$result = selectData($connection, $query);
		$ProductionExists = $result[0];
		
		if ($ProductionExists > 0 ){
			$message  = 'Edit not allowed, production request in use.';
			$AllowEdit = 0;
		}
	
	}

	if ($AllowEdit == 1) {

		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO Temp_ProductionRequest (ProductionReq_ID, ProductionReq_Reference, ProductionReq_Date, ProductionReq_Remark, ProductionReq_Manager, ".
				 " ProductionReq_Shift, ProductionReq_BelongsToGroup, ProductionReq_Posted, ProductionReq_Confirmed, Project_Code, CostCenter_Code, User_Account, Logged_Code ) ".
				 " SELECT ProductionReq_ID, ProductionReq_Reference, ProductionReq_Date, ProductionReq_Remark, ProductionReq_Manager, ".
				 " ProductionReq_Shift, ProductionReq_BelongsToGroup, ProductionReq_Posted, ProductionReq_Confirmed, Project_Code, CostCenter_Code, User_Account, '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " FROM ProductionRequest ".
				 " WHERE ProductionReq_Id = ".$SPrdId;
		
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			$message  = mysql_error(); 	
		}
				
		//echo $message.$query; exit;				 
			
		if ($ErrorExists == 0) {
		
			$query = " INSERT INTO Temp_ProductionReqDivisions (ProductionReqDivisions_Id, ProductionReq_ID, Divisions_Id ) ".
					 " SELECT ProductionReqDivisions_Id, ProductionReq_ID, Divisions_Id ".
					 " FROM ProductionReqDivisions ".
					 " WHERE ProductionReq_Id = ".$SPrdId;
					 
			if (!updateData($connection, $query, true))
				$message  = mysql_error();
		
			$query = " INSERT INTO Temp_ProductionReqRM (ProductionReqRM_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
					 " Warehouse_Code, ProductionReqRM_Quantity, ProductionReqFG_Id, Item_CodeFinished, Item_UnitCoef, Item_Unit2Qty, Logged_Code ) ".
					 " SELECT ProductionReqRM_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
					 " Warehouse_Code, ProductionReqRM_Quantity, ProductionReqFG_Id, Item_CodeFinished, Item_UnitCoef, Item_Unit2Qty, '".$HTTP_SESSION_VARS['useraccount']."'  ".
					 " FROM ProductionReqRM ".
					 " WHERE ProductionReq_Id = ".$SPrdId;
			
			if (!updateData($connection, $query, true))
				$message  = mysql_error(); 
		
				
			$query = " INSERT INTO Temp_ProductionReqFG (ProductionReqFG_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
					 " Warehouse_Code, ProductionReqFG_Quantity, Item_UnitCoef, Item_Unit2Qty, ProdRecipe_Id, Logged_Code ) ".
					 " SELECT ProductionReqFG_ID, ProductionReq_ID, ProductionReq_Date, Item_Code, Item_CodePacked, Item_QtyPacked, ".
					 " Warehouse_Code, ProductionReqFG_Quantity, Item_UnitCoef, Item_Unit2Qty, ProdRecipe_Id, '".$HTTP_SESSION_VARS['useraccount']."'  ".
					 " FROM ProductionReqFG ".
					 " WHERE ProductionReq_Id = ".$SPrdId;
			
			if (!updateData($connection, $query, true))
				$message  = mysql_error(); 
					  
		}  
	
	}
}




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

	$vPrdDate         = $txtDate;
	$vPrdManager      = $txtManager;
	$vPrdShift        = $txtShift;
	$vPrdRemark       = $txtRemark;
	$vPrdConfirmed    = $txtConfirmed;
	
	if (empty($txtCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
	
	
    $SaveAllow   = 1;
	$ErrorExists = 0;
	

	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['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;
		
		if ($ExceedLockPeriod == 1) {
			$message = 'Save not allowed. Exceed Lock Period.';			
		}
	}
	//echo $sub_query;exit;
	
	//Check For Mandatory Project, Costcenter and Machine
	/*if ($Module_Project == 1 && $Module_RestrictProjCost == 1) {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_ProductionReqDivisions As ProductionReqDivisions ".
					 " Inner Join Divisions on ProductionReqDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where ProductionReq_ID = '".$SPrdId."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Project is mandatory.';
		}
	}
	if ($Module_CostCenter == 1 && $Module_RestrictCost == 1) {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_ProductionReqDivisions As ProductionReqDivisions ".
					 " Inner Join Divisions on ProductionReqDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where ProductionReq_ID = '".$SPrdId."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. CostCenter is mandatory.';
		}
	}
	if ($Module_RestrictMachine == 1) {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_ProductionReqDivisions As ProductionReqDivisions ".
					 " Inner Join Divisions on ProductionReqDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where ProductionReq_ID = '".$SPrdId."' ".
					 " And Upper(DivisionTypes_Name) = 'MACHINE' ";
		$sub_result = selectData($connection, $sub_query);
		
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Machine is mandatory.';
		}
	}*/
	
	
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
		$sub_query2 = " UPDATE Temp_ProductionReqRM SET ".
					  " ProductionReq_Date = '".insertMySQLDate($vPrdDate)."' ".
					  " WHERE ProductionReq_Id = $SPrdId ";
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
			
		$sub_query2 = " UPDATE Temp_ProductionReqFG SET ".
					  " ProductionReq_Date = '".insertMySQLDate($vPrdDate)."' ".
					  " WHERE ProductionReq_Id = $SPrdId ";
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 	

			
		$query = " UPDATE Temp_ProductionRequest SET ".
				 " ProductionReq_Date = '".insertMySQLDate($vPrdDate)."', ProductionReq_Confirmed = $vPrdConfirmed, ".
				 " ProductionReq_Remark = '".ereg_replace("'", "\'", trim($vPrdRemark))."', ".
				 " ProductionReq_Manager = '".ereg_replace("'", "\'", trim($vPrdManager))."', ".
				 " ProductionReq_Shift = '".ereg_replace("'", "\'", trim($vPrdShift))."', ".
				 " Project_Code = $ProjectCode, Costcenter_code = $CostCentCode ".
				 " WHERE ProductionReq_Id = $SPrdId ";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
		
			$query = "Select Count(*) From Temp_ProductionRequest where ProductionReq_ID = '".$SPrdId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
				
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempProductionRequest('".$SMode."', ".$SPrdId.", '".$_SESSION['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
					
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT ProductionReq_Reference FROM ProductionRequest WHERE ProductionReq_Id = $SPrdId ";
					$result  = selectData($connection, $query);
					$vPrdRef = $result[0];
					
											
					if ($vPrdRef == ''){
							
						fbegin();
						$vPrdRef = get_nextsequence('ProductionReq_Reference','',$connection);	
						fcommit();
							
						$query = " UPDATE ProductionRequest SET ".
								 " ProductionReq_Reference = $vPrdRef ".
								 " WHERE ProductionReq_Id = $SPrdId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
					}
						
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempProductionRequest Function'; 
					frollback();
				}
			
			}
			if($transferdone!=''){
				
				$sub_query2 = " Select ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code, ".
						  " Sum(ifNull(TransferDt_Quantity,0)) As ProductionReqRM_Quantity, Items.Item_UnitSalesDesc,  ProductionReqRM.Item_CodePacked ".
						  " From ProductionReqRM As ProductionReqRM Left Join Items on ProductionReqRM.Item_Code = Items.Item_code ".
						  " left join temp_transfer on Transfer_Id = '$transferdone' 
							left join temp_transferdt on temp_transferdt.Transfer_Id = temp_transfer.Transfer_Id and temp_transferdt.item_code = ProductionReqRM.Item_Code ".
						  " Where ProductionReqRM.ProductionReq_ID = '".$txtPrdId."' ".
						  " Group By ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code ".
						  " Order By ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code ";
				$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error());
				$i=0; 
				fbegin();
				$transferid = get_nextsequence('transfer_id','',$connection);	
				fcommit();
				
				fbegin();
				$Transfer_reference = get_nextsequence('Transfer_reference','',$connection);	
				fcommit();	
           
		    				
			$query = "insert into transfer(Transfer_Id,Transfer_reference,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, Synchronized,    User_account,
			 Transfer_Type,transfer_warehousefrom,transfer_warehouseto) 
			select $transferid,$Transfer_reference, now(), 0, 0, '$txtProjectCode', '$txtProjectCode', '$txtCostCentCode',0,0,'".$_SESSION['useraccount']."', 'Tr',
			transfer_warehousefrom,transfer_warehouseto			
			from temp_transfer where transfer_id = $transferdone";
		//echo $query."<br>";  exit;
		$result=mysql_query($query,$connection) or die(mysql_error());	
	while($sub_rows2=mysql_fetch_array($sub_result2)){	
		if($sub_rows2[4] == '') $item_pck = null;
		fbegin();
				$transferidt = get_nextsequence('transferdt_id','',$connection);	
				fcommit();
				
					
		$querydt = "insert into transferdt ( Transferdt_Id,Transfer_Id, Transfer_Date, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code,
					Transferdt_posted, Item_CodePacked, TransferDt_PricePerUnit, TransferDt_QtyUnit) values ($transferidt,$transferid, now(), '$sub_rows2[0]','".$txtFromWhCode[$i]."','$sub_rows2[1]',
					$sub_rows2[2], 0,0,0,0,'$txtProjectCode','$txtProjectCode',";
		if($txtCostCentCode=='') $querydt=$querydt." null,";
		else $querydt=$querydt."'$txtCostCentCode',";	
				$querydt=$querydt."0, null, 0,0)"; //echo $querydt."<br>";
		//echo $querydt;exit;
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());			
	
		$i+=1;	
		//$transferidt++;
			}//exit;
		$querydel1 = "delete from temp_transferdt where transfer_id=$transferdone";
		$resdel1 = mysql_query($querydel1,$connection);
		$querydel2 = "delete from temp_transfer where transfer_id=$transferdone";
		$resdel2 = mysql_query($querydel2,$connection);	
		$transferdone = $transferid;
			}
			if($transferdoneFG!=''){
				$queryToWh = "select warehouseFG from transfersetup";
				$resToWh = mysql_query($queryToWh,$connection);
				$rwToWh = mysql_fetch_row($resToWh);
				
				$sub_query2 = " Select Transferdt_Id,Transfer_Id, Transfer_Date, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code,
					Transferdt_posted, Item_CodePacked, TransferDt_PricePerUnit, TransferDt_QtyUnit ".
						  " From temp_transferdt ".
						  " Where Transfer_Id = '".$transferdoneFG."' ";
				$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error()); //echo $sub_query2;exit;
				$i=0; 
				fbegin();
				$transferid = get_nextsequence('transfer_id','',$connection);	
				fcommit();
				
				fbegin();
				$Transfer_reference = get_nextsequence('Transfer_reference','',$connection);	
				fcommit();	
           
		    				
			$query = "insert into transfer(Transfer_Id,Transfer_reference,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, Synchronized,    User_account,
			 Transfer_Type) 
			values ($transferid,$Transfer_reference, now(), 0, 0, '$txtProjectCode', '$txtProjectCode', '$txtCostCentCode',0,0,'".$_SESSION['useraccount']."', 'Tr' )";
		//echo $query."<br>";  exit;
		$result=mysql_query($query,$connection) or die(mysql_error());	
	while($sub_rows2=mysql_fetch_array($sub_result2)){	//echo "hh";exit;
		if($sub_rows2[1] == '') $item_pck = null;
		fbegin();
				$transferidt = get_nextsequence('transferdt_id','',$connection);	
				fcommit();
				
					
		$querydt = "insert into transferdt ( Transferdt_Id,Transfer_Id, Transfer_Date, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code,
					Transferdt_posted, Item_CodePacked, TransferDt_PricePerUnit, TransferDt_QtyUnit) values ($transferidt,$transferid, now(), '$sub_rows2[3]','$sub_rows2[4]','$rwToWh[0]',
					$sub_rows2[6], 0,0,0,0,'$txtProjectCode','$txtProjectCode',";					
		if($txtCostCentCode=='') $querydt=$querydt." null,";
		else $querydt=$querydt."'$txtCostCentCode',";	
				$querydt=$querydt."0, null, 0,0)"; //echo $querydt."<br>";
		//echo $querydt;exit;
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());			
	
		$i+=1;	
		//$transferidt++;
			}//exit;
			$querydel1 = "delete from temp_transferdt where transfer_id=$transferdoneFG";
				$resdel1 = mysql_query($querydel1,$connection);
				$querydel2 = "delete from temp_transfer where transfer_id=$transferdoneFG";
				$resdel2 = mysql_query($querydel2,$connection);
		$transferdoneFG = $transferid;
			}
			
		} else{
			$message  = mysql_error(); 
			$ErrorExists = 1;
			frollback();
		}	
	}// End if($SaveAllowed == 1)
	
}
else if($mode == 'transferData'){
	if($txtProjectCode == '') $txtProjectCode = "NULL";
	else $txtProjectCode = "'".$txtProjectCode."'";
	if($txtCostCentCode == '') $txtCostCentCode = "NULL";
	else $txtCostCentCode = "'".$txtCostCentCode."'";

	$qtrid = "select max(transfer_id) from temp_transfer";
	$res_trid = mysql_query($qtrid,$connection);
	$row_trid=mysql_fetch_array($res_trid);
	$transferid = $row_trid[0]+1;
	$qtridt = "select max(transferdt_id) from temp_transferdt";
	$res_tridt = mysql_query($qtridt,$connection);
	$row_tridt=mysql_fetch_array($res_tridt);
	$transferidt = $row_tridt[0]+1;
	$sub_query2 = " Select ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code, ".
						  " Sum(ifNull(ProductionReqRM_Quantity,0)) As ProductionReqRM_Quantity, Items.Item_UnitSalesDesc,  ProductionReqRM.Item_CodePacked ".
						  " From Temp_ProductionReqRM As ProductionReqRM Left Join Items on ProductionReqRM.Item_Code = Items.Item_code ".
						  " Where ProductionReqRM.ProductionReq_ID = '".$txtPrdId."' ".
						  " Group By ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code ".
						  " Order By ProductionReqRM.Item_Code, ProductionReqRM.Warehouse_Code ";
	$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error());
		$i=0; 
		$towharehouse = 'towharehouse'.$i;
		if($txtCostCentCode=='') $txtCostCentCode=null;			  
		$query = "insert into temp_transfer(Transfer_Id,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, Synchronized,    User_account,
			Transfer_Type, transfer_warehousefrom, transfer_warehouseto) 
			values ($transferid,now(), 0, 0, $txtProjectCode, $txtProjectCode, $txtCostCentCode,0,0,'".$_SESSION['useraccount']."','Tr','".$txtFromWhCode[$i]."','".$$towharehouse."')";
		//echo $query."<br>"; 
	$result=mysql_query($query,$connection) or die(mysql_error());	
	while($sub_rows2=mysql_fetch_array($sub_result2)){	
		if($sub_rows2[4] == '') $item_pck = null;
		$itemqty = 'qtytotransfer'.$i;
		$querydt = "insert into temp_transferdt ( Transferdt_Id,Transfer_Id, Transfer_Date, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code,
					Transferdt_posted, Item_CodePacked, TransferDt_PricePerUnit, TransferDt_QtyUnit) values ($transferidt,$transferid, now(), '$sub_rows2[0]','".$txtFromWhCode[$i]."','$sub_rows2[1]',
					".$$itemqty.", 0,0,0,0,$txtProjectCode,$txtProjectCode,$txtCostCentCode,0, null, 0,0)"; //echo $querydt."<br>";
		//echo $querydt;exit;
		
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());			
	//echo $query;exit;
	
	
	
		$i+=1;	
		
		$transferidt++;
			}//exit;
		$transferdone = $transferid;	
}else if($mode == 'transferDataFG'){
	
	$queryToWh = "select warehouseFG from transfersetup";
	$resToWh = mysql_query($queryToWh,$connection);
	$rwToWh = mysql_fetch_row($resToWh);
	$qtrid = "select max(transfer_id) from temp_transfer";
	$res_trid = mysql_query($qtrid,$connection);
	$row_trid=mysql_fetch_array($res_trid);
	$transferid = $row_trid[0]+1;
	$qtridt = "select max(transferdt_id) from temp_transferdt";
	$res_tridt = mysql_query($qtridt,$connection);
	$row_tridt=mysql_fetch_array($res_tridt);
	$transferidt = $row_tridt[0]+1;
	$sub_query2 = " Select ProductionReqFG.ProductionReqFG_ID, ProductionReqFG.Item_CodePacked, ProductionReqFG.Item_Code, ".
						  " ProductionReqFG.Warehouse_Code, ifNull(ProductionReqFG_Quantity,0), Items.Item_UnitSalesDesc ".
						  " From Temp_ProductionReqFG As ProductionReqFG Left Join Items on ProductionReqFG.Item_Code = Items.Item_code ".
						  " Where ProductionReqFG.ProductionReq_ID = '".$txtPrdId."' "; 
	$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error());
		$i=0; 
		if($txtCostCentCode=='') $txtCostCentCode=null;			  
		$query = "insert into temp_transfer(Transfer_Id,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, Synchronized,    User_account,
			Transfer_Type) 
			values ($transferid,now(), 0, 0, '$txtProjectCode', '$txtProjectCode', '$txtCostCentCode',0,0,'".$_SESSION['useraccount']."','Tr' )";
		//echo $query."<br>"; 
	$result=mysql_query($query,$connection) or die(mysql_error());	
	while($sub_rows2=mysql_fetch_array($sub_result2)){	
		if($sub_rows2[1] == '') $item_pck = null;
		$querydt = "insert into temp_transferdt ( Transferdt_Id,Transfer_Id, Transfer_Date, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code,
					Transferdt_posted, Item_CodePacked, TransferDt_PricePerUnit, TransferDt_QtyUnit) values ($transferidt,$transferid, now(), '$sub_rows2[2]','$sub_rows2[3]','$rwToWh[0]',
					$sub_rows2[4], 0,0,0,0,'$txtProjectCode','$txtProjectCode','$txtCostCentCode',0, null, 0,0)"; //echo $querydt."<br>";
		//echo $querydt;exit;
		
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());			
	//echo $query;exit;
	
	
	
		$i+=1;	
		
		$transferidt++;
			}//exit;
		$transferdoneFG = $transferid;	
}

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


if($mode == "post" || $mode == "transferData" || $mode == "transferDataFG") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_ProductionRequest.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPrdId=".$SPrdId."&PrPrdRef=".$vPrdRef."&txtWhCodeRM=$txtWhCodeRM&message=".$message);
	else
		header ("Location: ./Form_ProductionRequest.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&txtWhCodeRM=$txtWhCodeRM&transferdone=$transferdone&transferdoneFG=$transferdoneFG&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_ProductionReqSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_ProductionReqSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_ProductionRequest.php?message=".$message);	
else if ($mode == "deletedtRM" || $mode == "deletedtFG")		
	header ("Location: ./Form_ProductionRequest.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&PTabIndex=".$STabIndex."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_ProductionReqDetail.php?PItemType=".$SItemType."&actionmode=".$mode."&mainaction=".$mainmode."&PPrdId=".$SPrdId."&PPrdDate=".$PPrdDate."&PPrdDtId=".$SPrdDtId."&message=".$message);
else if ($mode == "adddivision" || $mode == "editdivision" || $mode == "deletedivision")		
	header ("Location: ./Form_ProductionRequest.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);	
else if ($mode == "" && $mainmode == "search" )	{
	if ($AllowEdit == 1)
		header ("Location: ./Form_ProductionReqSearch.php?PMode=1");
	else
		header ("Location: ./Form_ProductionReqSearch.php?PMode=0&message=".$message);	
}	
else if ($mode == "" && ($mainmode == "confirmreq" || $mainmode == "unconfirmreq") )	
	header ("Location: ./Form_ProductionReqSearch.php?message=".$message);
else if ($mode == "submitrecord") {
    header ("Location: ./Form_ProductionRequest.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&txtWhCodeRM=$txtWhCodeRM&transferdone=$transferdone&transferdoneFG=$transferdoneFG&message=".$message);
}



function InsertDivisions($PId, $connection, $PDbLabel, $PUserAccount) {

	//Insert Project
	$sub_query = " Select Project_Code From ".$PDbLabel.".loginstk ".
				 " Where User_Account='".$PUserAccount."' ".
				 " And ifNull(Default_Project, 0) = 1 ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>"; 
	$ProjectCode = $sub_result[0];
	if ($ProjectCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$ProjectCode."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];
				
		fbegin();	
		$vPrdDivId = get_nextsequence('ProductionReqDivisions_Id','',$connection);
		fcommit();
				
		$query = " INSERT INTO Temp_ProductionReqDivisions (ProductionReqDivisions_Id, ProductionReq_ID, Divisions_Id ) ".
				 " VALUES (".$vPrdDivId.", ".$PId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}
	
	//Insert CostCenter
	$sub_query = " Select CostCent_Code From ".$PDbLabel.".loginstk ".
				 " Where User_Account='".$PUserAccount."' ".
				 " And ifNull(Default_CostCenter, 0) = 1 ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>"; 
	$CostCenterCode = $sub_result[0];
	if ($CostCenterCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$CostCenterCode."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];
				
		fbegin();	
		$vPrdDivId = get_nextsequence('ProductionReqDivisions_Id','',$connection);
		fcommit();
				
		$query = " INSERT INTO Temp_ProductionReqDivisions (ProductionReqDivisions_Id, ProductionReq_ID, Divisions_Id ) ".
				 " VALUES (".$vPrdDivId.", ".$PId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}
	
	
	//Insert Machine
	$sub_query = " Select Machine_Code From ".$PDbLabel.".loginstk ".
				 " Where User_Account='".$PUserAccount."' ".
				 " And ifNull(Default_Machine, 0) = 1 ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>"; 
	$MachineCode = $sub_result[0];
	if ($MachineCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$MachineCode."' ".
					 " And Upper(DivisionTypes_Name) = 'MACHINE' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];
				
		fbegin();	
		$vPrdDivId = get_nextsequence('ProductionReqDivisions_Id','',$connection);
		fcommit();
				
		$query = " INSERT INTO Temp_ProductionReqDivisions (ProductionReqDivisions_Id, ProductionReq_ID, Divisions_Id ) ".
				 " VALUES (".$vPrdDivId.", ".$PId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}
	//exit;
}

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

HERE;


?>