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


$message='';
$mode 				= $_POST['mode'];		 		if($mode == '') 			$mode 				= $_GET['mode'];
$mainmode			= $_POST['mainmode']; 			if($mainmode == '') 		$mainmode 			= $_GET['mainmode'];
$SItemType 			= $_POST['SItemType']; 			if($SItemType == '')	 	$SItemType 			= $_GET['SItemType'];
$SPrdId 			= $_POST['SPrdId']; 			if($SPrdId == '') 			$SPrdId 			= $_GET['SPrdId'];
$PPrdId 			= $_POST['PPrdId']; 			if($PPrdId == '') 			$PPrdId 			= $_GET['PPrdId'];
$vPrdDate 			= $_POST['PPrdDate']; 			if($vPrdDate == '') 		$vPrdDate 			= $_GET['PPrdDate'];
$vPrdRemark 		= $_POST['PPrdRemark']; 		if($vPrdRemark == '') 		$vPrdRemark 		= $_GET['PPrdRemark'];
$vPrdCur 			= $_POST['PPrdCur']; 			if($vPrdCur == '') 			$vPrdCur 			= $_GET['PPrdCur'];
$vPrdManualNo 		= $_POST['PPrdManualNo']; 		if($vPrdManualNo == '') 	$vPrdManualNo 		= $_GET['PPrdManualNo'];
$vPrdProjectCode	= $_POST['PPrdProjectCode']; 	if($vPrdProjectCode == '') 	$vPrdProjectCode 	= $_GET['PPrdProjectCode'];
$vPrdCostCode 		= $_POST['PPrdCostCode']; 		if($vPrdCostCode == '') 	$vPrdCostCode 		= $_GET['PPrdCostCode'];
$group_code 		= $_POST['group_code']; 		if($group_code == '') 		$group_code 		= $_GET['group_code'];
$subgroup_code 		= $_POST['subgroup_code']; 		if($subgroup_code == '') 	$subgroup_code 		= $_GET['subgroup_code'];
$category_code 		= $_POST['category_code']; 		if($category_code == '') 	$category_code 		= $_GET['category_code'];

$SPrdFGId 			= $_POST['SPrdFGId']; 			if($SPrdFGId == '')	 		$SPrdFGId 			= $_GET['SPrdFGId'];
$lstWarehouse 		= $_POST['lstWarehouse']; 		if($lstWarehouse == '') 	$lstWarehouse 		= $_GET['lstWarehouse'];
$txtItemCode 		= $_POST['txtItemCode']; 		if($txtItemCode == '') 		$txtItemCode 		= $_GET['txtItemCode'];
$txtItemCreadted 	= $_POST['txtItemCreadted'];	if($txtItemCreadted == '') 	$txtItemCreadted 	= $_GET['txtItemCreadted'];
$txtPrdQtyFG 		= $_POST['txtPrdQtyFG'];		if($txtPrdQtyFG == '') 		$txtPrdQtyFG 		= $_GET['txtPrdQtyFG'];
$txtPrdPriceFG 		= $_POST['txtPrdPriceFG']; 		if($txtPrdPriceFG == '') 	$txtPrdPriceFG 		= $_GET['txtPrdPriceFG'];
$txtPrdNetFG 		= $_POST['txtPrdNetFG'];	 	if($txtPrdNetFG == '') 		$txtPrdNetFG 		= $_GET['txtPrdNetFG'];
$txtPrdNetWeightFG	= $_POST['txtPrdNetWeightFG'];	if($txtPrdNetWeightFG == '') $txtPrdNetWeightFG = $_GET['txtPrdNetWeightFG'];
$txtPrdProjectCodedt	= $_POST['txtPrdProjectCodedt'];	if($txtPrdProjectCodedt == '') 	$txtPrdProjectCodedt 	= $_GET['txtPrdProjectCodedt'];
$txtPrdCostcentCodedt	= $_POST['txtPrdCostcentCodedt'];	if($txtPrdCostcentCodedt == '') $txtPrdCostcentCodedt 	= $_GET['txtPrdCostcentCodedt'];
$txtgroup_code  	= $_POST['txtgroup_code'];		if($txtgroup_code == '') $txtgroup_code 	= $_GET['txtgroup_code'];

$SPrdSFId 			= $_POST['SPrdSFId'];	 		if($SPrdSFId == '') 		$SPrdSFId 			= $_GET['SPrdSFId'];
$txtPrdWeightSF 	= $_POST['txtPrdWeightSF'];	 	if($txtPrdWeightSF == '') 	$txtPrdWeightSF 	= $_GET['txtPrdWeightSF'];
$txtPrdQtySF 		= $_POST['txtPrdQtySF'];	 	if($txtPrdQtySF == '') 		$txtPrdQtySF 		= $_GET['txtPrdQtySF'];
$txtPrdPriceSF 		= $_POST['txtPrdPriceSF'];	 	if($txtPrdPriceSF == '') 	$txtPrdPriceSF 		= $_GET['txtPrdPriceSF'];
$txtNetWeightRM		= $_POST['txtNetWeightRM'];	 	if($txtNetWeightRM == '') 	$txtNetWeightRM 	= $_GET['txtNetWeightRM'];
$txtNetWeightSF		= $_POST['txtNetWeightSF'];	 	if($txtNetWeightSF == '') 	$txtNetWeightSF 	= $_GET['txtNetWeightSF'];
$txtNetWaste		= $_POST['txtNetWaste'];	 	if($txtNetWaste == '') 		$txtNetWaste 		= $_GET['txtNetWaste'];

if($txtNetWeightRM == '') 	$txtNetWeightRM = 0;							
if($txtNetWeightSF == '') 	$txtNetWeightSF = 0;
if($txtNetWaste == '') 		$txtNetWaste = 0;
$alphas = range('A', 'Z');				
//Submit Record Mode

if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	if ($vPrdCostCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($vPrdProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$vPrdProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($SPrdId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$vPrdId = get_nextsequence('productionFactory_id','',$connection);
		fcommit();
			
		
		fbegin();
		$query = " INSERT INTO temp_productionFactory (productionFactory_id, productionFactory_reference, productionFactory_date, Currency_Code, productionFactory_remark, productionFactory_BelongsToGroup, ".
				 " User_Account, Logged_User, totnetweightrm, totnetweightsf, totwaste, productionfactory_manualno, project_code, costcent_code,  item_group, item_subgroup, item_category )".
				 " VALUES ( ".$vPrdId.", Null, '".insertMySQLDate($vPrdDate)."', '".$vPrdCur."', ".strformat($vPrdRemark).", $FI_BelongsToGrp, ".
				 " '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', $txtNetWeightRM, $txtNetWeightSF, $txtNetWaste, ".strformat($vPrdManualNo).", ".
				 " ".strformat($vPrdProjectCode).", ".strformat($vPrdCostCode).", ".strformat($group_code).", ".strformat($subgroup_code).", ".strformat($category_code)."   )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdId = $vPrdId;
			$PPrdId = $vPrdId;
			fcommit();
			
		}else{
			$PPrdId = "";
			$SPrdId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	else if ($SPrdId != "" && $ErrorExists == 0){
		$query = " update temp_productionFactory set productionFactory_date = '".insertMySQLDate($vPrdDate)."', Currency_Code = '".$vPrdCur."', productionFactory_remark = ".strformat($vPrdRemark).", ".
				 " productionFactory_BelongsToGroup = $FI_BelongsToGrp, Logged_User = '".$_SESSION['useraccount']."',  totnetweightrm = $txtNetWeightRM, totnetweightsf = $txtNetWeightSF, ".
				 " totwaste = $txtNetWaste, productionfactory_manualno = ".strformat($vPrdManualNo).", project_code = ".strformat($vPrdProjectCode).", costcent_code = ".strformat($vPrdCostCode)." ".
				 " where productionFactory_id = $SPrdId";
						 
		
		$result=mysql_query($query,$connection);
	}
	
	//Insert Detail Tables
	if ($SPrdId != "" && $SPrdFGId == "" && $SItemType == 'FG' && $ErrorExists == 0){
	
		if (empty($txtPrdQtyFG))	$txtPrdQtyFG = 0;
		if (empty($txtPrdPriceFG))	$txtPrdPriceFG = 1;
		if (empty($txtPrdNetFG))	$txtPrdNetFG = 0;
		
		if ($txtPrdProjectCodedt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtPrdProjectCodedt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
		}
		if ($txtPrdCostcentCodedt != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$txtPrdCostcentCodedt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
			}
		}	
		$txtPrdProjectCodedt = strformat($txtPrdProjectCodedt);
		$txtPrdCostcentCodedt = strformat($txtPrdCostcentCodedt);
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		// Case Not Pack Item
		if ($ItemPack != 1) {
		
			$vPrdFGCostBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
			$vPrdFGCostBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
			
			$vPrdFGNetBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);
			$vPrdFGNetBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);			
			fbegin();
			$SPrdFGId = get_nextsequence('productionFactoryfg_id','',$connection);
			fcommit();			
						 
			fbegin();	 
			$query = " INSERT INTO temp_productionFactoryFG (productionFactoryfg_id, productionFactory_id, item_code, item_created, warehouse_code, productionFactoryfg_qty, productionFactoryfg_price, ".
					 " productionFactoryfg_price1, productionFactoryfg_price2, productionFactoryfg_net, productionFactoryfg_net1, productionFactoryfg_net2, project_codedt, costcent_codedt ) ".
					 " VALUES ( ".$SPrdFGId.", ".$SPrdId.", '".$txtItemCode."',  '".$txtItemCreadted."', '".ereg_replace("'", "\'", trim($lstWarehouse))."', $txtPrdQtyFG, $txtPrdPriceFG, ".
					 " $vPrdFGCostBase1, $vPrdFGCostBase2, $txtPrdNetFG, $vPrdFGNetBase1, $vPrdFGNetBase2, ".$txtPrdProjectCodedt.", ".$txtPrdCostcentCodedt." ) ";//$message = $query;
			//echo $query."<br>";exit;		
			$result=mysql_query($query,$connection);
			
				
			if ($result){
				fcommit();
				$range = 0;
				$lastnbr = 0;
				for($i=1; $i<= $txtItemCreadted; $i++){
					$itemexist = 0;
					$nbrs = range(0+$range, 9+$range);
					foreach($nbrs as $nbr){
						foreach($alphas as $alpha){
							$sub_item = $txtItemCode."-".$alpha.$nbr;
							$querycheck = "select productionFactorysf_id from temp_productionFactorySF where item_code = '$sub_item' and productionFactory_id = ".$SPrdId.";";
							$rescheck = mysql_query($querycheck,$connection);
							$numrw = mysql_num_rows($rescheck);
							if($numrw == 0){
								fbegin();
								$SPrdSFId = get_nextsequence('productionFactorysf_id','',$connection);
								fcommit();	
								$insert = "insert into temp_productionFactorySF (productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, warehouse_code, ".
										" productionFactorysf_qty, productionFactorysf_price, productionFactorysf_price1, productionFactorysf_price2, project_codedt, costcent_codedt) values ".
										" ( ".$SPrdSFId.",".$SPrdFGId.", ".$SPrdId.", '".$sub_item."', '".ereg_replace("'", "\'", trim($lstWarehouse))."', $txtPrdQtyFG, $txtPrdPriceFG, ".
										" $vPrdFGCostBase1, $vPrdFGCostBase2, ".$txtPrdProjectCodedt.", ".$txtPrdCostcentCodedt." ) ";
								$res = mysql_query($insert,$connection);	
								$query = "select 1 from items where item_code = '$sub_item';";
								$res = mysql_query($query,$connection);
								$numr = mysql_num_rows($res);
								if($numr == 0){
									fbegin();
									$item_id = get_nextsequence('Item_Increment','',$connection);
									fcommit();
									$insert2 = "insert into items(Item_Code, Item_Description, Item_Barcode, Currency_code, CostCent_Code, Group_code, SubGroup_Code, Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Category_code, Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, Item_Weight, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, item_id, BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, Item_NetWeight, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist) ".
											  " select '$sub_item', concat( ifnull(".strformat($group_code).",Group_code), '-Width:',ifnull(".strformat($subgroup_code).",SubGroup_Code), '-Thickness:', ifnull(".strformat($category_code).",Category_code)), Item_Barcode, Currency_code, CostCent_Code, ifnull(".strformat($group_code).",Group_code), ifnull(".strformat($subgroup_code).",SubGroup_Code), Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2,  ifnull(".strformat($category_code).",Category_code), Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, null, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, '$item_id', BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, null, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist ".						 
											  " from items ".
											   " where item_code = '$txtItemCode'";
									$result2 = mysql_query($insert2,$connection);		
								}								
								$itemexist = 1;
							}
							if($itemexist == 1) break;
						}
						$lastnbr = $nbr;
						if($itemexist == 1) break;
					}
					if($lastnbr == $range-1) $range = $range + 10;
				}
			} else {
				$SPrdFGId  = "";
				$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];
						
				$txtPrdQtyFG    = 0;
				$txtPrdQtyFG    = $txtPrdQtyFG;
				$txtPrdQtyFG    = $txtPrdQtyFG*$vPackDtQty;
				
							
				$txtPrdPriceFG  = $txtPrdPriceFG*$vPackDtCostPer/100;
			
				$vPrdCostBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
				$vPrdCostBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
				
				$txtPrdNetFG = $txtPrdPriceFG * $txtPrdQtyFG;
				$vPrdNetBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);
				$vPrdNetBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);
				
				fbegin();
				$SPrdFGId = get_nextsequence('productionFactoryfg_id','',$connection);
				fcommit();			
							 
				fbegin();	 
				$query = " INSERT INTO temp_productionFactoryFG (productionFactoryfg_id, productionFactory_id, item_code, item_created, warehouse_code, productionFactoryfg_qty, productionFactoryfg_price, ".
						 " productionFactoryfg_price1, productionFactoryfg_price2, productionFactoryfg_net, productionFactoryfg_net1, productionFactoryfg_net2,  project_codedt, costcent_codedt  ) ".
						 " VALUES ( ".$SPrdFGId.", ".$SPrdId.", '".$vItemCode."',  '".$txtItemCreadted."', '".ereg_replace("'", "\'", trim($lstWarehouse))."', $txtPrdQtyFG, $txtPrdPriceFG, ".
						 " $vPrdCostBase1, $vPrdCostBase2, $txtPrdNetFG, $vPrdNetBase1, $vPrdNetBase2, ".$txtPrdProjectCodedt.", ".$txtPrdCostcentCodedt." ) ";
						
				$result=mysql_query($query,$connection);
				//echo $query."<br>";
						
						
			} // End Loop Of Packdt
					
			//echo $ErrorExists; echo $message; exit;
			if ($result){
				fcommit();
				$range = 0;
				$lastnbr = 0;
				for($i=1; $i<= $txtItemCreadted; $i++){
					$itemexist = 0;
					$nbrs = range(0+$range, 9+$range);
					foreach($nbrs as $nbr){
						foreach($alphas as $alpha){
							$sub_item = $vItemCode."-".$alpha.$nbr;
							$querycheck = "select productionFactorysf_id from temp_productionFactorySF where item_code = '$sub_item' and productionFactory_id = ".$SPrdId.";";
							$rescheck = mysql_query($querycheck,$connection);
							$numrw = mysql_num_rows($rescheck);
							if($numrw == 0){
								fbegin();
								$SPrdSFId = get_nextsequence('productionFactorysf_id','',$connection);
								fcommit();	
								$insert = "insert into temp_productionFactorySF (productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, warehouse_code, ".
										" productionFactorysf_qty, productionFactorysf_price, productionFactorysf_price1, productionFactorysf_price2, project_codedt, costcent_codedt) values ".
										" ( ".$SPrdSFId.",".$SPrdFGId.", ".$SPrdId.", '".$sub_item."', '".ereg_replace("'", "\'", trim($lstWarehouse))."', $txtPrdQtyFG, $txtPrdPriceFG, ".
										" $vPrdCostBase1, $vPrdCostBase2, ".$txtPrdProjectCodedt.", ".$txtPrdCostcentCodedt." ) ";
								$res = mysql_query($insert,$connection);
								$query = "select 1 from items where item_code = '$sub_item';";
								$res = mysql_query($query,$connection);
								$numr = mysql_num_rows($res);
								if($numr == 0){
									fbegin();
									$item_id = get_nextsequence('Item_Increment','',$connection);
									fcommit();
									$insert2 = "insert into items(Item_Code, Item_Description, Item_Barcode, Currency_code, CostCent_Code, Group_code, SubGroup_Code, Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Category_code, Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, Item_Weight, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, item_id, BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, Item_NetWeight, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist) ".
											  " select '$sub_item',  concat( ifnull(".strformat($group_code).",Group_code), '-Width:',ifnull(".strformat($subgroup_code).",SubGroup_Code), '-Thickness:', ifnull(".strformat($category_code).",Category_code)), Item_Barcode, Currency_code, CostCent_Code, ifnull(".strformat($group_code).",Group_code), ifnull(".strformat($subgroup_code).",SubGroup_Code), Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2,  ifnull(".strformat($category_code).",Category_code), Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, null, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, '$item_id', BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, null, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist ".						 
											  " from items ".
											   " where item_code = '$vItemCode'";
									$result2 = mysql_query($insert2,$connection);								
								}
								$itemexist = 1;
							}
							if($itemexist == 1) break;
						}
						$lastnbr = $nbr;
						if($itemexist == 1) break;
					}
					if($lastnbr == $range-1) $range = $range + 10;
				}
			}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 != "" && ($SPrdFGId != "" || $SPrdSFId != "")){
	if ($vPrdCostCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($vPrdProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$vPrdProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	$query = " UPDATE temp_productionFactory SET  ".
			" productionFactory_date = '".insertMySQLDate($vPrdDate)."', Currency_Code = '".$vPrdCur."', productionFactory_remark = ".strformat($vPrdRemark).",Logged_User = '".$_SESSION['useraccount']."', ".
			" totnetweightrm = $txtNetWeightRM, totnetweightsf = $txtNetWeightSF, totwaste = $txtNetWaste, ".
			" productionfactory_manualno = ".strformat($vPrdManualNo).", project_code = ".strformat($vPrdProjectCode).", costcent_code = ".strformat($vPrdCostCode).",  ".
			" item_group = ".strformat($group_code).", item_subgroup = ".strformat($subgroup_code).", item_category = ".strformat($category_code)." ".
			" Where productionFactory_id = '".$SPrdId."'";
	$result=mysql_query($query,$connection);			 
	fbegin();	
					
	if ($SItemType == 'FG' && $SPrdFGId != "") {
		if ($txtPrdProjectCodedt != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$txtPrdProjectCodedt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Project Code.';
			}
		}
		if ($txtPrdCostcentCodedt != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$txtPrdCostcentCodedt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
			}
		}
		$txtPrdProjectCodedt = strformat($txtPrdProjectCodedt);
		$txtPrdCostcentCodedt = strformat($txtPrdCostcentCodedt);
		
		if (empty($txtPrdQtyFG))		$txtPrdQtyFG = 0;
		if (empty($txtPrdPriceFG))	    $txtPrdPriceFG = 0;
		if (empty($txtPrdNetFG))	    $txtPrdNetFG = 0;
		
		$vPrdPriceBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
		$vPrdPriceBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdPriceFG, $connection);
	
		$vPrdNetBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);
		$vPrdNetBase1    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdNetFG, $connection);
		
		$query = " UPDATE temp_productionFactoryFG SET  ".
				 " item_code = '".$txtItemCode."', warehouse_code = '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
				 " item_created = $txtItemCreadted, productionFactoryfg_qty = $txtPrdQtyFG, ".
				 " productionFactoryfg_price = $txtPrdPriceFG, productionFactoryfg_price1 = $vPrdPriceBase1, productionFactoryfg_price2 = $vPrdPriceBase2, ".
				 " productionFactoryfg_net = $txtPrdNetFG, productionFactoryfg_net1 = $vPrdNetBase1, productionFactoryfg_net2 = $vPrdNetBase1, ".
				 " project_codedt = ".$txtPrdProjectCodedt.", costcent_codedt = ".$txtPrdCostcentCodedt." ".
				 " Where productionFactoryfg_id = '".$SPrdFGId."'";
	} 
	else if ($SItemType == 'SF' && $SPrdSFId != "") {
		if (empty($txtPrdQtySF))		$txtPrdQtySF = 0;
		if (empty($txtPrdPriceSF))	    $txtPrdPriceSF = 0;
		
		if ($txtPrdProjectCodedt2 != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$txtPrdProjectCodedt2."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Project Code.';
			}
		}
		if ($txtPrdCostcentCodedt2 != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$txtPrdCostcentCodedt2."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
			}
		}
		
		$vPrdPriceBase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $txtPrdPriceSF, $connection);
		$vPrdPriceBase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $txtPrdPriceSF, $connection);
			
		$query = " UPDATE temp_productionFactorySF SET  ".
				 " item_code = '".$txtItemCode."', warehouse_code = '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
				 " productionFactorysf_weight = ".strformat($txtPrdWeightSF).", productionFactorysf_qty = $txtPrdQtySF, ".
				 " productionFactorysf_price = $txtPrdPriceSF, productionFactorysf_price1 = $vPrdPriceBase1, productionFactorysf_price2 = $vPrdPriceBase2, ".
				 " project_codedt = ".strformat($txtPrdProjectCodedt2).", costcent_codedt = ".strformat($txtPrdCostcentCodedt2)." ".
				 " Where productionFactorysf_id = '".$SPrdSFId."'";
	}
					 
	//echo $query; exit;
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();
		if($SItemType == 'FG' && $SPrdFGId != ""){
			$range = 0;
			$lastnbr = 0;
			$querycount = "select productionFactorysf_id from temp_productionFactorySF where productionFactoryfg_id = ".$SPrdFGId.";"; 
			$rescount = mysql_query($querycount,$connection);
			$numcount = mysql_num_rows($rescount);
			$txtItemCreadted = abs($txtItemCreadted - $numcount ); 
			for($i=1; $i<= $txtItemCreadted; $i++){
				$itemexist = 0;
				$nbrs = range(0+$range, 9+$range);
				foreach($nbrs as $nbr){
					foreach($alphas as $alpha){
						$sub_item = $txtItemCode."-".$alpha.$nbr;
						$querycheck = "select productionFactorysf_id from temp_productionFactorySF where item_code = '$sub_item' and productionFactory_id = ".$SPrdId.";";
						$rescheck = mysql_query($querycheck,$connection);
						$numrw = mysql_num_rows($rescheck);
						if($numrw == 0){
							fbegin();
							$SPrdSFId = get_nextsequence('productionFactorysf_id','',$connection);
							fcommit();	
							$insert = "insert into temp_productionFactorySF (productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, warehouse_code, ".
									" productionFactorysf_qty, productionFactorysf_price, productionFactorysf_price1, productionFactorysf_price2, project_codedt, costcent_codedt) values ".
									" ( ".$SPrdSFId.",".$SPrdFGId.", ".$SPrdId.", '".$sub_item."', '".ereg_replace("'", "\'", trim($lstWarehouse))."', $txtPrdQtyFG, $txtPrdPriceFG, ".
									" $vPrdPriceBase1, $vPrdPriceBase2,  ".$txtPrdProjectCodedt.", ".$txtPrdCostcentCodedt." ) ";
							$res = mysql_query($insert,$connection);	
							
							$query = "select 1 from items where item_code = '$sub_item';";
							$res = mysql_query($query,$connection);
							$numr = mysql_num_rows($res);
							
							//echo $numr;exit;
							
							/*if($numr > 0){
								$update = " update items set Group_code = ".strformat($group_code).", SubGroup_Code = ".strformat($subgroup_code)." , Category_code = ".strformat($category_code).", ".
										  " Item_Weight = null, Item_NetWeight = null where item_code='$txtItemCode';";
								$res = mysql_query($update,$connection);
							} else */
							if($numr == 0)	{
								fbegin();
								$item_id = get_nextsequence('Item_Increment','',$connection);
								fcommit();
								$insert2 = "insert into items(Item_Code, Item_Description, Item_Barcode, Currency_code, CostCent_Code, Group_code, SubGroup_Code, Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Category_code, Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, Item_Weight, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, item_id, BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, Item_NetWeight, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist) ".
										  " select '$sub_item',  concat( ifnull(".strformat($group_code).",Group_code), '-Width:',ifnull(".strformat($subgroup_code).",SubGroup_Code), '-Thickness:', ifnull(".strformat($category_code).",Category_code)), Item_Barcode, Currency_code, CostCent_Code, ifnull(".strformat($group_code).",Group_code), ifnull(".strformat($subgroup_code).",SubGroup_Code), Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2,  ifnull(".strformat($category_code).",Category_code), Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, null, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, '$item_id', BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, null, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist ".						 
										  " from items ".
										  " where item_code = '$txtItemCode'";
								$result2 = mysql_query($insert2,$connection);			
							}
							$itemexist = 1;
						}
						if($itemexist == 1) break;
					}
					$lastnbr = $nbr;
					if($itemexist == 1) break;
				}
				if($lastnbr == $range-1) $range = $range + 10;
			}	
			
			
			
		} 
		else if($SItemType == 'SF' && $SPrdSFId != ""){
			$query = "select 1 from items where item_code = '$txtItemCode';";
			$res = mysql_query($query,$connection);
			$numr = mysql_num_rows($res);
			if($numr > 0){
				$update = " update items set item_description=concat( ifnull(".strformat($group_code).",Group_code), '-Width:',ifnull(".strformat($subgroup_code).",SubGroup_Code), '-Thickness:', ifnull(".strformat($category_code).",Category_code)) ".
				          " ,Group_code = ".strformat($txtgroup_code).", SubGroup_Code = ".strformat($txtsubgroup_code)." , Category_code = ".strformat($txtcategory_code).", ".
						  " Item_Weight = ".strformat($txtPrdWeightSF).", Item_NetWeight = ".strformat($txtPrdWeightSF)." where item_code='$txtItemCode';";
				$res = mysql_query($update,$connection);
			} 
		}
			
	}else{
		$message  = mysql_error(); 
		frollback();
	}		

}

//Delete Raw Materials
else if ($mode == "deletedtSF" && $SPrdSFId != ""){

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

		$ErrorExists    = 0;
		fbegin();
		$query = " DELETE FROM temp_productionFactorySF ".
				 " WHERE productionFactorysf_id = '".$SPrdSFId."'";
		
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
		
	if($ErrorExists == 0){
		$query = "select sum(ifnull(Item_NetWeight,0))
				from temp_productionFactoryFG
				inner join items on items.item_code  = temp_productionFactoryFG.item_code
				where productionFactory_id ='".$SPrdId."';";
		$res = mysql_query($query,$connection);
		$rw = mysql_fetch_row($res);
		$totnetWeight = $rw[0];
		if($totnetWeight == '') $totnetWeight = 0;
		
		$query = "select sum(ifnull(productionFactorysf_weight,0))
				from temp_productionFactorySF
				where productionFactory_id = '".$SPrdId."';";
		$res = mysql_query($query,$connection);
		$rw = mysql_fetch_row($res);
		$totSFWeight = $rw[0];
		if($totSFWeight == '') $totSFWeight = 0;
		
		$totwaste = $totnetWeight - $totSFWeight;
		$update = "update temp_productionFactory set totnetweightrm = $totnetWeight, totnetweightsf = $totSFWeight, totwaste = $totwaste where productionFactory_id = '".$SPrdId."'";
		$res = mysql_query($update,$connection);
	}
			
	} // End If No Constraints Found On Delete
	
}

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

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

		$ErrorExists    = 0;
		
		fbegin();
		$query = " DELETE FROM temp_productionFactorySF ".
				 " WHERE productionFactoryfg_id = '".$SPrdFGId."'";
				 
		fbegin();
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
		
	if($ErrorExists == 0){
		$query = " DELETE FROM temp_productionFactoryFG ".
				 " WHERE productionFactoryfg_id = '".$SPrdFGId."'";
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
				
	}
	
	if($ErrorExists == 0){
		$query = "select sum(ifnull(Item_NetWeight,0))
				from temp_productionFactoryFG
				inner join items on items.item_code  = temp_productionFactoryFG.item_code
				where productionFactory_id ='".$SPrdId."';";
		$res = mysql_query($query,$connection);
		$rw = mysql_fetch_row($res);
		$totnetWeight = $rw[0];
		if($totnetWeight == '') $totnetWeight = 0;
		
		$query = "select sum(ifnull(productionFactorysf_weight,0))
				from temp_productionFactorySF
				where productionFactory_id = '".$SPrdId."';";
		$res = mysql_query($query,$connection);
		$rw = mysql_fetch_row($res);
		$totSFWeight = $rw[0];
		if($totSFWeight == '') $totSFWeight = 0;
		
		$totwaste = $totnetWeight - $totSFWeight;
		$update = "update temp_productionFactory set totnetweightrm = $totnetWeight, totnetweightsf = $totSFWeight, totwaste = $totwaste where productionFactory_id = '".$SPrdId."'";
		$res = mysql_query($update,$connection);
	}
		
		
	} // 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 productionFactorySF ".
				 " WHERE productionFactory_id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		$query = " DELETE FROM productionFactoryFG ".
				 " WHERE productionFactory_id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		$query = " DELETE FROM productionFactory ".
				 " WHERE productionFactory_id = ".$SPrdId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error();   
		
	}
	
}

else if (($mode == "" && $mainmode == "deletepending") || ($mode == 'cancel') && $SPrdId != ''){

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

else if($mode == "" && $mainmode == "getWasteItem" && $SPrdId != ''){
	$errorexist = 0;
	$q = "select round(productionFactoryfg_price*$txtNetWaste/$txtNetWeightRM,$DecimalBase)
		from temp_productionFactoryFG as productionFactoryFG
		where productionFactory_id = $SPrdId
		limit 1";
	$rs = mysql_query($q,$connection);
	$rw = mysql_fetch_row($rs);
	$PriceWaste = $rw[0];
	
	$PriceWaste1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $PriceWaste, $connection);
	$PriceWaste2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $PriceWaste, $connection);
			
	fbegin();
	$SPrdSFId = get_nextsequence('productionFactorysf_id','',$connection);
	fcommit();	
	
	$insert = " insert into temp_productionFactorySF (productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, productionFactorysf_weight, warehouse_code, productionFactorysf_qty, ".
			  " productionFactorysf_price, productionFactorysf_price1, productionFactorysf_price2, project_codedt, costcent_codedt ) ".
			  " select $SPrdSFId,productionFactoryfg_id, productionFactoryFG.productionFactory_id, '$txtWasteItem','$txtNetWaste',productionFactoryFG.warehouse_code, 1, $PriceWaste, $PriceWaste1, ".
			  " $PriceWaste2, project_code, costcent_code ".
			  " from temp_productionFactoryFG as productionFactoryFG ".
			  " inner join temp_productionFactory as productionFactory on productionFactory.productionFactory_id = productionFactoryFG.productionFactory_id
				where productionFactoryFG.productionFactory_id = $SPrdId;";
	if (!updateData($connection, $insert, true)){
		$message  = mysql_error();  		
		$errorexist = 1;
		
	} 
	if($errorexist == 0){
		$update = "update temp_productionFactory set totnetweightsf = (totnetweightsf + $txtNetWaste), totwaste = 0, wasteItem_Code='$txtWasteItem' where productionFactory_id = $SPrdId";
		if (!updateData($connection, $update, true))
		$message  = mysql_error();  
	}
	echo $message;
	echo "[BRK]";	
	
exit;	
}
//Post Mode	
else if($mode == "post" && $SPrdId != ''){  

	$SaveAllow   = 1;
	$ErrorExists = 0;
	
	$vPrdDate = $_POST['txtDate'];
	$vPrdCur = $_POST['txtCurr'];
	$vPrdRemark = $_POST['txtRemark'];
	
	$vPrdManualNo = $_POST['txtManualNo'];
	$vPrdProjectCode = $_POST['txtProjectCode'];
	$vPrdCostCode = $_POST['txtCostCentCode'];
	
	if ($vPrdCostCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($vPrdProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$vPrdProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	$sub_query = " Select Count(*) FROM temp_productionFactoryFG ".
				 " WHERE productionFactory_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).";
	}
	
	/*$sub_query = " Select productionFactoryfg_id, ifnull(item_created,0) FROM temp_productionFactoryFG ".
				 " WHERE productionFactory_id = ".$SPrdId;	
	$result = mysql_query($sub_query,$connection);
	while($row = mysql_fetch_row($result)){
		$item_created = $row[1];
		$sub_query2 = " Select productionFactorysf_id FROM temp_productionFactorySF ".
				 " WHERE productionFactoryfg_id = ".$row[0];	
		$result2 = mysql_query($sub_query2,$connection);
		$numSF = mysql_num_rows($result2);
		if ($numSF != $item_created) {
		$ErrorExists = 1;
		$message = "Save not allowed. Please Numbers of (Finished Good) and (Semi Finished) Does not Macth.";
		break;
		}
	}*/
	//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;
	}
	//echo $sub_query;exit;
	

	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		
		$query = " UPDATE temp_productionFactory SET  ".
			" productionFactory_date = '".insertMySQLDate($vPrdDate)."', Currency_Code = '".$vPrdCur."', productionFactory_remark = ".strformat($vPrdRemark).",Logged_User = '".$_SESSION['useraccount']."' ".
			" , totnetweightrm = $txtNetWeightRM, totnetweightsf = $txtNetWeightSF, totwaste = $txtNetWaste, ".
			" productionfactory_manualno = ".strformat($vPrdManualNo).", project_code = ".strformat($vPrdProjectCode).", costcent_code = ".strformat($vPrdCostCode)." ".
			" Where productionFactory_id = '".$SPrdId."'";
		$result=mysql_query($query,$connection);	
		
		fbegin();		
		$query = "SELECT CopyData_TempProductionFactory('', ".$SPrdId.", '".$_SESSION['useraccount']."') FROM Dual ";//echo $query;exit;
		$result = selectData($connection, $query);
		$result = $result[0];
		if ($result != 0){
			fcommit();
						
			$query   = " SELECT productionFactory_reference FROM productionFactory WHERE productionFactory_id = $SPrdId ";
			$result  = selectData($connection, $query);
			$vPrdRef = $result[0];
					
			if ($vPrdRef == ''){
				if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
				else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
				else $vProjCostCent = '';			
											
				fbegin();
				$vPrdRef = get_nextsequence('productionFactory_reference',$vProjCostCent,$connection);	
				fcommit();
							
				$query = " UPDATE productionFactory SET ".
						 " productionFactory_reference = $vPrdRef ".
						 " WHERE productionFactory_id = $SPrdId ";
							
				if (!updateData($connection, $query, true)) 
					$message  = mysql_error();
						
			}
			
			
			$query = "select related_id, Currency_Code, productionFactory_date from productionFactory where productionFactory_id = $SPrdId "; 
			$res = mysql_query($query, $connection);
			$row = mysql_fetch_row($res);
			$vAdjId = $row[0];
			$vPrdCur = $row[1];
			$vPrdDate = $row[2];
			
			$querysub = "select sum(productionFactoryfg_net) as tot
								from productionFactoryFG  where productionFactory_id = $SPrdId
								group by productionFactory_id ";
			$ressub = mysql_query($querysub,$connection);
			$rowsub = mysql_fetch_row($ressub);
			$totFG = $rowsub[0];	
			
			$querysub = "select sum(productionFactorysf_price*productionFactorysf_qty) as tot
								from productionFactorySF  where productionFactory_id = $SPrdId
								group by productionFactory_id ";
			$ressub = mysql_query($querysub,$connection);
			$rowsub = mysql_fetch_row($ressub);
			$totSF = $rowsub[0];	
			
			$tot = $totSF - $totFG;
			$totbase1    = ConvertCurrency($vPrdCur, $base1, insertMySQLDate($vPrdDate), $tot, $connection);
			$totbase2    = ConvertCurrency($vPrdCur, $base2, insertMySQLDate($vPrdDate), $tot, $connection);
			if($totbase1 == '') $totbase1 = 0;
			if($totbase2 == '') $totbase2 = 0;
			
			if($vAdjId == ''){
				
				fbegin();
				$vAdjId = get_nextsequence('Adjustment_id','',$connection);
				fcommit();
				$vProjCostCent = '';

				fbegin();
				$vAdjRef = get_nextsequence('Adjustment_Reference',$vProjCostCent,$connection);

				fcommit();
				
				fbegin();
				$query = " INSERT INTO adjustment (Adjustment_ID, Adjustment_Reference, Adjustment_Date, Adjustment_Remak, Currency_Code, Costcent_code, Project_code, ".
						 " Adjustment_Type, Adjustment_EntryType, Adjustment_Amount, Adjustment_AmountBase1, Adjustment_AmountBase2, ".
						 " Journal_Id, Adjustment_BelongsToGroup, Adjustment_Posted, Entry_Type, User_Account ) ".
						 " select  ".$vAdjId.", ".$vAdjRef.", productionFactory_date, productionFactory_remark, Currency_Code, costcent_code, project_code, ".
						 "  'AD', 'A', $tot, $totbase1, $totbase2, Null, productionFactory_BelongsToGroup, 0, 'ADJUSTMENT', 
						 User_Account ".
						 " from productionFactory 
						  where  productionFactory.productionFactory_id = $SPrdId ";

				//echo $query;exit;
				$result=mysql_query($query,$connection);
			} else {
				
				fbegin();
				$query = " update adjustment, productionFactory ".
						 " set Adjustment_Date = productionFactory_date, Adjustment_Remak = productionFactory_remark, adjustment.Currency_Code = productionFactory.Currency_Code, ".
						 " Adjustment_Amount = $tot, Adjustment_AmountBase1 = $totbase1, Adjustment_AmountBase2 = $totbase2, ".
						 " adjustment.Adjustment_BelongsToGroup = productionFactory_BelongsToGroup,  ".
						 " adjustment.Costcent_code = productionFactory.costcent_code, adjustment.Project_code = productionFactory.project_code ".
						 " where  productionFactory_id = $SPrdId and Adjustment_ID = $vAdjId ";
				$result=mysql_query($query,$connection);
			} 
			
			if($result != 0){
				fcommit();
				$del = "delete from adjustmentdt where Adjustment_Id = $vAdjId";
				$res = mysql_query($del,$connection);
				$query1 = " select item_code, productionFactorysf_weight, warehouse_code, productionFactorysf_qty, productionFactorysf_price, productionFactorysf_price1, ".
						" productionFactorysf_price2, project_codedt, costcent_codedt ".
						" from productionFactorySF ".
						" where productionFactory_id = ".$SPrdId.";";
				$res1 = mysql_query($query1,$connection);
				while($rw1 = mysql_fetch_row($res1)){	
					
					$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), ifNull(Item_Unit, 0) ".
								 " FROM Items WHERE Item_Code = '".$rw1[0]."'";
					$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];
					$ItemUnit   	 = $sub_result[7];

					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					
					$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = 'AD' ".
								 " AND Group_code = '".$ItemGroupCode."'  ";

					$sub_result = selectData($connection, $sub_query);

					$vTranStpDirectStkDbt = $sub_result[0];
					$vTranStpDirectStkCrd = $sub_result[1];
					$vTranStpDirectStkCur = $sub_result[2];

					$vAdjDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vAdjDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vAdjDtDirectStkCur = $vTranStpDirectStkCur;
					
					fbegin();
					$vAdjDtId = get_nextsequence('AdjustmentDt_id','',$connection);
					fcommit();

				
					$query = " INSERT INTO adjustmentdt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date, Warehouse_Code, Project_code, Costcent_code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
							 " AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Journal_Type, AdjustmentDt_DirectStkDbt, AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, ".
							 " AdjustmentDt_Posted, Item_UnitCoef, Item_Unit2Qty ) ".
							 " select ".$vAdjDtId.", ".$vAdjId.", Currency_Code, productionFactory_date, '".$rw1[2]."',  ".strformat($rw1[7]).",  ".strformat($rw1[8]).", ".
							 " '".$rw1[0]."', Null, 0, ".$rw1[3].", $rw1[4], $rw1[5], $rw1[6], 0, 0, 'AI', '".$vAdjDtDirectStkDbt."', ".
							 " '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty  ".
							 " from productionFactory where productionFactory_id = $SPrdId  ";
//echo $query;
					$result=mysql_query($query,$connection);
				}
				
				$query2 = " select item_code, warehouse_code, productionFactoryfg_qty, productionFactoryfg_price, productionFactoryfg_price1, productionFactoryfg_price2, project_codedt, costcent_codedt  ".
						" from productionFactoryFG ".
						" where productionFactory_id = ".$SPrdId.";";
				$res2 = mysql_query($query2,$connection);
				while($rw2 = mysql_fetch_row($res2)){	
					
					$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), ifNull(Item_Unit, 0) ".
								 " FROM Items WHERE Item_Code = '".$rw2[0]."'";
					$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];
					$ItemUnit   	 = $sub_result[7];

					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					
					$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = 'AD' ".
								 " AND Group_code = '".$ItemGroupCode."'  ";

					$sub_result = selectData($connection, $sub_query);

					$vTranStpDirectStkDbt = $sub_result[0];
					$vTranStpDirectStkCrd = $sub_result[1];
					$vTranStpDirectStkCur = $sub_result[2];

					$vAdjDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vAdjDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vAdjDtDirectStkCur = $vTranStpDirectStkCur;
					
					fbegin();
					$vAdjDtId = get_nextsequence('AdjustmentDt_id','',$connection);
					fcommit();

				
					$query = " INSERT INTO adjustmentdt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date, Warehouse_Code,  Project_code, Costcent_code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
							 " AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Journal_Type, AdjustmentDt_DirectStkDbt, AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, ".
							 " AdjustmentDt_Posted, Item_UnitCoef, Item_Unit2Qty ) ".
							 " select ".$vAdjDtId.", ".$vAdjId.", Currency_Code, productionFactory_date, '".$rw2[1]."',  ".strformat($rw2[6]).",  ".strformat($rw2[7]).", ".
							 " '".$rw2[0]."', Null, 0, -".$rw2[2].", $rw2[3], $rw2[4], $rw2[5], 0, 0, 'AR', '".$vAdjDtDirectStkDbt."', ".
							 " '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty ".
							 " from productionFactory where productionFactory_id = $SPrdId  ";
//echo $query;
					$result=mysql_query($query,$connection);
				}
				$message = Create_AdjustmentJv($vAdjId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);

				$query = "update productionFactory set related_id = $vAdjId where productionFactory_id = $SPrdId ";
				$res = mysql_query($query, $connection);
			} else {
				$message  = mysql_error(); 
				frollback();
			}
			//exit;
		} 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();
	}	
}

else if($mainmode == "search" && $SPrdId != ''){
	$query = "insert into temp_productionFactory (productionFactory_id, productionFactory_reference, productionFactory_date, Currency_Code, productionFactory_remark, productionFactory_BelongsToGroup, ".
			" User_Account, Logged_User, totnetweightrm, totnetweightsf, totwaste, related_id, productionfactory_manualno, project_code, costcent_code, wasteItem_Code) ".
			" select productionFactory_id, productionFactory_reference, productionFactory_date, Currency_Code, productionFactory_remark, productionFactory_BelongsToGroup, ".
			" User_Account, '".$_SESSION['useraccount']."', totnetweightrm, totnetweightsf, totwaste, related_id, productionfactory_manualno, project_code, costcent_code, wasteItem_Code ".
			" from productionFactory ".
			" where productionFactory_id = ".$SPrdId.";";
	if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 	

	$query = "insert into temp_productionFactoryFG (productionFactoryfg_id, productionFactory_id, item_code, item_created, warehouse_code, productionFactoryfg_qty, productionFactoryfg_price, productionFactoryfg_price1, ".
			" productionFactoryfg_price2, productionFactoryfg_net, productionFactoryfg_net1, productionFactoryfg_net2, project_codedt, costcent_codedt) ".
			" select productionFactoryfg_id, productionFactory_id, item_code, item_created, warehouse_code, productionFactoryfg_qty, productionFactoryfg_price, productionFactoryfg_price1, productionFactoryfg_price2, ".
			" productionFactoryfg_net, productionFactoryfg_net1, productionFactoryfg_net2, project_codedt, costcent_codedt ".
			" from productionFactoryFG ".
			" where productionFactory_id = ".$SPrdId.";";
	if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 
		
	$query = "insert into temp_productionFactorySF (productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, productionFactorysf_weight, warehouse_code, productionFactorysf_qty, productionFactorysf_price, ".
			" productionFactorysf_price1, productionFactorysf_price2,project_codedt, costcent_codedt) ".
			" select productionFactorysf_id, productionFactoryfg_id, productionFactory_id, item_code, productionFactorysf_weight, warehouse_code, productionFactorysf_qty, productionFactorysf_price, productionFactorysf_price1, ".
			" productionFactorysf_price2, project_codedt, costcent_codedt ".
			" from productionFactorySF ".
			" where productionFactory_id = ".$SPrdId.";";
	if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 	
}

else if ($mode == "" && $mainmode == "getiteminfo"){
	$txtItemCode = $_GET['txtItemCode'];
	$txtDate	 = $_GET['txtDate'];
	$txtCurr	 = $_GET['txtCurr'];
	
	$query = "select ifnull(Item_NetWeight,0), round(MeanCostCur('$txtItemCode','".insertMySQLDate($txtDate)."',1, '$base1','$txtCurr'),$DecimalBase)
			from items where item_code='$txtItemCode';";
	$res = mysql_query($query,$connection);
	$rw = mysql_fetch_row($res);
	$netweight = $rw[0];
	$avgCost = $rw[1];
	
	echo $message;
	echo "[BRK]";
	echo $netweight;
	echo "[BRK]";
	echo $avgCost;
	exit;
}

else if ($mode == "" && $mainmode == "CalcWeight"){
	$txtNetWeightRM = $_GET['txtNetWeightRM'];
	$prdsfid	 	= $_GET['prdsfid'];
	$txtPrdId	 	= $_GET['txtPrdId'];
	
	$query = "select sum(ifnull(productionFactorysf_weight,0))
			from temp_productionFactorySF
			where productionFactory_id = $txtPrdId and productionFactorysf_id <> $prdsfid;";
	$res = mysql_query($query,$connection);
	$rw = mysql_fetch_row($res);
	$netweight = $rw[0];
	
	echo $message;
	echo "[BRK]";
	echo $netweight;
	exit;
}
$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_ProductionFactory.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPrdId=".$SPrdId."&PrPrdRef=".$vPrdRef."&message=".$message);
	else
		header ("Location: ./Form_ProductionFactory.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);
}if($mode == "cancel") {
	header ("Location: ./Form_ProductionFactory.php?message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_ProductionFactorySearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending" )	
	header ("Location: ./Form_ProductionFactorySearchPending.php?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);
} else if($mode == "" && $mainmode == "search")
	header ("Location: ./Form_ProductionFactorySearch.php?PMode=1&message=".$message);	

$return_arr = array();

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

function strformat($str){
	if($str == "") $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}



?>