<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

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

$txtItemCode = $_POST['txtItemCode']; if($txtItemCode == ""){ $txtItemCode = $_GET['txtItemCode']; }
$txtItemCode = trim(strtoupper($txtItemCode));

$lstWarehouse = $_POST['lstWarehouse']; if($lstWarehouse == "") { $lstWarehouse = $_GET['lstWarehouse']; }
$lstWarehouse = trim(strtoupper($lstWarehouse));

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$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_rawmaterial,0) As Module_RawMaterial, ".
             " ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_DirectStockPD,0) As Module_DirectStockPD, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_Sorderproduction,0) As Module_Sorderproduction ".
			 " 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(Actual_Zero,0) As Actual_Zero,ifNull(ShowAdditions,0) as ShowAdditions, ifNull(Production_extraInfo,0) As Production_extraInfo,
					   ifnull(showNonStockItem,0) as showNonStockItem, waste_warehouseCode 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='SSelectdId' value='$SSelectdId'>
HERE;
*/
$message='';


if ($mode == 'CheckQtyExists'){
	$vItemCode 		= $_GET['vItemCode'];
	$vWarehouseCode = $_GET['vWarehouseCode'];
	$vDate 			= $_GET['vDate'];
	$data = substr($vDate, 6, 4) . substr($vDate, 3, 2) . substr($vDate, 0, 2);
    $vDate = substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");
	
	$QtyExists = 0;
	if ($Prdt_id == '') $Prdt_id = 0;
	
	if ($vItemCode != ''){
		$query = "select ifnull(Item_Pack,0) from items where item_code = '$vItemCode' ";
		$res = mysql_query($query, $connection);
		$rw = mysql_fetch_row($res);
		$Item_Pack = $rw[0];
		if ($Item_Pack==1)
		{
			$min_sorder_qty = 0;
			$min_available_qty = 9999999999;
			$min_exists_qty = 9999999999;
			$available_qty = 0;
			$exist_qty = 0;
			
			$queryPack = "SELECT Item_CodePackDt, PackDt_Quantity FROM packdt WHERE Item_Code = '".$vItemCode."' And ifNull(PackDt_CostPercentage,0) != 0 ";
			$resultPack = mysql_query($queryPack, $connection);
			
			while($cur = mysql_fetch_row($resultPack)){
			$Qry_QtyExists = " SELECT ifnull(QtyExists('".$cur[0]."', '".$vWarehouseCode."', '".$vDate."', $Prdt_id, 'PD', '', ''),0) As QtyExists ";
			$resultex = mysql_query($Qry_QtyExists, $connection);
			$sub_result3 = mysql_fetch_row($resultex);
		
			$exist_qty = ($sub_result3[0] / $cur[1]); 
			if ($exist_qty < $min_exists_qty && $exist_qty != 0){
				$min_exists_qty = $exist_qty;
			}
			
			}
			$min_exists_qty = floor($min_exists_qty);
		} else {
			$Qry_QtyExists = " SELECT ifnull(QtyExists('".$vItemCode."', '".$vWarehouseCode."', '".$vDate."', $Prdt_id, 'PD', '', ''),0) As QtyExists ";
			echo $Qry_QtyExists;
			$resultex = mysql_query($Qry_QtyExists, $connection);
			$rex = mysql_fetch_row($resultex);		
			$min_exists_qty = $rex[0];
		
		}
	}
	if ($min_exists_qty != '') $QtyExists = $min_exists_qty;
	echo "[BRK]";
	echo $QtyExists;
	exit;
}
if($mode == 'CheckExtraInfo' && $SPrdId != ''){
	$query = "select item_Shade, production_shadeAct, item_Strength , production_strengthAct, production_prevBatchno , production_referenceStd ,
		production_viscosityDirect, production_viscosityReduced, packingdt_amountStrd, packingdt_nbrStrd , packingdt_amountAct,
		packingdt_nbrAct, item_reducer, Item_UnitSalesDesc, item_retarder, item_ViscosityDirect,item_ViscosityReduced,production_gloss,production_Adhesion,item_gloss,item_Adhesion,
		production_Alkali,production_scuff,item_Alkali,item_scuff,packingdt_amountAct2,packingdt_nbrAct2 from temp_production
		left join items on items.item_code = temp_production.item_code
		where Production_id=$SPrdId"; //echo $query;
	$res = mysql_query($query,$connection);
	$rows=mysql_fetch_row($res);
	
	$txtprodshadestrd = $rows[0];
	$txtprodshadeact = $rows[1];
	$txtprodstrengthstrd = $rows[2];
	$txtprodstrengthact = $rows[3];
	$txtproduction_prevBatchno = $rows[4];
	$txtproduction_referenceStd = $rows[5];

	$txtproduction_viscosityDirect = $rows[6];
	$txtproduction_viscosityReduced = $rows[7];

	$txtproduction_gloss = $rows[17];
	$txtproduction_Adhesion = $rows[18];

	$txtpackingdt_amountStrd = $rows[8];
	$txtpackingdt_nbrStrd = $rows[9];

	$txtpackingdt_amountAct = $rows[10];
	$txtpackingdt_nbrAct = $rows[11];

	$txtReducer = $rows[12];
	$txtRetarder = $rows[14];

	$txtitem_ViscosityDirect = $rows[15];
	$txtitem_ViscosityReduced = $rows[16];

	$txtitem_gloss = $rows[19];
	$txtitem_Adhesion = $rows[20];

	$txtproduction_Alkali = $rows[21];
	$txtproduction_scuff = $rows[22];

	$txtitem_Alkali = $rows[23];
	$txtitem_scuff = $rows[24];

	$txtpackingdt_amountAct2 = $rows[25];
	$txtpackingdt_nbrAct2 = $rows[26];
	
	if( ($txtprodshadestrd != '' && $txtprodshadeact == '') || ($txtprodstrengthstrd != '' && $txtprodstrengthact == '') || ($txtitem_ViscosityDirect != '' && $txtproduction_viscosityDirect == '')
		|| ($txtitem_ViscosityReduced != '' && $txtproduction_viscosityReduced == '')  || ($txtitem_gloss != '' && $txtproduction_gloss == '') || ($txtitem_Adhesion != '' && $txtproduction_Adhesion == '')
		|| ($txtitem_Alkali != '' && $txtproduction_Alkali == '') || ($txtitem_scuff != '' && $txtproduction_scuff == '') || ($txtitem_scuff != '' && $txtproduction_scuff == '')	)
		
	$message = "Please Check Quality Assurance!";	
	else $message = "";		
//	exit;
}
else if($mode == 'transferDataFG'){
	$prodActualQty = $_GET['prodActualQty'];
	
	$ErrorExists = 0;
	
	$transferid = get_nextsequence('transfer_id','',$connection);
	$transferref = get_nextsequence('transfer_reference','',$connection);
	$transferdtid = get_nextsequence('transferdt_id','',$connection);
	
	$queryProd = "select ifnull(production_quantity,0) from production where Production_ID = $SPrdId ";
	$resProd = mysql_query($queryProd, $connection);
	$rowProd = mysql_fetch_row($resProd);
	$production_quantity = $rowProd[0];
	
	$wasteQty = $production_quantity - $prodActualQty;
		
	fbegin();	
	$query = "insert into transfer(Transfer_reference,Transfer_Id,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, Synchronized,    User_account,
			Transfer_Type) 
			select $transferref,$transferid,now(),0,0,project_code,project_code,costcenter_code,0,0,'".$_SESSION['useraccount']."','Tr' 
			from production Where Production.Production_ID = $SPrdId";
	
	//echo $query."<br>"; exit;
	$result=mysql_query($query,$connection);	
	
	if (!$result){
		frollback();
		$ErrorExists = 1;
		$message = mysql_error();
	}
	if ($ErrorExists == 0){
		$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) 
					select $transferdtid,$transferid,now(),item_code,warehouse_code,'FG',production_quantity,
					   0,0,0,0,project_code,project_code,costcenter_code,0 from production Where Production.Production_ID = $SPrdId";
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());		
		if ($resultdt){
			fcommit(); 
		}
		else {
			frollback();
			$ErrorExists = 1;
			$message = mysql_error();
		}
	}	
	if ($ErrorExists == 0){
		$query2 = "update production set transfer_id=$transferid Where Production.Production_ID = $SPrdId";
		$result2=mysql_query($query2,$connection) or die(mysql_error());	
	}
	
	if ($ErrorExists == 0 && $waste_warehouseCode != '' && $wasteQty > 0){
		$transferid2 = get_nextsequence('transfer_id','',$connection);
		$transferref2 = get_nextsequence('transfer_reference','',$connection);
		$transferdtid2 = get_nextsequence('transferdt_id','',$connection);
		fbegin();	
		$query = "insert into transfer(Transfer_reference,Transfer_Id,Transfer_Date, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,  Transfer_BelongsToGroup, 
				Synchronized,User_account,Transfer_Type) 
				select $transferref2,$transferid2,now(),0,0,project_code,project_code,costcenter_code,0,0,'".$_SESSION['useraccount']."','Tr' 
				from production Where Production.Production_ID = $SPrdId";
		
		//echo $query."<br>"; exit;
		$result=mysql_query($query,$connection);	
		
		if (!$result){
			frollback();
			$ErrorExists = 1;
			$message = mysql_error();
		}
		if ($ErrorExists == 0){
			$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) 
						select $transferdtid2,$transferid2,now(),item_code,'FG', '$waste_warehouseCode', '$wasteQty',
						   0,0,0,0,project_code,project_code,costcenter_code,0 from production Where Production.Production_ID = $SPrdId";
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());		
			if ($resultdt){
				fcommit(); 
				$query2 = "update production set transfer_id2=$transferid2 Where Production.Production_ID = $SPrdId";
				$result2=mysql_query($query2,$connection) or die(mysql_error());	
			}
			else {
				frollback();
				$ErrorExists = 1;
				$message = mysql_error();
			}
		}
		
	}
	
	
} 

else if ($mode == "checkduplicate" ){

$query = " select  1 from Temp_Productiondt where item_code='".$PItem."' and Production_id = ".$SSaId;
$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_array($result);
echo $row[0];
exit;
}
else
if ($mode == "submitrecord" || $mode == "loadmaterials" || $mode == "submitrecord-ajax" || $mode == 'loadmaterialsproj'){//Submit Record Mode
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
						  
	if ($mode == "submitrecord" || $mode == "submitrecord-ajax") {
		$vPrdDate         = $PPrdDate;
		$vPrdExpireDate   = $PPrdExpireDate;
		$vPrdBatchNo 	  = $PPrdBatchNo;
		$vPrdItemCode     = $PPrdItemCode;
		$vPrdWhCode       = $PPrdWhCode;
		$vPrdCurr         = $PPrdCurr;
		$vPrdProjectCode  = $PPrdProjectCode;
		$vPrdCostCentCode = $PPrdCostCentCode;
		$vPrdQty          = $PPrdQty;
		$vPrdQtyIdeal     = $PPrdQtyIdeal;
		$vPrdWaste        = $PPrdWaste;
		$vPrdRemark       = $PPrdRemark;
		$vPrdQtyill		  = $txtqtyill;
	}
	else if ($mode == "loadmaterials" || $mode == 'loadmaterialsproj') {
		$vPrdDate         = $txtDate;
		$vPrdExpireDate   = $txtExpireDate;
		$vPrdBatchNo 	  = $txtPrdBatchNo;
		$vPrdItemCode     = $txtItemCodeFG;
		$vPrdWhCode       = $txtWhCode;
		$vPrdCurr         = $txtCurr;
		$vPrdProjectCode  = $txtProjectCode;
		$vPrdCostCentCode = $txtCostCentCode;
		$vPrdQty          = $txtPrdQty;
		$vPrdQtyIdeal     = $txtPrdQtyIdeal;
		$vPrdWaste        = $txtPrdWaste;
		$vPrdRemark       = $txtRemark;
		$vPrdQtyill		  = $txtqtyill;
	
	}
	
	
	
	if (empty($vPrdExpireDate))		$vPrdExpireDate = 'Null';
	else  $vPrdExpireDate = "'".insertMySQLDate($vPrdExpireDate)."'";
	

	if (!isset($vPrdCurr))	    $vPrdCurr = $base1;
	if (empty($vPrdQty))		$vPrdQty = 0;   
	if (empty($vPrdQtyIdeal))	$vPrdQtyIdeal = $vPrdQty;
	if (empty($vPrdWaste))		$vPrdWaste = 0;
	if (empty($vPrdQtyill))		$vPrdQtyill = 0;		   
	   
	$vPrdCostCentCode = "".$vPrdCostCentCode;	
	if ($vPrdCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vPrdCostCentCode."'";
	
	$vPrdProjectCode = "".$vPrdProjectCode;		
	if ($vPrdProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vPrdProjectCode."'";   

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($vPrdCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCentCode."'";
		$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."' and ifnull(project_blocked,0) = 0 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($vPrdItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$vPrdItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for FG Item Code.';
		}
	}
	if ($vPrdWhCode != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$vPrdWhCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for FG Warehouse Code.';
		}
	}
	
	if ($mode == "submitrecord" || $mode == "submitrecord-ajax") {
		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 RM Item Code.';
			}
		}
		
		if ($lstWarehouse != '') {
			$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
						 " Where Warehouse_Code = '".$lstWarehouse."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for RM Warehouse Code.';
			}
		}
		if ($txtProjectCodeDt != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$txtProjectCodeDt."' and ifnull(project_blocked,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Project Code.';
			}
		}
	
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($txtCostCentCodeDt != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$txtCostCentCodeDt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
			}
		}
	}
	
	
	//Insert Master Table
	if ($SPrdId == "" && $ErrorExists == 0){
	
		$vPrdDirectStkDbt = '';
		$vPrdDirectStkCrd = '';
		$vPrdDirectStkCur = '';
		$vPrdWasteDbtAcc  = '';
		$vPrdWasteCrdAcc  = '';
		$vPrdWasteDifAcc  = '';
		$vPrdItemAcc      = '';
			
		fbegin();	
		$vPrdId = get_nextsequence('Production_id','',$connection);
		fcommit();
		
		$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_QtyToBeProduced, 1) ".
			         " FROM Items WHERE Item_Code = '".$vPrdItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		$ItemVat 	     = $sub_result[0];
		$ItemGroupCode   = $sub_result[1];
		$ItemProd        = $sub_result[2];
		$ItemTTCInc      = $sub_result[3];
		$ItemQtyToBeProd = $sub_result[4];
	//ECHO "XXXXX3";
//EXIT;
	
				
				
		$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
		//echo $sub_query; exit;			 
		$sub_result = selectData($connection, $sub_query);
				
		$vTranStpDirectStkDbt = $sub_result[0];
		$vTranStpDirectStkCrd = $sub_result[1];
		$vTranStpDirectStkCur = $sub_result[2];
		$vTranStpWasteDbtAcc  = $sub_result[3];
		$vTranStpWasteCrdAcc  = $sub_result[4];
		$vTranStpWasteDifAcc  = $sub_result[5];
		$vTranStpNonRmVatAcc  = $sub_result[6];
		$vTranStpRmVatAcc     = $sub_result[7];
		$vTranStpNonRmTTCIncAcc  = $sub_result[8];
		$vTranStpRmTTCIncAcc     = $sub_result[9];
		$vTranStpNonRmAcc        = $sub_result[10];
		$vTranStpRmAcc           = $sub_result[11];
				
		$vPrdDirectStkDbt = $vTranStpDirectStkDbt;
		$vPrdDirectStkCrd = $vTranStpDirectStkCrd;
		$vPrdDirectStkCur = $vTranStpDirectStkCur;
		$vPrdWasteDbtAcc  = $vTranStpWasteDbtAcc;
		$vPrdWasteCrdAcc  = $vTranStpWasteCrdAcc;
		$vPrdWasteDifAcc  = $vTranStpWasteDifAcc;
					
		if ($ItemVat > 0) {
			if ($ItemProd == 1)	$vPrdItemAcc = $vTranStpNonRmVatAcc; else $vPrdItemAcc = $vTranStpRmVatAcc;
		}
		else {
			if ($ItemProd == 1) {
				if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdItemAcc = $vTranStpNonRmAcc;
			}	
			else {
				if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpRmTTCIncAcc; else $vPrdItemAcc = $vTranStpRmAcc;
			}
		}	
			
		if ($Module_ExpireDate == 1 || $Module_Sorderproduction == 1) {
			$expdate = explode('/',$vPrdDate);
			$newdate = $expdate[2]."".$expdate[1]."".$expdate[0]; 
			$querydate = "select date_format('$newdate','%c'), date_format('$newdate','%y') ;";
			$resdate = mysql_query($querydate, $connection);
			$rwdate = mysql_fetch_row($resdate);
			$vmonth = $rwdate[0];
			$vyear = $rwdate[1];
			$queryseq = "select (prod_ref+1) from jfolio where Journal_Date = '$vmonth'";
			$resseq = mysql_query($queryseq,$connection);
			$rowseq = mysql_fetch_row($resseq);
			$seqno = $rowseq[0]; 
			if(strlen($seqno) == 1) $seqno = '00'.$seqno;
			else if(strlen($seqno) == 2) $seqno = '0'.$seqno;
			//$vbacthno = $vmonth."".$seqno."/".$vyear;
			
		} 
		//else $vbacthno = '0';
		if($txtClientCode!='') $clientcode=$txtClientCode;
		fbegin();
		$query = " INSERT INTO temp_production (Production_ID, Production_Reference, Production_Date, Production_Remark, Currency_Code, Project_Code, Costcenter_code, ".
				 " Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_Total, Production_TotalBase1, Production_TotalBase2, ".
				 " Production_IdealTotal, Journal_Id, Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, Production_DirectStkDbt, ".
				 " Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff, Production_ExpireDate, Production_BatchNo, User_Account, Logged_Code, Production_idealqty,Quantity_Ill";
		if($clientcode != '') $query = $query." ,Client_Code ";
		$query = $query." ) ";
		$query = $query." VALUES ( ".$vPrdId.", Null, '".insertMySQLDate($vPrdDate)."', '".ereg_replace("'", "\'", trim($vPrdRemark))."', '".$vPrdCurr."', ".
				 "          $ProjectCode, $CostCentCode, 'P', '".ereg_replace("'", "\'", trim($vPrdItemCode))."', '".ereg_replace("'", "\'", trim($vPrdWhCode))."', $vPrdQty, ".
				 "          0, 0, 0, 0, Null, $FI_BelongsToGrp, 0, 0, 0, '".$vPrdItemAcc."', '".$vPrdDirectStkDbt."', '".$vPrdDirectStkCrd."', '".$vPrdDirectStkCur."', ".
				 "          '".$vPrdWasteDbtAcc."', '".$vPrdWasteCrdAcc."', '".$vPrdWasteDifAcc."', $vPrdExpireDate, '".ereg_replace("'", "\'", trim($vPrdBatchNo))."', ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',$vPrdQtyIdeal, $vPrdQtyill ";
		if($clientcode != '' ) $query = $query." ,'".$clientcode."' ";
		$query = $query." ) ";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdId = $vPrdId;
			$PPrdId = $vPrdId;
			if ($Module_ExpireDate == 1 || $Module_Sorderproduction == 1) {
			$queryupdatebacth = "update jfolio set prod_ref = prod_ref+1 where Journal_Date='$vmonth'";
			$resupdatebatch = mysql_query($queryupdatebacth,$connection);
		}
			fcommit();
		}else{
			$PPrdId = "";
			$SPrdId = "";
			$message  = mysql_error(); 
			frollback();
			if ($Module_ExpireDate == 1 || $Module_Sorderproduction == 1) {
			
			$queryupdatebacth = "update jfolio set prod_ref = prod_ref-1 where Journal_Date='$vmonth'";
			$resupdatebatch = mysql_query($queryupdatebacth,$connection);
		}
		}
	
	}
	//echo $vPrdQty; exit;
	//Insert Detail Tables
	if ($SPrdId != "" && $ErrorExists == 0 && $mode == "loadmaterials"){
	
		
		$packdt_query = " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.Group_Code, ifNull(PackDt.PackDt_Quantity,1) as PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_PreCosting,0) as PackDt_PreCosting, 1 as ItemChecked,Packdt.item_stage ".
						" FROM PackDt ".
						" WHERE PackDt.Item_Code = '".$vPrdItemCode."' ".
						" AND (PackDt.Group_Code IS NULL OR PackDt.Group_Code = '') ".
						" AND '".insertMySQLDate($vPrdDate)."' between ifNull(PackDt_FromDate, '".insertMySQLDate($vPrdDate)."') and ifNull(PackDt_ToDate, '".insertMySQLDate($vPrdDate)."') ".
						" UNION ".
						" (SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.Group_Code, ifNull(PackDt.PackDt_Quantity,1) as PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_PreCosting,0) as PackDt_PreCosting, 1 as ItemChecked,Packdt.item_stage ".
						" FROM PackDt ".
						" WHERE PackDt.Item_Code = '".$vPrdItemCode."' ".
						" AND '".insertMySQLDate($vPrdDate)."' between ifNull(PackDt_FromDate, '".insertMySQLDate($vPrdDate)."') and ifNull(PackDt_ToDate, '".insertMySQLDate($vPrdDate)."')) order by item_stage ";
		//echo $packdt_query; exit;					   
		$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[3];
			$vPackDtCostPer  = $packdt_rows[4];
			$vPackDtPreCost  = $packdt_rows[5];
			$vItemChecked    = $packdt_rows[6];
			$SaDtitem_stage  = $packdt_rows[7];
			
			$vPrdDtaddQty   = 0;
			
			$vPrdDtQty       = 0;
			$vPrdDtQtyIdeal  = 0; 
			$vPrdDtWaste     = 0;
			$vPrdDtCost      = 0;
			$vPrdDtCostBase1 = 0;
			$vPrdDtCostBase2 = 0;
			
			$vPrdDtDirectStkDbt = '';
			$vPrdDtDirectStkCrd = '';
			$vPrdDtDirectStkCur = '';
			$vPrdDtWasteDbtAcc  = '';
			$vPrdDtWasteCrdAcc  = '';
			$vPrdDtItemAcc      = '';
			
			
			
			$QtyExistExceeded   = 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), Project_Code, CostCent_Code ".
						 " FROM Items WHERE Item_Code = '".$vItemCode."'";
			$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];
			$ItemProject     = $sub_result[7];
			$ItemCostCent    = $sub_result[8];
			
			if ($Module_ProjectDt == 1) {
				if (empty($ItemProject)) {
					if (empty($vPrdProjectCode))
						$vPrdDtProject = 'Null';
					else
						$vPrdDtProject = "'".$vPrdProjectCode."'";   
				}	
				else {
					$vPrdDtProject = "'".$ItemProject."'";
				}	
			
			} else {
				if (empty($vPrdProjectCode))
					$vPrdDtProject = 'Null';
				else
					$vPrdDtProject = "'".$vPrdProjectCode."'";   
			}
			
			$vPrdCostCentCode = "".$vPrdCostCentCode;
			if ($Module_CostCenterDt == 1) {
				if (empty($ItemCostCent)) {
					if ($vPrdCostCentCode == '')
						$vPrdDtCostCent = 'Null';
					else
						$vPrdDtCostCent = "'".$vPrdCostCentCode."'";   
				}	
				else {
					$vPrdDtCostCent = "'".$ItemCostCent."'";
				}	
			
			} else {
				if ($vPrdCostCentCode == '')
					$vPrdDtCostCent = 'Null';
				else
					$vPrdDtCostCent = "'".$vPrdCostCentCode."'";   
			}
			
				
			//If Item NonStock Is False Then Check On QtyExists For The Item
			if ($ItemNonStock == 0) {
				$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$vPrdWhCode."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];
				
				$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
	//ECHO 	($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd."<BR>";
//ECHO "vPrdQty=".$vPrdQty."<BR>$vPackDtQty=".$vPackDtQty."<BR>ItemQtyToBeProd=".$ItemQtyToBeProd;	
//				ECHO "XXXXX3";
//EXIT;				
				if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
					$QtyExistExceeded = 1;
			}		
			
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
				$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
							 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$sub_result = selectData($connection, $sub_query);
						
				$vTranStpDirectStkDbt = $sub_result[0];
				$vTranStpDirectStkCrd = $sub_result[1];
				$vTranStpDirectStkCur = $sub_result[2];
				$vTranStpWasteDbtAcc  = $sub_result[3];
				$vTranStpWasteCrdAcc  = $sub_result[4];
				$vTranStpWasteDifAcc  = $sub_result[5];
				$vTranStpNonRmVatAcc  = $sub_result[6];
				$vTranStpRmVatAcc     = $sub_result[7];
				$vTranStpNonRmTTCIncAcc  = $sub_result[8];
				$vTranStpRmTTCIncAcc     = $sub_result[9];
				$vTranStpNonRmAcc        = $sub_result[10];
				$vTranStpRmAcc           = $sub_result[11];
						
				$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
				$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
				$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
							
				if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
						
				

				$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;

				if ($DisableIdeal == 0) {
					$vPrdDtQtyIdeal = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
					//$vPrdDtQtyIdeal = ($vPrdQtyIdeal*$vPackDtQty)/$ItemQtyToBeProd; 
					$vPrdDtWaste    = $vPrdDtQtyIdeal - $vPrdDtQty;
				} else {
					$vPrdDtQtyIdeal = 0; 
					$vPrdDtWaste    = 0;
				}	
				if($ShowAdditions == 1)
				$vPrdDtiniQty   = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
				else $vPrdDtiniQty   = 0;		
				//If Item Is Non-Stock And PreCosting True Then Get RawMaterial PreCosting
				if ($ItemNonStock == 1 && $vPackDtPreCost == 1) 
					$vPrdDtCost = Get_RawMaterialCost($vPrdItemCode, $vPrdDate, $vPrdCurr, $connection);
				else
					$vPrdDtCost = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $base1, $base2, $connection);
				//$vPrdDtCost = 400;
				$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
				$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
						
					
							
				fbegin();
				$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
				fcommit();			
					 
				fbegin();	 
				$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
						 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
						 " ProductionDt_CostBase2, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
						 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_Checked, Logged_Code, ".
						 " productiondt_initialQty, productiondt_addition";
				if($SaDtitem_stage!='') $query =$query.",productiondt_stage";
				$query =$query.", productiondt_oldItem) ";
				$query =$query." VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$vPrdCurr."', '".insertMySQLDate($vPrdDate)."', $vPrdDtProject, $vPrdDtCostCent, '".ereg_replace("'", "\'", trim($vPrdWhCode))."', ".
						 "          '".ereg_replace("'", "\'", trim($vItemCode))."',  Null, 0, $vPrdDtQty, $vPrdDtQtyIdeal, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, ".
						 "          Null, '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', '".$vPrdDtDirectStkCrd."', '".$vPrdDtDirectStkCur."', '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', ".
						 "          $vItemChecked, '".$HTTP_SESSION_VARS['useraccount']."', $vPrdDtiniQty,$vPrdDtaddQty ";			
				if($SaDtitem_stage!='') $query =$query.",'$SaDtitem_stage'";		 
				$query =$query.",  '".ereg_replace("'", "\'", trim($vItemCode))."') ";
				//	echo $query."<br>";exit;
				$result=mysql_query($query,$connection);
				//echo $query."<br>";
				//exit;
				if ($result){
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} else {
				//$ErrorExists = 1;
				$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
			}
			
		} // End Loop Of Packdt
				
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;
		}	
	
	}

	// load material by project 
	if ($SPrdId != "" && $ErrorExists == 0 && $mode == "loadmaterialsproj"){
		//and date_format(transfer.Transfer_Date,'%Y-%m-%d') <= '".insertMySQLDate($vPrdDate)."'	
		$query_item = " select '' as item_code, '' as qty, '' as price from dual where 1=0 ";
		if($chk_tr == 1)
			$query_item .= " union select item_code, round(qty, $DecimalBase), price from (
						select item_code, sum(qty) as qty,
						round(MeanCostCur(item_code,now(),if(upper('$vPrdCurr')='$base1', 1,if(upper('$vPrdCurr')='$base2',2, 0)),'$vPrdCurr', if(upper('$vPrdCurr')='$base1', '',if(upper('$vPrdCurr')='$base2','','$vPrdCurr' ))), $DecimalBase) as price
						from (
						select transferdt.item_code as item_code, sum(TransferDt_Quantity)  as qty
						from transferdt
						inner join transfer on transfer.Transfer_Id = transferdt.Transfer_Id
						left join temp_transfer on temp_transfer.Transfer_Id = transfer.Transfer_Id
						where ifnull(temp_transfer.Transfer_Id, -1) = -1 and if('$mat_warehouse' = '', 1=1, TransferDt_WarehouseTo = '$mat_warehouse') 
						and if('$mat_project' = '', 1=1, transferdt.Project_code2 = '$mat_project') 
						group by item_code
						union	
						select transferdt.item_code as item_code, sum(ifnull(TransferDt_Quantity,0)*-1)  as qty
						from transferdt
						inner join transfer on transfer.Transfer_Id = transferdt.Transfer_Id
						left join temp_transfer on temp_transfer.Transfer_Id = transfer.Transfer_Id
						where ifnull(temp_transfer.Transfer_Id, -1) = -1 and if('$mat_warehouse' = '', 1=1, TransferDt_Warehousefrom = '$mat_warehouse') 
						and if('$mat_project' = '', 1=1, transferdt.Project_code1 = '$mat_project') 
						group by item_code
							) as Qitem  group by item_code
					) as Qtr where qty > 0 ";
		
		
		$mat_project = "".$mat_project;	
	//echo $query_item;exit;
		$res_item = mysql_query($query_item, $connection);
		while($rw_item = mysql_fetch_array($res_item)){
			$vItemCode = $rw_item[0];
			$vPrdDtQty = $rw_item[1];
			
			$queryItemProd = "select round(sum(qty), $DecimalBase) from (
							select productiondt.item_code as item_code, sum(ifnull(ProductionDt_Quantity,0)) as qty
							from productiondt
							inner join production on production.production_id = productiondt.production_id
							left join temp_production on temp_production.production_id = production.production_id
							where productiondt.production_id <> $SPrdId and productiondt.item_code='$vItemCode' and ifnull(temp_production.production_id,-1) = -1
							and if('$mat_project' = '', 1=1, production.Project_code = '$mat_project')
							group by productiondt.item_code
							union
							select temp_productiondt.item_code as item_code, sum(ifnull(ProductionDt_Quantity,0)) as qty
							from temp_productiondt
							inner join temp_production on temp_production.production_id = temp_productiondt.production_id
							where temp_productiondt.item_code='$vItemCode' and temp_productiondt.production_id <> $SPrdId
							and if('$mat_project' = '', 1=1, temp_production.Project_code = '$mat_project')
							group by temp_productiondt.item_code
							) as Qitem";
			//echo $queryItemProd;exit;
			$resItemProd = mysql_query($queryItemProd, $connection);
			$rowItemProd = mysql_fetch_row($resItemProd);
			$prodQty = $rowItemProd[0];
			if ($prodQty == '') $prodQty = 0;
			
			$vPrdDtQty = $vPrdDtQty - $prodQty;
			
		if ($vPrdDtQty > 0) {
			
			$vPrdDtCost = $rw_item[2];
			$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
			$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
			
			if ($DisableIdeal == 0) {
				$vPrdDtQtyIdeal = $vPrdDtQty;
				$vPrdDtWaste    = $vPrdDtQtyIdeal - $vPrdDtQty;
			} else {
				$vPrdDtQtyIdeal = 0;
				$vPrdDtWaste    = 0;
			}
			if($ShowAdditions == 1)
				$vPrdDtiniQty   = $vPrdDtQty; 
			else $vPrdDtiniQty   = 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), Project_Code, CostCent_Code, Item_WarehouseCode ".
						 " FROM Items WHERE Item_Code = '".$vItemCode."'";
			$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];
			$ItemProject     = $sub_result[7];
			$ItemCostCent    = $sub_result[8];
			$ItemWarehouse   = $sub_result[9];
	
			$ItemProject = "".$ItemProject;
			$ItemCostCent = "".$ItemCostCent;
		
			if ($Module_ProjectDt == 1) {
				if ($mat_project == '') {
					if($ItemProject == ''){
						if ($vPrdProjectCode == '')
							$vPrdDtProject = 'Null';
						else
							$vPrdDtProject = "'".$vPrdProjectCode."'";   
					} else {
						$vPrdDtProject = "'".$ItemProject."'";   	
					}
				}	
				else {
					$vPrdDtProject = "'".$mat_project."'";
				}	
			
			} else {
				if ($vPrdProjectCode == '')
					$vPrdDtProject = 'Null';
				else
					$vPrdDtProject = "'".$vPrdProjectCode."'";   
			}
			
			if ($Module_CostCenterDt == 1) {
				if ($ItemCostCent == '') {
					if ($vPrdCostCentCode == '')
						$vPrdDtCostCent = 'Null';
					else
						$vPrdDtCostCent = "'".$vPrdCostCentCode."'";   
				}	
				else {
					$vPrdDtCostCent = "'".$ItemCostCent."'";
				}	
			
			} else {
				if ($vPrdCostCentCode == '')
					$vPrdDtCostCent = 'Null';
				else
					$vPrdDtCostCent = "'".$vPrdCostCentCode."'";   
			}
				
			if($mat_warehouse == ''){
				if($ItemWarehouse == ''){
					if ($vPrdWhCode == '')
						$vPrdWhCodedt = 'Null';
					else
						$vPrdWhCodedt = "'".$vPrdWhCode."'";
				} else $vPrdWhCodedt = "'".$ItemWarehouse."'";
				 
			} else $vPrdWhCodedt = "'".$mat_warehouse."'";
		
			$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
						 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'PD' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
							 
			$sub_result = selectData($connection, $sub_query);
					
			$vTranStpDirectStkDbt = $sub_result[0];
			$vTranStpDirectStkCrd = $sub_result[1];
			$vTranStpDirectStkCur = $sub_result[2];
			$vTranStpWasteDbtAcc  = $sub_result[3];
			$vTranStpWasteCrdAcc  = $sub_result[4];
			$vTranStpWasteDifAcc  = $sub_result[5];
			$vTranStpNonRmVatAcc  = $sub_result[6];
			$vTranStpRmVatAcc     = $sub_result[7];
			$vTranStpNonRmTTCIncAcc  = $sub_result[8];
			$vTranStpRmTTCIncAcc     = $sub_result[9];
			$vTranStpNonRmAcc        = $sub_result[10];
			$vTranStpRmAcc           = $sub_result[11];
					
			$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
			$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
			$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
			$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
			$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
						
			if ($ItemVat > 0) {
				if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
			}
			else {
				if ($ItemProd == 1) {
					if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
				}	
				else {
					if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
				}
			}

			$querychk = "select productiondt_id from temp_productiondt
						where production_id = $SPrdId and warehouse_code = $vPrdWhCodedt and item_code = '".$vItemCode."'";
			$reschk = mysql_query($querychk, $connection);
			while($rwchk = mysql_fetch_array($reschk)){
			$pdt_id = $rwchk[0];
				if($pdt_id != ''){
					$querydel = "delete from temp_productiondt where productiondt_id = $pdt_id; ";
					$resdel = mysql_query($querydel,$connection);
				}
			}
			fbegin();
			$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
			fcommit();			
				 
			fbegin();	 
			$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
					 " ProductionDt_CostBase2, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
					 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_Checked, Logged_Code, ".
					 " productiondt_initialQty, productiondt_addition)";
			
			$query =$query." VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$vPrdCurr."', '".insertMySQLDate($vPrdDate)."', $vPrdDtProject, $vPrdDtCostCent, $vPrdWhCodedt, ".
							"          '".$vItemCode."',  Null, 0, $vPrdDtQty, $vPrdDtQtyIdeal, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, ".
							"          Null, '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', '".$vPrdDtDirectStkCrd."', '".$vPrdDtDirectStkCur."', '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', ".
							"          1, '".$_SESSION['useraccount']."', $vPrdDtiniQty, 0 ) ";			
			//	echo $query."<br>";exit;
			$result=mysql_query($query,$connection);
			//echo $query."<br>";
			//exit;
			if ($result){
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		} // end if Qty > 0
	} // end while items
	if ($ErrorExists == 0) {
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;
	}//exit;	
}	
	//Insert Detail Tables
	if ($SPrdId != "" && $SPrdDtId == "" && $ErrorExists == 0 && ($mode == "submitrecord" || $mode == "submitrecord-ajax")){
	
		if (empty($txtPrdDtQty))			$txtPrdDtQty = 0;
		if (empty($txtPrdDtQtyIdeal))	    $txtPrdDtQtyIdeal = 0;
		if (empty($txtPrdDtWaste))		    $txtPrdDtWaste = 0;      		
		if (empty($txtPrdDtCostPrice))	    $txtPrdDtCostPrice = 0;
		
		if (empty($txtPrdDtExpireDate))		$vPrdDtExpireDate = 'Null';
		else  $vPrdDtExpireDate = "'".insertMySQLDate($txtPrdDtExpireDate)."'";  
		
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}

		$txtCostCentCodeDt = "".$txtCostCentCodeDt;	
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}
		
			
			
		$vPrdDtQty       = 0;
		$vPrdDtQtyIdeal  = 0; 
		$vPrdDtQtyIni 	 = 0;
		$vPrdDtWaste     = 0;
		$vPrdDtCost      = 0;
		$vPrdDtCostBase1 = 0;
		$vPrdDtCostBase2 = 0;
			
		$vPrdDtDirectStkDbt = '';
		$vPrdDtDirectStkCrd = '';
		$vPrdDtDirectStkCur = '';
		$vPrdDtWasteDbtAcc  = '';
		$vPrdDtWasteCrdAcc  = '';
		$vPrdDtItemAcc      = '';
			
		$QtyExistExceeded   = 0;
		
		if ($olditem == '') $olditem = $txtItemCode;
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
			
			
		// Case Not Pack Item
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
		if ($ItemPack != 1) {
		
			$vPrdDtQty       = $txtPrdDtQty;
			
			if ($DisableIdeal == 0) {
				//$vPrdDtQtyIdeal  = $txtPrdDtQty; //Ideal Qty Is Equal To Qty On Insert
				$vPrdDtQtyIdeal  = $txtPrdDtQtyIdeal; //Ideal Qty Is Equal To Qty On Insert
				$vPrdDtWaste     = $txtPrdDtWaste;
			} else {
				$vPrdDtQtyIdeal  = 0;
				$vPrdDtWaste     = 0;
			}	
			$vPrdDtQtyIni	= $vPrdDtQtyIdeal;	
			$vPrdDtCost      = $txtPrdDtCostPrice;
			$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
			$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
			
			$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];
			
			
			//If Item NonStock Is False Then Check On QtyExists For The Item
			if ($ItemNonStock == 0) {
				if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "") {
					$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtPrdDtBatchNo."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
				} else {
					$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
				}	
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];
				
				$sub_query1 = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)),0) FROM Temp_ProductionDt ".
							  " Where Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Production_ID = $SPrdId And ProductionDt_ID != ifNull('".$SPrdDtId."',0) ";	
				if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "")
					$sub_query1 = $sub_query1." And	ProductionDt_BatchNo = '".$txtPrdDtBatchNo."' ";			  
				$sub_result1 = selectData($connection, $sub_query1);
				if (empty($sub_result1[0])) $sub_result1[0] = 0;
				
				$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
				
					
				if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
					$QtyExistExceeded = 1;
			}
			
			
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
				$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
							 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$sub_result = selectData($connection, $sub_query);
						
				$vTranStpDirectStkDbt = $sub_result[0];
				$vTranStpDirectStkCrd = $sub_result[1];
				$vTranStpDirectStkCur = $sub_result[2];
				$vTranStpWasteDbtAcc  = $sub_result[3];
				$vTranStpWasteCrdAcc  = $sub_result[4];
				$vTranStpWasteDifAcc  = $sub_result[5];
				$vTranStpNonRmVatAcc  = $sub_result[6];
				$vTranStpRmVatAcc     = $sub_result[7];
				$vTranStpNonRmTTCIncAcc  = $sub_result[8];
				$vTranStpRmTTCIncAcc     = $sub_result[9];
				$vTranStpNonRmAcc        = $sub_result[10];
				$vTranStpRmAcc           = $sub_result[11];
						
				$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
				$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
				$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
							
				if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
						
				
					
							
				fbegin();
				$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
				fcommit();			
					 
				fbegin();	 
				$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
						 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty,productiondt_initialQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
						 " ProductionDt_CostBase2, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
						 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_ExpireDate, ProductionDt_BatchNo, Logged_Code  ";
				if($SaDtitem_stage!='') $query=$query.",productiondt_stage";
				 $query=$query." ,productiondt_oldItem ) ".
						 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$vPrdCurr."', '".insertMySQLDate($vPrdDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
						 "          '".$txtItemCode."', Null, 0, $vPrdDtQty, $vPrdDtQtyIdeal,$vPrdDtQtyIni, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, ".
						 "          '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', '".$vPrdDtDirectStkCrd."', '".$vPrdDtDirectStkCur."', ".
						 "          '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', $vPrdDtExpireDate, '".ereg_replace("'", "\'", trim($txtPrdDtBatchNo))."', '".$_SESSION['useraccount']."' ";			
				if($SaDtitem_stage!='') $query=$query.",'$SaDtitem_stage'";
				$query=$query." ,'".ereg_replace("'", "\'", trim($olditem))."') ";		 
				//echo $query."<br>";exit;
				$result=mysql_query($query,$connection);
				//$message= $query."<br>";
				
				if ($result){
					fcommit();
					
					if ($showNonStockItem == 1) NonStuckItem_Recalculation($SPrdId, $base1, $base2, $connection);
				}else{
					$txtPrdDtId  = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} else {
				//$ErrorExists = 1;
				$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
			}	
				
						
		}	// End Case Not Pack Item
		else {
		
				$QtyExistExceeded   = 0;
				
				$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
								" FROM PackDt ".
								" WHERE Item_Code = '".$txtItemCode."'  ";
									   
				$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
				while($packdt_rows=mysql_fetch_array($packdt_result)){
				
					$vItemCodePacked = $packdt_rows[0];
					$vItemCode 		 = $packdt_rows[1];
					$vPackDtQty 	 = $packdt_rows[2];
					$vPackDtCostPer  = $packdt_rows[3];
					
					$vPrdDtQty       = $txtPrdDtQty;
					
					$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 = '".$vItemCode."'";
					$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];
					
					
					//If Item NonStock Is False Then Check On QtyExists For The Item
					if ($ItemNonStock == 0) {
						if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "") {
							$sub_query  = " Select QtyExistsByBatchNo('".$vItemCode."', '".$lstWarehouse."', '".$txtPrdDtBatchNo."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
						} else {
							$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
						}	
						$sub_result = selectData($connection, $sub_query);
						$vItemQtyExists = 0;
						$vItemQtyExists = $sub_result[0];
						
						$sub_query1 = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)),0) FROM Temp_ProductionDt ".
									  " Where Item_code = '".$vItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Production_ID = $SPrdId And ProductionDt_ID != ifNull('".$SPrdDtId."',0) ";	
						if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "")
							$sub_query1 = $sub_query1." And	ProductionDt_BatchNo = '".$txtPrdDtBatchNo."' ";
						$sub_result1 = selectData($connection, $sub_query1);
						if (empty($sub_result1[0])) $sub_result1[0] = 0;
						
						$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
						$vPrdDtQty      = $vPrdDtQty*$vPackDtQty;
							
						if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0) {
							$QtyExistExceeded = 1;
							Break;
						}	
					}
				}	
				
				if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
					fbegin();	 
					
					$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
									" FROM PackDt ".
									" WHERE Item_Code = '".$txtItemCode."'  ";
										   
					$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
					while($packdt_rows=mysql_fetch_array($packdt_result)){
					
						$vItemCodePacked = $packdt_rows[0];
						$vItemCode 		 = $packdt_rows[1];
						$vPackDtQty 	 = $packdt_rows[2];
						$vPackDtCostPer  = $packdt_rows[3];
						
						
						
						$vPrdDtQty       = 0;
						$vPrdDtQtyIdeal  = 0; 
						$vPrdDtQtyIni  = 0; 
						$vPrdDtWaste     = 0;
						$vPrdDtCost      = 0;
						$vPrdDtCostBase1 = 0;
						$vPrdDtCostBase2 = 0;
						
						$vPrdDtDirectStkDbt = '';
						$vPrdDtDirectStkCrd = '';
						$vPrdDtDirectStkCur = '';
						$vPrdDtWasteDbtAcc  = '';
						$vPrdDtWasteCrdAcc  = '';
						$vPrdDtItemAcc      = '';
						
						$QtyExistExceeded   = 0;
						
						$vPrdDtQty       = $txtPrdDtQty;
						
						if ($DisableIdeal == 0) {
							$vPrdDtQtyIdeal  = $txtPrdDtQty; //Ideal Qty Is Equal To Qty On Insert
							$vPrdDtWaste     = $txtPrdDtWaste;
						} else {
							$vPrdDtQtyIdeal  = 0;
							$vPrdDtWaste     = 0;
						}	
						$vPrdDtCost      = $txtPrdDtCostPrice;
						
						$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 = '".$vItemCode."'";
						$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];
						

						
						$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
									 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
									 " FROM transactionsetup ".
									 " WHERE Journal_type = 'PD' ".
									 " AND Group_code = '".$ItemGroupCode."'  ";
											 
						$sub_result = selectData($connection, $sub_query);
									
						$vTranStpDirectStkDbt = $sub_result[0];
						$vTranStpDirectStkCrd = $sub_result[1];
						$vTranStpDirectStkCur = $sub_result[2];
						$vTranStpWasteDbtAcc  = $sub_result[3];
						$vTranStpWasteCrdAcc  = $sub_result[4];
						$vTranStpWasteDifAcc  = $sub_result[5];
						$vTranStpNonRmVatAcc  = $sub_result[6];
						$vTranStpRmVatAcc     = $sub_result[7];
						$vTranStpNonRmTTCIncAcc  = $sub_result[8];
						$vTranStpRmTTCIncAcc     = $sub_result[9];
						$vTranStpNonRmAcc        = $sub_result[10];
						$vTranStpRmAcc           = $sub_result[11];
									
						$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
						$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
						$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
										
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
							}
						}
									
							

						$vPrdDtQty      = $vPrdDtQty*$vPackDtQty;
						
						if ($DisableIdeal == 0) {
							$vPrdDtQtyIdeal = $vPrdDtQty*$vPackDtQty; 
							$vPrdDtWaste    = $vPrdDtWaste*$vPackDtQty; 
						} else {
							$vPrdDtQtyIdeal = 0; 
							$vPrdDtWaste    = 0; 
						}	
							
						$vPrdDtCost      = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $base1, $base2, $connection);
						//$vPrdDtCost      = 100;
						$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
						$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
								
						$olditem = $vItemCode;
						
						fbegin();
						$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
						fcommit();			
								 
							
						$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
								 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty,productiondt_initialQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
								 " ProductionDt_CostBase2, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
								 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_ExpireDate, ProductionDt_BatchNo, Logged_Code, productiondt_oldItem ) ".
								 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$vPrdCurr."', '".insertMySQLDate($vPrdDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
								 "          '".$vItemCode."',  '".$vItemCodePacked."', $vPackDtQty, $vPrdDtQty, $vPrdDtQtyIdeal,$vPrdDtQtyIni, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, ".
								 "          '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', ".
								 "          '".$vPrdDtDirectStkCrd."', '".$vPrdDtDirectStkCur."', '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', $vPrdDtExpireDate, '".ereg_replace("'", "\'", trim($txtPrdDtBatchNo))."', ".
								 "          '".$_SESSION['useraccount']."', ,'".ereg_replace("'", "\'", trim($olditem))."' ) ";			
						//echo $query."<br>";exit;	
						$result=mysql_query($query,$connection);
						
						
						
					} // End Loop Of Packdt
					
					//echo $ErrorExists; echo $message; exit;
					if ($result){
						fcommit();
						if ($showNonStockItem == 1) NonStuckItem_Recalculation($SPrdId, $base1, $base2, $connection);
					}else{
						$txtPrdDtId = "";
						$message  = mysql_error(); 
						frollback();
					}	
				
				} else {
					$ErrorExists = 1;
					$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
				}
	
			
		} // End CasePack Item
		
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;
		}
		
	} // End Case Insert In Detail Tables

} 


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

	$ErrorExists == 0;
	
	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.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."' and ifnull(project_blocked,0) = 0 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if ($ErrorExists == 0) {
	
		if (empty($txtPrdDtQty))		$txtPrdDtQty = 0;
		if (empty($txtPrdDtQtyIdeal))   $txtPrdDtQtyIdeal = 0;
		if (empty($txtPrdDtWaste))	    $txtPrdDtWaste = 0;      		
		if (empty($txtPrdDtCostPrice))  $txtPrdDtCostPrice = 0;
		
		if (empty($txtPrdDtExpireDate))		$vPrdDtExpireDate = 'Null';
		else  $vPrdDtExpireDate = "'".insertMySQLDate($txtPrdDtExpireDate)."'";  
		
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}
			
				
					
		$vPrdDtQty       = 0;
		$vPrdDtQtyIdeal  = 0; 
		$vPrdDtWaste     = 0;
		$vPrdDtCost      = 0;
		$vPrdDtCostBase1 = 0;
		$vPrdDtCostBase2 = 0;
				
		$vPrdDtDirectStkDbt = '';
		$vPrdDtDirectStkCrd = '';
		$vPrdDtDirectStkCur = '';
		$vPrdDtWasteDbtAcc  = '';
		$vPrdDtWasteCrdAcc  = '';
		$vPrdDtItemAcc      = '';
		
			
		$QtyExistExceeded   = 0;	
			
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPrdCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];		
		
		$vPrdDtQty       = $txtPrdDtQty;
		$vPrdDtWaste     = $txtPrdDtWaste;
		$vPrdDtCost      = $txtPrdDtCostPrice;
				
		$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
		$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
		
		$productiondt_initialQty = $SaDtiniQty;	
		$productiondt_addition = $SaDtaddQty;
		
		if($productiondt_initialQty == '')
			$productiondt_initialQty = $vPrdDtQty;
		if($productiondt_addition == '')
			$productiondt_addition = 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];
				
		
		//If Item NonStock Is False Then Check On QtyExists For The Item
		if ($ItemNonStock == 0) {
			if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "") {
				$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtPrdDtBatchNo."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			} else {
				$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			}	
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
					
			$sub_query1 = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)),0) FROM Temp_ProductionDt ".
						  " Where Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Production_ID = $SPrdId And ProductionDt_ID != ifNull('".$SPrdDtId."',0) ";	
			if ($Module_ExpireDate == 1 && $txtPrdDtBatchNo != "")
				$sub_query1 = $sub_query1." And	ProductionDt_BatchNo = '".$txtPrdDtBatchNo."' ";
			$sub_result1 = selectData($connection, $sub_query1);
			if (empty($sub_result1[0])) $sub_result1[0] = 0;
					
			$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
					
						
			if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
				$QtyExistExceeded = 1;
		}
					
			
			
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {		
				
			fbegin();	
			
			$query = " UPDATE temp_productiondt SET Item_Code = '".ereg_replace("'", "\'", trim($txtItemCode))."', ".
					 " ProductionDt_Quantity = $vPrdDtQty, ProductionDt_Waste = $vPrdDtWaste, ".
					 " ProductionDt_Cost = $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2, ".
					 " ProductionDt_Remark = '".ereg_replace("'", "\'", trim($txtPrdDtRemark))."', ".
					 " ProductionDt_ExpireDate = $vPrdDtExpireDate, Warehouse_code = '$lstWarehouse', ProductionDt_BatchNo = '".ereg_replace("'", "\'", trim($txtPrdDtBatchNo))."' ";
			
			 
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCenter_Code = $CostCentCodeDt ";
			if($ShowAdditions == 1){
				$query = $query.", productiondt_initialQty = $productiondt_initialQty ";
			$query = $query.", productiondt_addition = $productiondt_addition ";
			}
			if($SaDtitem_stage!='') $query=$query.",productiondt_stage='$SaDtitem_stage'";		 
			$query = $query." , productiondt_oldItem = '".ereg_replace("'", "\'", trim($olditem))."'  Where ProductionDt_ID = ".$SPrdDtId;
		
								 
			//echo $query; exit;
			$result=mysql_query($query,$connection);
			if ($result){
				fcommit();
				
				if ($showNonStockItem == 1) NonStuckItem_Recalculation($SPrdId, $base1, $base2, $connection);
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
				$message  = $message . $CalculateResult;

			}else{
				$message  = mysql_error(); 
				frollback();
			}				
				
		} else {
			//$ErrorExists = 1;
			$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
		}
	}	
}
	
//Delete Detail Mode
else if ($mode == "deletedt" && $SPrdDtId != ""){

	$AllowDelete = 1;
	$message  = '';
	

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

		$ErrorExists    = 0;

		
		if (!isset($txtCurr))
		   $txtCurr = $base1;

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];
		
						
		
				
		$querypack = " SELECT ProductionDt.Item_CodePacked, ProductionDt.Item_code ".
					 " FROM Temp_ProductionDt As ProductionDt ".
					 " Where ProductionDt.ProductionDt_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 TempProductionDt For Selected Record
			$query = " DELETE FROM Temp_ProductionDt ".
					 " WHERE ProductionDt_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 ProductionDt_ID, ProductionDt.Item_CodePacked, ProductionDt.Item_code  ".
					   " From Temp_ProductionDt As ProductionDt  ".
					   " Where ProductionDt.Production_ID = ".$SPrdId.
					   " And ProductionDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
					
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vPrdDtId =	$rowsdt[0];
					
						
				// Delete From TempProductionDt For Selected Record
				$query = " DELETE FROM Temp_ProductionDt ".
						 " WHERE ProductionDt_id = ".$vPrdDtId;
						 
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 ){ 
			
			if ($showNonStockItem == 1) NonStuckItem_Recalculation($SPrdId, $base1, $base2, $connection);
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;

		} // End If No Error Exists 
		
	
	} // End If No Constraints Found On Delete
	
	
}

else if($mode == "editqty" && $SPrdId != ''){

	$sub_query = " Select Production.Currency_Code, Date_Format(Production_Date,'%d/%m/%Y') As Production_Date, ".
				 " Production.Item_Code, Production.Warehouse_Code ".
                 " From Temp_Production As Production  ".
				 " Where Production.Production_ID = '".$SPrdId."' ";
	$sub_result = selectData($connection, $sub_query);
	$vPrdCurr      = $sub_result[0];
	$vPrdDate      = $sub_result[1];
	$vPrdItemCode  = $sub_result[2];
	$vPrdWhCode    = $sub_result[3];
	$vPrdQty       = $QItemQty;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];	
	
	fbegin();
		
	$sub_query = " UPDATE Temp_Production SET  ".
				 " Production_Quantity = $vPrdQty ".
				 " Where Production_ID = '".$SPrdId."'";
								 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection);
	
	$packdt_query = " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, ifNull(PackDt.PackDt_Quantity,1), PackDt.PackDt_CostPercentage ".
					" , ifNull(Item_QtyToBeProduced, 1) ".
					" FROM PackDt ".
					" INNER JOIN Temp_ProductionDt on Temp_ProductionDt.Item_Code = PackDt.Item_CodePackDt ".
					" INNER JOIN items on items.Item_Code = PackDt.Item_Code ".
					" WHERE PackDt.Item_Code = '".$vPrdItemCode."'  ";
							   
	$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];
		$ItemQtyToBeProd = $packdt_rows[4];
		
		$vPrdDtQty       = 0;
		$vPrdDtQtyIdeal  = 0; 
		$vPrdDtWaste     = 0;
		$vPrdDtCost      = 0;
		$vPrdDtCostBase1 = 0;
		$vPrdDtCostBase2 = 0;
		
		$QtyExistExceeded   = 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 = '".$vItemCode."'";
		$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];
		//nabil $ItemQtyToBeProd = $sub_result[7];
   		//$ItemQtyToBeProd =1;
//ECHO "XXXXX4";
//EXIT;		

		//If Item NonStock Is False Then Check On QtyExists For The Item
		if ($ItemNonStock == 0) {
			$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$vPrdWhCode."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
				
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
				
					
			if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
				$QtyExistExceeded = 1;
		}		
			
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
				
			if ($DisableIdeal == 0) {
				$vPrdDtQtyIdeal = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
				$vPrdDtWaste    = $vPrdDtQtyIdeal - $vPrdDtQty;
			} else {
				$vPrdDtQtyIdeal = 0; 
				$vPrdDtWaste    = 0;
			}	
						
			$vPrdDtCost = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $base1, $base2, $connection);
			//$vPrdDtCost = 200;	
			$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
			$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
						
				
			fbegin();	 
			$query = " UPDATE temp_productiondt SET ".
			         " ProductionDt_Quantity = $vPrdDtQty, ProductionDt_IdealQty = $vPrdDtQtyIdeal, ".
					 " ProductionDt_Waste = $vPrdDtWaste, ProductionDt_Cost =  $vPrdDtCost, ".
					 " ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2 ".
					 " WHERE Production_ID = '".$SPrdId."' ".
					 " AND Item_code = '".$vItemCode."'";
				
			$result=mysql_query($query,$connection);
			//echo $query."<br>";
				
			if ($result){
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		} else {
			//$ErrorExists = 1;
			$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
		}
			
	} // End Loop Of Packdt
		
	if ($ErrorExists == 0){
			
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;
						
	}
}

//Load Sales Order

else if($mainmode == "loadsorder" && $SPrdId != ''){
if (!isset($vPrdCurr))
	   $vPrdCurr = $base1;
	   
			//echo $SPrdId; exit;
	$vPrdCostCentCode = "".$vPrdCostCentCode;		
	if ($vPrdCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vPrdCostCentCode."'";
			
	if (empty($vPrdProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vPrdProjectCode."'";   

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	$ErrorExists = 0;
	if ($vPrdCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($vPrdProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$vPrdProjectCode."' and ifnull(project_blocked,0) = 0 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
			
	if ($ErrorExists == 1) 
		$message = 'Load not allowed. Please check for Project/Costcenter Code.';
		
	$message = '';	
		
	if ($SPrdId != '' && $ErrorExists == 0) {
		fbegin();	
		$vPrdId = get_nextsequence('Production_id','',$connection);	
		fcommit();
		$queryQty = " select ifNull(SorderDt.SorderDt_Quantity,0) - (ifNull(Q1.QuantityDelivered,0) + ifNull(Q2.QuantityDeliveredTemp,0)) ".
					" from sorderdt ".
					 " Left Join ( Select production.RelatedDt_ID, production.Item_code, Sum(ifNull(production.Production_quantity,0)) As QuantityDelivered ".
					   "             From production ".
					   "             Where (production.RelatedDt_ID != '' or production.RelatedDt_ID Is Not Null)  ".
					   "             Group By production.RelatedDt_ID, production.Item_code ".
					   "            ) Q1 on Q1.Item_code = SorderDt.Item_code  and Q1.RelatedDt_ID = SorderDt.SorderDt_id ".
					   " Left Join ( Select Temp_production.RelatedDt_ID, Temp_production.Item_code, Sum(ifNull(Temp_production.Production_quantity,0)) As QuantityDeliveredTemp ".
					   "             From Temp_production ".
					   "             Where (Temp_production.RelatedDt_ID != '' or Temp_production.RelatedDt_ID Is Not Null) ".
					   "             Group By Temp_production.RelatedDt_ID, Temp_production.Item_code ".
					   "            ) Q2 on Q2.Item_code = SorderDt.Item_code  and Q2.RelatedDt_ID = SorderDt.SorderDt_id ".
					   " where SorderDt_id = $SPrdId";
		$resultQty = mysql_query($queryQty, $connection);
		$rowQty = mysql_fetch_row($resultQty);
		$remainingQty = $rowQty[0];
		if ($Module_ExpireDate == 1 || $Module_Sorderproduction == 1) {
			$vyear  = date('y');
			$vmonth = date('n');
			$queryseq = "select (prod_ref+1) from jfolio where Journal_Date = '$vmonth'";
			$resseq = mysql_query($queryseq,$connection);
			$rowseq = mysql_fetch_row($resseq);
			$seqno = $rowseq[0]; 
			if(strlen($seqno) == 1) $seqno = '00'.$seqno;
			else if(strlen($seqno) == 2) $seqno = '0'.$seqno;
			//$vbacthno = $vmonth."".$seqno."/".$vyear;
			$queryupdatebacth = "update jfolio set prod_ref = prod_ref+1 where Journal_Date='$vmonth'";
			$resupdatebatch = mysql_query($queryupdatebacth,$connection);
		} 
		//else $vbacthno = '0';
		fbegin();
		$query = "insert into temp_production (Production_id, Production_Reference, Production_Date, Item_Code, Warehouse_Code, Production_quantity,Currency_Code, Project_Code, Costcenter_Code, ".
				" Item_UnitCoef, Item_Unit2Qty, User_account, RelatedDt_Id, Client_Code, Production_idealqty, Quantity_Ill, Production_BatchNo, Production_DirectStkCur) ".
				" select $vPrdId, null, now(), Item_code, Warehouse_code, $remainingQty, CURRENCY_cODE, Project_Code, CostCent_Code, ".
				" Item_UnitCoef, Item_Unit2Qty, '".$_SESSION['useraccount']."', $SPrdId, CLIENT_CODE, $remainingQty, $remainingQty, '$vPrdBatchNo', CURRENCY_cODE".
				" from sorderdt where SorderDt_id = $SPrdId";
		
		$result = mysql_query($query,$connection);
		//echo $query; exit;	
        $query_item_group_code  = "select item_code as ItemCodeX, Warehouse_Code as WareHouseCodeX, CURRENCY_cODE as CurrencyCodeX from sorderdt where SorderDt_id = $SPrdId";
		//echo $query_item_group_code; exit;
		$result_item_group_code = mysql_query($query_item_group_code, $connection);
		$row_item_group_code    = mysql_fetch_array($result_item_group_code);
		extract($row_item_group_code);
		
		$query_group_code  = "select group_code as ItemGroupCode from items where item_code = '".$ItemCodeX."'";
		$result_group_code = mysql_query($query_group_code, $connection); 
		$row_group_code    = mysql_fetch_array($result_group_code);
		extract($row_group_code);
		
		$query_item_non_stock  = "select Item_NonStock as ItemNonStock from items where item_code = '".$ItemCodeX."'";
		$result_item_non_stock = mysql_query($query_item_non_stock, $connection);
		$row_item_non_stock    = mysql_fetch_array($result_item_non_stock);
		extract($row_item_non_stock);
		
		$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
		//echo $sub_query; exit;			 
		$sub_result = selectData($connection, $sub_query);
				
		$vTranStpDirectStkDbt = $sub_result[0];
		$vTranStpDirectStkCrd = $sub_result[1];
		$vTranStpDirectStkCur = $sub_result[2];
		$vTranStpWasteDbtAcc  = $sub_result[3];
		$vTranStpWasteCrdAcc  = $sub_result[4];
		$vTranStpWasteDifAcc  = $sub_result[5];
		$vTranStpNonRmVatAcc  = $sub_result[6];
		$vTranStpRmVatAcc     = $sub_result[7];
		$vTranStpNonRmTTCIncAcc  = $sub_result[8];
		$vTranStpRmTTCIncAcc     = $sub_result[9];
		$vTranStpNonRmAcc        = $sub_result[10];
		$vTranStpRmAcc           = $sub_result[11];
				
		$vPrdDirectStkDbt = $vTranStpDirectStkDbt;
		$vPrdDirectStkCrd = $vTranStpDirectStkCrd;
		$vPrdDirectStkCur = $vTranStpDirectStkCur;
		$vPrdWasteDbtAcc  = $vTranStpWasteDbtAcc;
		$vPrdWasteCrdAcc  = $vTranStpWasteCrdAcc;
		$vPrdWasteDifAcc  = $vTranStpWasteDifAcc;
		
		$query_update_temp_production  = "update temp_production set Production_DirectStkDbt = '".$vPrdDirectStkDbt."',
		                                                             Production_DirectStkCrd = '".$vPrdDirectStkCrd."'
										  where production_id = $vPrdId";
		
		$result_update_temp_production = mysql_query($query_update_temp_production, $connection);
		
		if ($result){
			$SPrdId = $vPrdId;
			fcommit();
		}else{
			$SPrdId = "";
			$vPrdId = "";
			$message  = mysql_error(); 
			frollback();
		}
		if($SPrdId != ''){
			//echo $SPrdId; exit;
			$queryitem = "select item_code from temp_production where production_id = $vPrdId";
			$resultitem = mysql_query($queryitem,$connection);
			$rwitem = mysql_fetch_row($resultitem);
			$itemcode = $rwitem[0];
			$vPrdDate     = date("d/m/Y");
			$vPrdItemCode = $ItemCodeX;
			$vPrdWhCode   = $WareHouseCodeX;
			$vPrdCurr     = $CurrencyCodeX;
			$querydt = " select Item_CodePackDt,packdt.Warehouse_Code, PackDt_Quantity,packdt.CURRENCY_CODE,BARCODE, Packdt_cost,
				ifNull(B.Item_QtyToBeProduced, 1), ifNull(PackDt_PreCosting,0) as PackDt_PreCosting
			    from packdt
			    left join items A on A.item_code=packdt.Item_CodePackDt
				left join items B on B.item_code=packdt.Item_Code
			    left join warehouse on warehouse.warehouse_code=packdt.Warehouse_Code
			    where packdt.Item_Code='$itemcode'"; 
					//echo $querydt; exit;
			$resultdt = mysql_query($querydt,$connection);
			while($rwdt = mysql_fetch_row($resultdt)){
			    $vPackDtPreCost = $rwdt[7];
				$vItem_CodePackDt = $rwdt[0];
				$QtyExistExceeded   = 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 = '".$rwdt[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];
				
				
				$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
				//echo $sub_query; exit;			 
				$sub_result = selectData($connection, $sub_query);
		
				$vTranStpDirectStkDbt = $sub_result[0];
		$vTranStpDirectStkCrd = $sub_result[1];
		$vTranStpDirectStkCur = $sub_result[2];
		$vTranStpWasteDbtAcc  = $sub_result[3];
		$vTranStpWasteCrdAcc  = $sub_result[4];
		$vTranStpWasteDifAcc  = $sub_result[5];
		$vTranStpNonRmVatAcc  = $sub_result[6];
		$vTranStpRmVatAcc     = $sub_result[7];
		$vTranStpNonRmTTCIncAcc  = $sub_result[8];
		$vTranStpRmTTCIncAcc     = $sub_result[9];
		$vTranStpNonRmAcc        = $sub_result[10];
		$vTranStpRmAcc           = $sub_result[11];
				
		$vPrdDirectStkDbt = $vTranStpDirectStkDbt;
		$vPrdDirectStkCrd = $vTranStpDirectStkCrd;
		$vPrdDirectStkCur = $vTranStpDirectStkCur;
		$vPrdWasteDbtAcc  = $vTranStpWasteDbtAcc;
		$vPrdWasteCrdAcc  = $vTranStpWasteCrdAcc;
		$vPrdWasteDifAcc  = $vTranStpWasteDifAcc;
		
		if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
		
				$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);
                }
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	            $result = selectData($connection, $query);
	            $rate_dt = $result[0];
	
	            $query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	            $result = selectData($connection, $query);
	            $rate_dt1 = $result[0];
	
	            $query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	            $result = selectData($connection, $query);
	            $rate_dt2 = $result[0];
				
			    /*
				echo $vPrdItemCode."<br>";
				echo $vPrdDate."<br>";
				echo $vPrdCurr."<br>";
				echo $connection."<br><br>";
				
				echo $vItem_CodePackDt."<br>";
				echo $ItemCurr."<br>";
				echo $ItemCostMethod."<br>";
				echo $base1."<br>";
				echo $base2."<br>";
				exit;
				*/
			
				
			    if ($ItemNonStock == 1 && $vPackDtPreCost == 1) {
					//echo "test1";
					$vPrdDtCost = Get_RawMaterialCost($vPrdItemCode, $vPrdDate, $vPrdCurr, $connection);
				}
				else {
					//echo "test2<br>";
					$vPrdDtCost = Get_CostPrice($vItem_CodePackDt, $vPrdCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $base1, $base2, $connection);
				}
				//echo $vPrdCurr."<br>";
				//echo $vPrdDtCost;exit;
			//exit;
			$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
			$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;
			//echo "xxxx".$ItemNonStock	;
			$vPrdDtQty      = ($rwdt[2])/$rwdt[6];
			if ($ItemNonStock == 0) {
			$sub_query  = " Select QtyExistsWSorder('".$rwdt[0]."', '".$rwdt[1]."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
				
			$vPrdDtQty      = ($remainingQty*$rwdt[2])/$rwdt[6];
			//echo "xxxx".$remainingQty;
			//echo 	$remainingQty;
			if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
				$QtyExistExceeded = 1;
			}
			
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
			if ($DisableIdeal == 0) {
				$vPrdDtQtyIdeal = ($remainingQty*$rwdt[2])/$rwdt[6];
			} else {
				$vPrdDtQtyIdeal = 0; 
				
			}	
			if (empty($Actual_Zero) || !isset($Actual_Zero))
					$Actual_Zero=0;
			
			if($Actual_Zero == 1) $actualqty = 0;
			else if($Actual_Zero == 0) $actualqty = $vPrdDtQty;
			//	echo "x".$vPrdDtQty;
			fbegin();	
			$vPrddtId = get_nextsequence('ProductionDt_id','',$connection);	
			fcommit();
			fbegin();
			$queryins = " insert into temp_productiondt (ProductionDt_id,Production_id,Production_Date,Item_Code,Warehouse_Code,ProductionDt_Quantity,Currency_Code,Productiondt_idealqty, ProductionDt_cost, ProductionDt_CostBase1, ProductionDt_CostBase2, Productiondt_ItemAccount,ProductionDt_DirectStkCur, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd) ".
						" values ".
						" ($vPrddtId,$SPrdId,now(), '$rwdt[0]','$rwdt[1]',$actualqty, '$vPrdCurr', $vPrdDtQtyIdeal, '".$vPrdDtCost."', '".$vPrdDtCostBase1."', '".$vPrdDtCostBase2."', '".$vPrdDtItemAcc."', '".$vPrdCurr."', '".$vPrdDirectStkDbt."', '".$vPrdDirectStkCrd."') ";
					//	echo $queryins;exit;
			$resultins = mysql_query($queryins, $connection);
			if ($resultins){
			$sum_temp_productiondt    = "select sum(ProductionDt_cost) as TotalProduction, sum(ProductionDt_CostBase1) as TotalProduction1, sum(ProductionDt_CostBase2) as TotalProduction2
			                             from temp_productiondt
									     where production_id = '".$SPrdId."'";
			$result_temp_productiondt = mysql_query($sum_temp_productiondt, $connection);
			$row_temp_productiondt    = mysql_fetch_array($result_temp_productiondt);
			extract($row_temp_productiondt);
			
			//echo $TotalProduction."<br>";
			//echo $TotalProduction1."<br>";
			//echo $TotalProduction2."<br>";exit;
			
            $update_total_production = "update temp_production set Production_Total = '".$TotalProduction."',
			                                                  Production_TotalBase1 = '".$TotalProduction1."',
															  Production_TotalBase2 = '".$TotalProduction2."'
															  where production_id = '".$SPrdId."'";
			
			//echo $update_total_production; exit;
			$result_total_production = mysql_query($update_total_production, $connection);
			
			fcommit();
			}else{
			$vPrddtId = "";
			$message  = mysql_error(); 
			frollback();
			}
			}
		} //echo $querydt;exit;
			
		}
		//echo $ErrorExists; exit;

	}
}	
//Load Data From PreProduction 
else if($mode == "" && $mainmode == "updateinfo" && $SPrdId != ""){
	if($txtpackingdt_amountStrd == '') $txtpackingdt_amountStrd = 0;
	if($txtpackingdt_nbrStrd == '') $txtpackingdt_nbrStrd = 0;
	if($txtpackingdt_amountAct == '') $txtpackingdt_amountAct = 0;
	if($txtpackingdt_nbrAct == '') $txtpackingdt_nbrAct = 0;
	if($txtpackingdt_amountAct2 == '') $txtpackingdt_amountAct2 = 0;
	if($txtpackingdt_nbrAct2 == '') $txtpackingdt_nbrAct2 = 0;
	if($txttotalSum == '') $txttotalSum = 0;
	
	if($txtprodshadeact != '')		$txtprodshadeact = "'".$txtprodshadeact."'";
	else $txtprodshadeact = "NULL";
	
	if($txtprodstrengthact != '')		$txtprodstrengthact = "'".$txtprodstrengthact."'";
	else $txtprodstrengthact = "NULL";
	
	if($txtproduction_prevBatchno != '') $txtproduction_prevBatchno = "'".$txtproduction_prevBatchno."'";
	else $txtproduction_prevBatchno = "NULL";
	
	if($txtproduction_referenceStd != '')		$txtproduction_referenceStd = "'".$txtproduction_referenceStd."'";
	else $txtproduction_referenceStd = "NULL";
	
	if($txtproduction_viscosityDirect != '')		$txtproduction_viscosityDirect = "'".$txtproduction_viscosityDirect."'";
	else $txtproduction_viscosityDirect = "NULL";
	
	if($txtproduction_viscosityReduced != '')		$txtproduction_viscosityReduced = "'".$txtproduction_viscosityReduced."'";
	else $txtproduction_viscosityReduced = "NULL";

    if($txtproduction_gloss != '')		$txtproduction_gloss = "'".$txtproduction_gloss."'";
	else $txtproduction_gloss = "NULL";
	
	if($txtproduction_Adhesion != '')		$txtproduction_Adhesion = "'".$txtproduction_Adhesion."'";
	else $txtproduction_Adhesion = "NULL";

	if($txtproduction_Alkali != '')		$txtproduction_Alkali = "'".$txtproduction_Alkali."'";
	else $txtproduction_Alkali = "NULL";
	
	if($txtproduction_scuff != '')		$txtproduction_scuff = "'".$txtproduction_scuff."'";
	else $txtproduction_scuff = "NULL";
	
	$queryupdate = "update temp_production set  ";
		$queryupdate = $queryupdate."  packingdt_amountStrd='$txtpackingdt_amountStrd' ";
		$queryupdate = $queryupdate." , packingdt_nbrStrd='$txtpackingdt_nbrStrd' ";
	
		$queryupdate = $queryupdate." , packingdt_amountAct='$txtpackingdt_amountAct' ";
		$queryupdate = $queryupdate." , packingdt_nbrAct='$txtpackingdt_nbrAct' ";
		
		$queryupdate = $queryupdate." , packingdt_amountAct2='$txtpackingdt_amountAct2' ";
		$queryupdate = $queryupdate." , packingdt_nbrAct2='$txtpackingdt_nbrAct2' "
									." , production_shadeAct=$txtprodshadeact "
									." , production_strengthAct=$txtprodstrengthact "	
									." , production_prevBatchno=$txtproduction_prevBatchno "
									." , production_referenceStd=$txtproduction_referenceStd "
									." , production_viscosityDirect=$txtproduction_viscosityDirect "
									." , production_viscosityReduced=$txtproduction_viscosityReduced "
									." , production_gloss=$txtproduction_gloss "
									." , production_Adhesion=$txtproduction_Adhesion "
									." , production_Alkali=$txtproduction_Alkali "
									." , production_scuff=$txtproduction_scuff "
									." , Quantity_Ill='$txttotalSum' ";	
	
		
	$queryupdate = $queryupdate." where Production_id=$SPrdId ";
	//echo $queryupdate; exit;
	$resupdate = mysql_query($queryupdate, $connection);
	
	$queryUphead = "update temp_production set  ";
	
	if($newbatchno != '') $queryUphead = $queryUphead." Production_BatchNo = '$newbatchno' ";
	else $queryUphead = $queryUphead." Production_BatchNo = NULL ";
	if($newRemark != '') $queryUphead = $queryUphead.",Production_Remark = '$newRemark' ";
	$queryUphead = $queryUphead."  where Production_id = $SPrdId ".
	$resUpHead = mysql_query($queryUphead, $connection);
	//echo $queryUphead;exit;
	header ("Location: ./Form_Production_info.php?txtPrdId=".$SPrdId."&closeWin=1");
	exit;
}
else if ($mode == "" && $mainmode == "loadpreprod" && $SSelectdId != ""){

	$ErrorExists = 0;
	$InsertAllow = 1;
	
	
	$sub_query = " Select Production_Id, Item_Code, Warehouse_Code, ifNull(Production_quantity,0), ".
				 " Project_Code, Costcenter_Code, Currency_Code, Production_Remark, ifNull(Production_idealqty,0) ".
				 " From PreProduction ".
				 " Where Production_Id = '".$SSelectdId."'";
	$sub_result = selectData($connection, $sub_query);	
	$vPrePrdID	  = $sub_result[0];
	$vPrdItemCode = $sub_result[1];
		
	if ($vPrePrdID != "" && $SPrdId == "" ) {
		//Insert Master Table
		
		$vPrdDate         = displayToday();
		$vPrdExpireDate   = '';
		$vPrdBatchNo      = '';
		$vPrdWhCode		  = $sub_result[2];
		$vPrdQty		  = $sub_result[3];
		$vProjectCode	  = $sub_result[4];
		$vCostCentCode	  = $sub_result[5];
		$vPrdCurr         = $sub_result[6];
		$vPrdRemark       = $sub_result[7];
		$vPrdQtyIdeal	  = $sub_result[8];
		
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];
	
	
	
		$vPrdDirectStkDbt = '';
		$vPrdDirectStkCrd = '';
		$vPrdDirectStkCur = '';
		$vPrdWasteDbtAcc  = '';
		$vPrdWasteCrdAcc  = '';
		$vPrdWasteDifAcc  = '';
		$vPrdItemAcc      = '';
			
		fbegin();	
		$vPrdId = get_nextsequence('Production_id','',$connection);
		fcommit();
		
		$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_QtyToBeProduced, 1) ".
			         " FROM Items WHERE Item_Code = '".$vPrdItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		$ItemVat 	     = $sub_result[0];
		$ItemGroupCode   = $sub_result[1];
		$ItemProd        = $sub_result[2];
		$ItemTTCInc      = $sub_result[3];
		$ItemQtyToBeProd = $sub_result[4];
	//ECHO "XXXXX5";
//EXIT;
	
				
				
		$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
		
		$sub_result = selectData($connection, $sub_query);
				
		$vTranStpDirectStkDbt = $sub_result[0];
		$vTranStpDirectStkCrd = $sub_result[1];
		$vTranStpDirectStkCur = $sub_result[2];
		$vTranStpWasteDbtAcc  = $sub_result[3];
		$vTranStpWasteCrdAcc  = $sub_result[4];
		$vTranStpWasteDifAcc  = $sub_result[5];
		$vTranStpNonRmVatAcc  = $sub_result[6];
		$vTranStpRmVatAcc     = $sub_result[7];
		$vTranStpNonRmTTCIncAcc  = $sub_result[8];
		$vTranStpRmTTCIncAcc     = $sub_result[9];
		$vTranStpNonRmAcc        = $sub_result[10];
		$vTranStpRmAcc           = $sub_result[11];
				
		$vPrdDirectStkDbt = $vTranStpDirectStkDbt;
		$vPrdDirectStkCrd = $vTranStpDirectStkCrd;
		$vPrdDirectStkCur = $vTranStpDirectStkCur;
		$vPrdWasteDbtAcc  = $vTranStpWasteDbtAcc;
		$vPrdWasteCrdAcc  = $vTranStpWasteCrdAcc;
		$vPrdWasteDifAcc  = $vTranStpWasteDifAcc;
					
		if ($ItemVat > 0) {
			if ($ItemProd == 1)	$vPrdItemAcc = $vTranStpNonRmVatAcc; else $vPrdItemAcc = $vTranStpRmVatAcc;
		}
		else {
			if ($ItemProd == 1) {
				if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdItemAcc = $vTranStpNonRmAcc;
			}	
			else {
				if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpRmTTCIncAcc; else $vPrdItemAcc = $vTranStpRmAcc;
			}
		}	
			
		
		fbegin();
		$query = " INSERT INTO temp_production (Production_ID, Production_Reference, Production_Date, Production_ExpireDate, Production_Remark, Currency_Code, Project_Code, Costcenter_code, ".
				 " Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_Total, Production_TotalBase1, Production_TotalBase2, ".
				 " Production_IdealTotal, Production_idealqty, Journal_Id, Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, Production_DirectStkDbt, ".
				 " Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff, PreProduction_id, User_Account, Logged_Code ) ".
				 " VALUES ( ".$vPrdId.", Null, '".insertMySQLDate($vPrdDate)."', Null, '".ereg_replace("'", "\'", trim($vPrdRemark))."', '".$vPrdCurr."', ".
				 "          '".$vProjectCode."', '".$vCostCentCode."', 'P', '".ereg_replace("'", "\'", trim($vPrdItemCode))."', '".ereg_replace("'", "\'", trim($vPrdWhCode))."', $vPrdQty, ".
				 "          0, 0, 0, 0, $vPrdQtyIdeal, Null, $FI_BelongsToGrp, 0, 0, 0, '".$vPrdItemAcc."', '".$vPrdDirectStkDbt."', '".$vPrdDirectStkCrd."', '".$vPrdDirectStkCur."', ".
				 "          '".$vPrdWasteDbtAcc."', '".$vPrdWasteCrdAcc."', '".$vPrdWasteDifAcc."', ".$vPrePrdID.", '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPrdId = $vPrdId;
			fcommit();
		}else{
			$SPrdId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SPrdId != "" && $ErrorExists == 0 && $SSelectdId != ""){
	
	
		//Load Items From PreProductionDt 
		$sub_query1 = " Select PreProductionDt.ProductionDt_Id, PreProductionDt.Item_Code, PreProductionDt.Warehouse_Code, ".
					  " ifNull(ProductionDt_Quantity,1), ifNull(Productiondt_idealqty,0), Item_Barcode, Item_UnitCoef, Item_Unit2Qty, ".
					  " PreProductionDt.Project_Code, PreProductionDt.CostCenter_Code ".
					  " From PreProductionDt ".
					  " Where PreProductionDt.Production_Id = '".$SSelectdId."' ";
				 
		$sub_result1=mysql_query($sub_query1, $connection) or die(mysql_error());
		while($sub_rows1=mysql_fetch_array($sub_result1)){			   
				
			$vItemCode       = $sub_rows1[1];
			$vPrdDtWhCode    = $sub_rows1[2];
			$vPrdDtQty       = $sub_rows1[3];
			if ($DisableIdeal == 0) {
				$vPrdDtQtyIdeal  = $vPrdDtQty; //Ideal Qty Is Equal To Qty On Insert
				$vPrdDtWaste     = 0;
			} else {
				$vPrdDtQtyIdeal  = 0;
				$vPrdDtWaste     = 0;
			}
			
			$vItemBarcode    = $sub_rows1[5];
			$vItemUnitCoef   = $sub_rows1[6];
			$vItemUnit2Qty   = $sub_rows1[7];
			
			$vProjectCodeDt	  = $sub_rows1[8];
			$vCostCentCodeDt  = $sub_rows1[9];
			
			$vPrdDtRemark    = '';
			$vPrdDtOption    = 1;
			
			$vPrdDtCost      = 0;
			$vPrdDtCostBase1 = 0;
			$vPrdDtCostBase2 = 0;
			
			$vPrdDtDirectStkDbt = '';
			$vPrdDtDirectStkCrd = '';
			$vPrdDtDirectStkCur = '';
			$vPrdDtWasteDbtAcc  = '';
			$vPrdDtWasteCrdAcc  = '';
			$vPrdDtItemAcc      = '';
			
			$QtyExistExceeded   = 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 = '".$vItemCode."'";
			$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];
			
			
			//If Item NonStock Is False Then Check On QtyExists For The Item
			/*if ($ItemNonStock == 0) {
				$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$vPrdDtWhCode."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];
				
				$sub_query = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)),0) FROM Temp_PreProductionDt ".
							 " Where Item_code = '".$vItemCode."'  And  Warehouse_code = '".$vPrdDtWhCode."' And Production_ID = '".$SPrdId."' ";	
				$sub_result = selectData($connection, $sub_query);
				if (empty($sub_result[0])) $sub_result[0] = 0;
				
				$vItemQtyExists = $vItemQtyExists - $sub_result[0];
				
					
				if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
					$QtyExistExceeded = 1;
			}*/
			
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
				$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
							 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
									 
				$sub_result = selectData($connection, $sub_query);
							
				$vTranStpDirectStkDbt = $sub_result[0];
				$vTranStpDirectStkCrd = $sub_result[1];
				$vTranStpDirectStkCur = $sub_result[2];
				$vTranStpWasteDbtAcc  = $sub_result[3];
				$vTranStpWasteCrdAcc  = $sub_result[4];
				$vTranStpWasteDifAcc  = $sub_result[5];
				$vTranStpNonRmVatAcc  = $sub_result[6];
				$vTranStpRmVatAcc     = $sub_result[7];
				$vTranStpNonRmTTCIncAcc  = $sub_result[8];
				$vTranStpRmTTCIncAcc     = $sub_result[9];
				$vTranStpNonRmAcc        = $sub_result[10];
				$vTranStpRmAcc           = $sub_result[11];
							
				$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
				$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
				$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
								
				if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
				
				$vPrdDtCost      = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $base1, $base2, $connection);
				//$vPrdDtCost      = 300;
				$vPrdDtCostBase1 = ($vPrdDtCost*$rate_dt)/$rate_dt1;
				$vPrdDtCostBase2 = ($vPrdDtCost*$rate_dt)/$rate_dt2;

				
				fbegin();
				$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
				fcommit();			
					 
				fbegin();	 
				$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
						 " Item_code, Item_CodePacked, Item_qtyPacked,productiondt_initialQty,productiondt_addition, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
						 " ProductionDt_CostBase2, ProductionDt_ExpireDate, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
						 " ProductionDt_WasteDebit, ProductionDt_WasteCredit, Logged_Code, ProductionDt_DirectStkCur,productiondt_oldItem) ".
						 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$vPrdCurr."', '".insertMySQLDate($vPrdDate)."', '".$vProjectCodeDt."', '".$vCostCentCodeDt."', '".ereg_replace("'", "\'", trim($vPrdWhCode))."', ".
						 "          '".$vItemCode."',  Null, 0,$vPrdDtQty,0, $vPrdDtQty, $vPrdDtQtyIdeal, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, Null, ".
						 "          Null, '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', '".$vPrdDtDirectStkCrd."', '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', ".
						 "          '".$_SESSION['useraccount']."', '".$vPrdCurr."','".$vItemCode."' ) ";
				//echo $query."<br>";	exit;	 
				$result=mysql_query($query,$connection);
				
					
				if ($result){
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} else {
				//$ErrorExists = 1;
				$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
			}
		} // End Loop Of PreProductionDt
		
		
		
		
				
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;
			
		}	
	
	}
	
}
//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SPrdId != ''){

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Production Is Posted
	$sub_query = "SELECT ifNull(Production_Posted,0) As ProductionPosted FROM Production WHERE Production_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 && ($Module_NegativeQuantity == 0 || $Login_negativeQty == 0)) {
		//Check Production Item For Quantity Exists If Negative
		$sub_query = " Select Count(Item_Code) ".
					 " From ( ".
					 " Select Item_Code, WareHouse_Code, Production_Quantity, ".
					 " QtyExistsWSorder(Item_Code, WareHouse_Code, Now(), Production_Id, 'PD', '', '') QtyExists ".
					 " From Production ".
					 " Where Production.Production_ID = '".$SPrdId."' ".
					 " ) Q1 Where QtyExists < 0 ";
 
		$sub_result   = selectData($connection, $sub_query);
		$ItemQtyExists = $sub_result[0];
		
		if ($ItemQtyExists > 0 ){
			$message  = 'Delete not allowed, negative quantity exists.';
			$AllowDelete = 0;
		}
	
	}
	
	if ($AllowDelete == 1) {
		//Check Each Production If Has Serial No Used
		$query = " Select Count(Purchasesserialno.SerialNo_Code) ".
				 " From Production ".
				 " Inner Join Purchasesserialno on Purchasesserialno.PurchaseDt_Id = Production.Production_ID ".
				 " Where Production.Production_ID = '".$SPrdId."' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'PD' ";
 
		$result = selectData($connection, $query);
		$SerNoUsedExists = $result[0];
		
		if ($SerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$AllowDelete = 0;
		}
	
	}
	
		


	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
	    $sub_query = " Select Journal_Id From Production Where Production_id = ".$SPrdId;
		$sub_result = selectData($connection, $sub_query);
		$vPrdJournalID = $sub_result[0];
		if(empty($vPrdJournalID)) $vPrdJournalID = -1;
		
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPrdId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'production', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		
				
		// Delete From ProductionDt For Selected Record
		$query = " DELETE FROM ProductionDt ".
				 " WHERE Production_id = ".$SPrdId;
					 
		if (updateData($connection, $query, true)) {
			$query = " DELETE FROM Purchasesserialno ".
					 " WHERE PurchaseDt_id = '".$SPrdId."' ".
					 " AND Journal_Type = 'PD' ";
			//echo $query; exit;		 
			if (!updateData($connection, $query, true))		 
			  $message  = mysql_error(); 
			  
			// Delete From Production For Selected Record
			$query = " DELETE FROM Production ".
					 " WHERE Production_id = ".$SPrdId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
					
				
			if ($vPrdJournalID != -1) {
				
				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vPrdJournalID;
					
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	

			}	
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SPrdId != ''){

	// Delete From TempProductionDt For Selected Record
	$query = " DELETE FROM Temp_ProductionDt ".
			 " WHERE Production_id = ".$SPrdId;
			 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
				 
	if (updateData($connection, $query, true)) {
		$query = " DELETE FROM Temp_Purchasesserialno ".
				 " WHERE PurchaseDt_id = '".$SPrdId."' ".
				 " AND Journal_Type = 'PD' ";
				 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
		if (!updateData($connection, $query, true))		 
		  $message  = mysql_error(); 
	  
		// Delete From TempProduction For Selected Record
		$query = " DELETE FROM Temp_Production ".
				 " WHERE Production_id = ".$SPrdId;
				 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		$expdate = explode('/',$txtDate);
			$newdate = $expdate[2]."".$expdate[1]."".$expdate[0]; 
			$querydate = "select date_format('$newdate','%c'), date_format('$newdate','%y') ;";
			$resdate = mysql_query($querydate, $connection);
			$rwdate = mysql_fetch_row($resdate);
			$vmonth = $rwdate[0];
		
		$queryupdatebacth = "update jfolio set prod_ref = prod_ref-1 where Journal_Date='$vmonth'";
		$resupdatebatch = mysql_query($queryupdatebacth,$connection);
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SPrdId != ''){
	
	$ErrorExists = 0;
	$message  = '';
	

	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_production (Production_ID, Production_Reference, Production_Date, Production_ExpireDate, Production_Remark, Currency_Code, Project_Code, Costcenter_code, ".
			 " Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_IdealQty, Production_Waste, Production_Total, Production_TotalBase1, Production_TotalBase2, ".
			 " Production_IdealTotal, Journal_Id, Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, Production_DirectStkDbt, ".
			 " Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff, PreProduction_id, Production_BatchNo, ".
			 " User_Account, Logged_Code,RelatedDt_Id,Client_Code,Quantity_Ill,production_shadeStrd, production_shadeAct, production_strengthStrd , production_strengthAct, production_prevBatchno , ".
			 " production_referenceStd , production_viscosityDirect, production_viscosityReduced, packingdt_amountStrd, packingdt_nbrStrd , packingdt_amountAct, packingdt_nbrAct,packingdt_amountAct2, ".
			 " packingdt_nbrAct2,production_gloss,production_Adhesion,production_Alkali,production_scuff, transfer_id, transfer_id2 ) ".
			 " SELECT Production_ID, Production_Reference, Production_Date, Production_ExpireDate, Production_Remark, Currency_Code, Project_Code, Costcenter_code, ".
			 " Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_IdealQty, Production_Waste, Production_Total, Production_TotalBase1, Production_TotalBase2, ".
			 " Production_IdealTotal, Journal_Id, Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, Production_DirectStkDbt, ".
			 " Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff, PreProduction_id, Production_BatchNo, ".
			 " User_Account, '".$_SESSION['useraccount']."',RelatedDt_Id,Client_Code,Quantity_Ill,production_shadeStrd, production_shadeAct, production_strengthStrd , production_strengthAct, ".
			 " production_prevBatchno , production_referenceStd , production_viscosityDirect, production_viscosityReduced, packingdt_amountStrd, packingdt_nbrStrd , packingdt_amountAct,packingdt_nbrAct, ".
			 " packingdt_amountAct2, packingdt_nbrAct2,production_gloss,production_Adhesion,production_Alkali,production_scuff, transfer_id, transfer_id2 ".
			 " FROM Production ".
			 " WHERE Production_id = ".$SPrdId;
	//echo $query; exit;
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}
			
	//echo $message.$query; exit;				 
		
	if ($ErrorExists == 0) {
		
		$query = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
				 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
				 " ProductionDt_CostBase2, ProductionDt_ExpireDate, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
				 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_BatchNo, Logged_Code,productiondt_initialQty, productiondt_addition,productiondt_stage, ".
				 " productiondt_oldItem, prodcutiondt_isNonStock, prodcutiondt_nonStockPer) ".
				 " SELECT ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
				 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
				 " ProductionDt_CostBase2, ProductionDt_ExpireDate, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
				 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_BatchNo, '".$_SESSION['useraccount']."' ,productiondt_initialQty, productiondt_addition,productiondt_stage, ".
				 " productiondt_oldItem, prodcutiondt_isNonStock, prodcutiondt_nonStockPer ".
				 " FROM ProductionDt ".
				 " WHERE Production_id = ".$SPrdId;
		//echo $query; exit;
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 


		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_ID, Production_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
				 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.PurchaseDt_ID, Purchasesserialno.Production_ID, Purchasesserialno.Item_Code, Purchasesserialno.SerialNo_Code, Purchasesserialno.SerialNo_Used, Purchasesserialno.RelatedSerial_Id, Purchasesserialno.SerialNo_Quantity, ".
				 " SerialNo_QuantitySold, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " FROM Purchasesserialno ".
				 " Inner Join Temp_Production on Purchasesserialno.PurchaseDt_ID = Temp_Production.Production_ID ".
				 " WHERE Temp_Production.Production_ID = ".$SPrdId.
				 " AND Purchasesserialno.Journal_Type = 'PD' ";
	
		if (!updateData($connection, $query, true))
			$message  = mysql_error();	

		  
	}  
	
	
}

else if ($mode == "getitemname"){
	
		$query = "SELECT item_code,item_description
					FROM items ";
					
		if($choice==0)
			$query = $query." WHERE Upper(item_code) = Upper('".str_replace('\\','\\\\',$itemcode)."') ";
		else
			$query = $query." WHERE Upper(item_description) = Upper('".str_replace('\\','\\\\',$itemcode)."') ";
					
		$result = selectData($connection, $query);
		$ItemCode = $result[0];
		$ItemDesc = $result[1];
		echo"[BRK]";
		echo $ItemCode;
		echo"[BRK]";
		echo $ItemDesc;
 
exit;
}


//Changing Sales Currency
else if($mode == "changecurrency" && $SPrdId != ''){ 

	$Rate_Query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$Rate_Result = selectData($connection, $Rate_Query);
	$vRate = $Rate_Result[0];
	
	$Rate_Query1  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$Rate_Result1 = selectData($connection, $Rate_Query1);
	$vRateB1 = $Rate_Result1[0];
	
	$Rate_Query2  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$Rate_Result2 = selectData($connection, $Rate_Query2);
	$vRateB2 = $Rate_Result2[0];
	
	

	$query = " UPDATE Temp_Production SET Currency_Code = '".$txtCurr."' WHERE Production_ID = $SPrdId ";
	$result=mysql_query($query,$connection);
	
	//echo $query; exit;

		
	//Update Detail Amount Columns
	$sub_query = " Select ProductionDt_Id, Currency_Code, ifNull(ProductionDt_Cost,0), ifNull(ProductionDt_CostBase1,0), ifNull(ProductionDt_CostBase2,0) ".
				 " From Temp_ProductionDt ".
				 " Where Production_ID = ".$SPrdId;	
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_row=mysql_fetch_array($sub_result)){
					
		$vPrdDtCost         = $sub_row[2];
		$vPrdDtCostBase1    = $sub_row[3];
		$vPrdDtCostBase2    = $sub_row[4];
			
		$vPrdDtCost       = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPrdDtCost, $connection);	
		$vPrdDtCostBase1  = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vPrdDtCost, $connection);
		$vPrdDtCostBase2  = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vPrdDtCost, $connection);
		
		$sub_query1 = " UPDATE Temp_ProductionDt SET  ".
					  " Currency_Code = '".$txtCurr."', ".
					  " ProductionDt_Cost = $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2 ".
					  " Where ProductionDt_Id = ".$sub_row[0];
		
		//echo $sub_query1; exit;	
		if (!updateData($connection, $sub_query1, true))		 
			$message  = mysql_error(); 
					
	}  //End Loop of SalesDt Query
		

	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($SPrdId, $vRate, $vRateB1, $vRateB2, $connection);
	$message  = $message . $CalculateResult;

	
		
}

//Change Header Item Qty
else if($mode == "changeprodqty" && $SPrdId != ''){

	if (empty($PPrdQty)) $PPrdQty = 0;
	if (empty($PPrdQtyIdeal)) $PPrdQtyIdeal = 0;
	
	$sub_query = " Select Production.Currency_Code, Date_Format(Production_Date,'%d/%m/%Y') As Production_Date, ".
				 " Production.Item_Code, Production.Warehouse_Code ".
                 " From Temp_Production As Production  ".
				 " Where Production.Production_ID = '".$SPrdId."' ";
	$sub_result = selectData($connection, $sub_query);
	$vPrdCurr      = $sub_result[0];
	$vPrdDate      = $sub_result[1];
	$vPrdItemCode  = $sub_result[2];
	$vPrdWhCode    = $sub_result[3];
	$vPrdQty       = $PPrdQty;
	$vPrdQtyIdeal  = $PPrdQtyIdeal;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];	
		
	$sub_query = " UPDATE Temp_Production SET  ".
				 " Production_Quantity = $vPrdQty ".
				 " ,Production_IdealQty = $vPrdQtyIdeal ".
				 " Where Production_ID = '".$SPrdId."'";
								 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection);
	
	$packdt_query = " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, ifNull(PackDt.PackDt_Quantity,1), PackDt.PackDt_CostPercentage ".
					" , ifNull(Item_QtyToBeProduced, 1) ".
					" FROM PackDt ".
					" INNER JOIN Temp_ProductionDt on Temp_ProductionDt.Item_Code = PackDt.Item_CodePackDt ".
					" INNER JOIN items on items.Item_Code = PackDt.Item_Code ".
					" WHERE PackDt.Item_Code = '".$vPrdItemCode."'  ";
							   
	$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];
		$ItemQtyToBeProd = $packdt_rows[4];	
		$vPrdDtQty       = 0;
		$vPrdDtQtyIdeal  = 0; 
		$vPrdDtWaste     = 0;
		$vPrdDtCost      = 0;
		$vPrdDtCostBase1 = 0;
		$vPrdDtCostBase2 = 0;
		$vPrdDtQtyIni =0;
		$QtyExistExceeded   = 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 = '".$vItemCode."'";
		$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];
		//$ItemQtyToBeProd = $sub_result[7];
//ECHO "XXXXX1";
//EXIT;
		//$ItemQtyToBeProd = 1;	
//echo $sub_query;
//exit;		
		//If Item NonStock Is False Then Check On QtyExists For The Item

		if ($ItemNonStock == 0) {
			$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$vPrdWhCode."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
				
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
//IF ($vItemCode=='RM-RAR-BAP') {
//	ECHO 	($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd."<BR>";
//	ECHO "vPrdQty=".$vPrdQty."<BR>vPackDtQty=".$vPackDtQty."<BR>ItemQtyToBeProd=".$ItemQtyToBeProd;
//	ECHO "XXXXX1";
//	EXIT;					
//}
					
			if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
				$QtyExistExceeded = 1;
		}		
	
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
				//	echo $ItemQtyToBeProd ;
//echo $sub_query;
//exit;	
			if ($DisableIdeal == 0) {
				if($vPrdQtyIdeal=='' or $vPrdQtyIdeal==0 )
					$vPrdDtQtyIdeal = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
				else $vPrdDtQtyIdeal = ($vPrdQtyIdeal*$vPackDtQty)/$ItemQtyToBeProd; 
				
				$vPrdDtWaste    = $vPrdDtQtyIdeal - $vPrdDtQty;
				$vPrdDtQtyIni = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
			} else {
				$vPrdDtQtyIdeal = 0; 
				$vPrdDtWaste    = 0;
			}	
						
				
			fbegin();	 
			$query = " UPDATE temp_productiondt SET ".
			         " ProductionDt_Quantity = $vPrdDtQty, ".
					 " Productiondt_idealqty = $vPrdDtQtyIdeal,".
					 " productiondt_initialQty = $vPrdDtQtyIni ";
			
			
			//$query = $query."  ,ProductionDt_IdealQty = $vPrdDtQtyIdeal ";
			
			
			$query = $query." ,ProductionDt_Waste = $vPrdDtWaste ".
					 " WHERE Production_ID = '".$SPrdId."' ".
					 " AND Item_code = '".$vItemCode."'";
				
			$result=mysql_query($query,$connection);
			//echo $query."<br>";
				
			if ($result){
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		} else {
			//$ErrorExists = 1;
			$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
		}
			
	} // End Loop Of Packdt
		
	if ($ErrorExists == 0){
			
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;
						
	}
}
else if($mode == "changeprodqtyideal" && $SPrdId != ''){

	if (empty($PPrdQty)) $PPrdQty = 0;
	if (empty($PPrdQtyIdeal)) $PPrdQtyIdeal = 0;
	
	$sub_query = " Select Production.Currency_Code, Date_Format(Production_Date,'%d/%m/%Y') As Production_Date, ".
				 " Production.Item_Code, Production.Warehouse_Code ".
                 " From Temp_Production As Production  ".
				 " Where Production.Production_ID = '".$SPrdId."' ";
	$sub_result = selectData($connection, $sub_query);
	$vPrdCurr      = $sub_result[0];
	$vPrdDate      = $sub_result[1];
	$vPrdItemCode  = $sub_result[2];
	$vPrdWhCode    = $sub_result[3];
	$vPrdQty       = $PPrdQty;
	$vPrdQtyIdeal  = $PPrdQtyIdeal;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];	
		
	$sub_query = " UPDATE Temp_Production SET  ".
				 " Production_Quantity = $vPrdQty ".
				 " ,Production_IdealQty = $vPrdQtyIdeal ".
				 " Where Production_ID = '".$SPrdId."'";
								 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection);
	
	$packdt_query = " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, ifNull(PackDt.PackDt_Quantity,1), PackDt.PackDt_CostPercentage ".
					" , ifNull(Item_QtyToBeProduced, 1) ".
					" FROM PackDt ".
					" INNER JOIN Temp_ProductionDt on Temp_ProductionDt.Item_Code = PackDt.Item_CodePackDt ".
					" INNER JOIN items on items.Item_Code = PackDt.Item_Code ".
					" WHERE PackDt.Item_Code = '".$vPrdItemCode."'  ";
							   
	$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];
		$ItemQtyToBeProd = $packdt_rows[4];
			
		$vPrdDtQty       = 0;
		$vPrdDtQtyIdeal  = 0; 
		$vPrdDtWaste     = 0;
		$vPrdDtCost      = 0;
		$vPrdDtCostBase1 = 0;
		$vPrdDtCostBase2 = 0;
		
		$QtyExistExceeded   = 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 = '".$vItemCode."'";
		$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];
		//$ItemQtyToBeProd = $sub_result[7];

//$ItemQtyToBeProd = 1;
//ECHO "XXXXX2";
//EXIT;			
		//If Item NonStock Is False Then Check On QtyExists For The Item
		if ($ItemNonStock == 0) {
			$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$vPrdWhCode."', Now(), 0, 'PDT', '', '') QtyExists From Dual ";
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
				
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
			$vPrdDtQtyIdeal      = ($vPrdQtyIdeal*$vPackDtQty)/$ItemQtyToBeProd;
				
					
			if ($vPrdDtQty > $vItemQtyExists && $vPrdDtQty > 0)
				$QtyExistExceeded = 1;

			if ($vPrdDtQtyIdeal > $vItemQtyExists && $vPrdDtQtyIdeal > 0)
				$QtyExistExceeded = 1;
		}		
			
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
			$vPrdDtQty      = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd;
			$vPrdDtQtyIdeal      = ($vPrdQtyIdeal*$vPackDtQty)/$ItemQtyToBeProd;
				
			if ($DisableIdeal == 0) {
			
				if($vPrdQtyIdeal=='' or $vPrdQtyIdeal==0 )
					$vPrdDtQtyIdeal = ($vPrdQty*$vPackDtQty)/$ItemQtyToBeProd; 
				else	
					$vPrdDtQtyIdeal = ($vPrdQtyIdeal*$vPackDtQty)/$ItemQtyToBeProd; 
				
				$vPrdDtWaste    = $vPrdDtQtyIdeal - $vPrdDtQty;
			} else {
				$vPrdDtQtyIdeal = 0; 
				$vPrdDtWaste    = 0;
			}	
						
				
			fbegin();	 
			$query = " UPDATE temp_productiondt SET ".
			        // " ProductionDt_Quantity = $vPrdDtQty, ".
					 " ProductionDt_IdealQty = $vPrdDtQtyIdeal, ".
					 " ProductionDt_Waste = $vPrdDtWaste ".
					 " WHERE Production_ID = '".$SPrdId."' ".
					 " AND Item_code = '".$vItemCode."'";
				
			$result=mysql_query($query,$connection);
			//echo $query."<br>";
				
			if ($result){
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		} else {
			//$ErrorExists = 1;
			$message  = "Qty[$vPrdDtQty] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
		}
			
	} // End Loop Of Packdt
		
	if ($ErrorExists == 0){
			
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;
						
	}
}

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

	   
	$vPrdDate         = $txtDate;
	$vPrdExpireDate   = $txtPrdExpireDate;
	$vPrdBatchNo 	  = $txtPrdBatchNo;
	$vPrdItemCode     = $txtItemCodeFG;
	$vPrdWhCode       = $txtWhCode;
	$vPrdCurr         = $txtCurr;
	$vPrdProjectCode  = $txtProjectCode;
	$vPrdCostCentCode = $txtCostCentCode;
	$vPrdQty          = $txtPrdQty;
	$vPrdQtyIdeal     = $txtPrdQtyIdeal;
	$vPrdWaste        = $txtPrdWaste;
	$vPrdRemark       = $txtRemark;
	$vPrdQtyill 	  = $txtqtyill;
	
	if (empty($vPrdExpireDate))		$vPrdExpireDate = 'Null';
	else  $vPrdExpireDate = "'".insertMySQLDate($vPrdExpireDate)."'";
	
	
	if (!isset($vPrdCurr))
	   $vPrdCurr = $base1;
	if (empty($vPrdQty))
		$vPrdQty = 0;   
	if (empty($vPrdQtyIdeal))
		$vPrdQtyIdeal = 0;
	if (empty($vPrdWaste))
		$vPrdWaste = 0;
	
	if (empty($vPrdQtyill))
		$vPrdQtyill = 0;
	   
	$vPrdCostCentCode = "".$vPrdCostCentCode;   
	if ($vPrdCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vPrdCostCentCode."'";
	
	$vPrdProjectCode = "".$vPrdProjectCode; 	
	if ($vPrdProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vPrdProjectCode."'";      

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPrdCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPrdCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	if ($UnSelectedRows != '') {
		// Delete From TempProductionDt For UnSelected Records
		$query = " DELETE FROM Temp_ProductionDt ".
				 " WHERE ProductionDt_Id IN (".$UnSelectedRows.")";
					 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	
	
    $SaveAllow   = 1;
	$ErrorExists = 0;
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From Temp_ProductionDt ".
				 " Where Production_ID = '".$SPrdId."' ".
				 " And (Item_CodePacked Is Not Null and Item_CodePacked != '') ";
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$sub_rowcount = mysql_num_rows ($sub_result);
	
	if ($sub_rowcount > 0) {
		while($sub_row=mysql_fetch_array($sub_result)){
			$ItemQty = 0;
			$ItemPackQty = 0;
			
			$CheckQty = 0;
			$PackDtCode = '';
			$PackDtQty  = 0;
			
			$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
						  " From PackDt ".
						  " Where Item_Code = '".$sub_row[0]."' ";
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
			while($sub_row1=mysql_fetch_array($sub_result1)){
				// PackDt Items Should Be Different And Have Same Qty
				if ($PackDtCode != '' && $PackDtCode != $sub_row1[1] && $PackDtQty  == $sub_row1[2])
					$CheckQty = 1;
				
				$PackDtCode = $sub_row1[1];
				$PackDtQty  = $sub_row1[2];
			}
			
			// If PackDt Items Are Different And Have Same Qty Then Check For Qty Differences
			if ($CheckQty == 1) {
				$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
							  " From PackDt ".
							  " Where Item_Code = '".$sub_row[0]."' ";
				$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
				while($sub_row1=mysql_fetch_array($sub_result1)){
					$sub_query2 = " Select Item_CodePacked, Item_Code, Sum(ifNull(ProductionDt_Quantity,0)) As ProductionDtQuantity ".
								  " From Temp_ProductionDt ".
								  " Where Production_ID = '".$SPrdId."' ".
								  " And Item_CodePacked = '".$sub_row1[0]."' ".
								  " And Item_Code = '".$sub_row1[1]."' ".
								  " Group by Item_CodePacked, Item_Code ";
								  
					$sub_result2 = selectData($connection, $sub_query2);
					$ItemPackQty = $sub_result2[2] / $sub_row1[2];
					if (empty($sub_result2[2])) $ItemPackQty = -1;
					
					if ($ItemQty == 0) $ItemQty = $ItemPackQty;
					if ($ItemQty != $ItemPackQty) $SaveAllow = 0;
					
					
				}
			}		  
			
		}
	}
	
	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($vPrdCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$vPrdCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	if ($vPrdProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$vPrdProjectCode."' and ifnull(project_blocked,0) = 0 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	if ($vPrdItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$vPrdItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for FG Item Code.';
		}
	}
	if ($vPrdWhCode != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$vPrdWhCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for FG Warehouse Code.';
		}
	}
	
	if($txtClientCode != '') {
		$query = "update temp_production set Client_Code = '$txtClientCode' where Production_id=$SPrdId";
		$res = mysql_query($query,$connection);// echo $query;
		//exit;
	}
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select ProductionDt.ProductionDt_ID, ProductionDt.Item_code, ifNull(ProductionDt_Quantity,0) as ProductionDt_Quantity ".
					 " 	From Temp_ProductionDt As ProductionDt ".
					 " 	Where ProductionDt.Production_ID = ".$SPrdId.
					 " 	And ifNull(ProductionDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}
	
	//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) {
	
		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select ProductionDt_Id, Currency_Code, ifNull(ProductionDt_Cost,0), ifNull(ProductionDt_CostBase1,0), ifNull(ProductionDt_CostBase2,0) ".
					 " From Temp_ProductionDt ".
					 " Where Production_ID = ".$SPrdId;	
					 //echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vPrdDtCost         = $sub_row[2];
			$vPrdDtCostBase1    = $sub_row[3];
			$vPrdDtCostBase2    = $sub_row[4];
			
			
		    	
			if ($sub_row[1] != $vPrdCurr) {
				//ConvertCurrency($sub_row[1], $vPrdCurr, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection); exit;
				$vPrdDtCost    = ConvertCurrency($sub_row[1], $vPrdCurr, insertMySQLDate($vPrdDate), $vPrdDtCost, $connection);
						
				$vPrdDtCostBase1    = ($vPrdDtCost*$rate_dt)/$rate_dt1;
				$vPrdDtCostBase2    = ($vPrdDtCost*$rate_dt)/$rate_dt2;
					
				$sub_query1 = " UPDATE Temp_ProductionDt SET  ".
							  " Currency_Code = '".$vPrdCurr."', ".
							  " ProductionDt_Cost = $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2 ".
							  " Where ProductionDt_Id = ".$sub_row[0];
					
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
					
			}
			
			
			
					
		}  //End Loop of ProductionDt Query
		

		//Update Serials ExpireDate and BatchNo From Detail Table
		if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
			$sub_query5 = " Select Production_Id, Production_ExpireDate, Production_BatchNo ".
						  " From Temp_Production As Production  ".
						  " Where Production.Production_ID = ".$SPrdId;
							  
			//echo $sub_query5; 
			$sub_result5=mysql_query($sub_query5,$connection) or die(mysql_error());
			while($sub_rows5=mysql_fetch_array($sub_result5)){
				if (empty($sub_rows5[1]))		$vPrdDtExpireDate = 'Null';
				else  $vPrdDtExpireDate = "'".$sub_rows5[1]."'";		
			
				$query = " UPDATE temp_purchasesserialno SET ".
						 " Item_ExpireDate = $vPrdDtExpireDate, Item_BatchNo = '".$sub_rows5[2]."' ".
						 " WHERE PurchaseDt_Id  = '".$sub_rows5[0]."' ".
						 " AND Journal_Type = 'PD' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
				
			}
		}

		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPrdId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;
			

		$sub_query2 = " UPDATE Temp_ProductionDt SET ".
					  " Currency_Code = '".$vPrdCurr."', Production_Date = '".insertMySQLDate($vPrdDate)."' ";
					  
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCenter_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Production_id = $SPrdId ";
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
			
			
		if ($Module_SerialNo == 1) {
			//Check Each Production If Has Serial No Used
			$query = " Select Count(Purchasesserialno.SerialNo_Code) ".
					 " From Temp_Production ".
					 " Inner Join Temp_Purchasesserialno on Temp_Purchasesserialno.PurchaseDt_Id = Temp_Production.Production_ID ".
					 " Where Temp_Production.Production_ID = '".$SPrdId."' ".
					 " And ifNull(SerialNo_Used,0) = 1 ".
					 " And Temp_Purchasesserialno.Journal_Type = 'PD' ";
	 
			$result = selectData($connection, $query);
			$SerNoUsedExists = $result[0];
			
			if ($SerNoUsedExists == 0 ){
				$query = " UPDATE temp_purchasesserialno SET ".
						 " Item_code = '".ereg_replace("'", "\'", trim($vPrdItemCode))."', Warehouse_Code = '".ereg_replace("'", "\'", trim($vPrdWhCode))."' ".
						 " WHERE PurchaseDt_Id  = '".$SPrdId."' ".
						 " AND Journal_Type = 'PD' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
			}
		
		}

			
		$query = " UPDATE Temp_Production SET ".
				 " Production_Date = '".insertMySQLDate($vPrdDate)."' , Production_ExpireDate = $vPrdExpireDate, ".
				 " Production_Remark = '".ereg_replace("'", "\'", trim($vPrdRemark))."', ".
				 " Production_BatchNo = '".ereg_replace("'", "\'", trim($vPrdBatchNo))."', ".
				 " Currency_Code = '".$vPrdCurr."', Project_Code = $ProjectCode, Costcenter_code = $CostCentCode, ".
				 " Production_Quantity = $vPrdQty, Item_code = '".ereg_replace("'", "\'", trim($vPrdItemCode))."', ".
				 " Warehouse_Code = '".ereg_replace("'", "\'", trim($vPrdWhCode))."', ".
				 " Quantity_Ill = $vPrdQtyill ".
				 " WHERE Production_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;
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcenter_Code  FROM Production WHERE Production_id = $SPrdId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_Production where Production_ID = '".$SPrdId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			 $query_checkDelivery  = "select count(*) as ProductionExist from production where production_id = '$SPrdId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($ProductionExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
				
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query_test_temp  = "select ProductionDt_cost from temp_productiondt";
				$result_test_temp = mysql_query($query_test_temp, $connection);
				$row_test_temp    = mysql_fetch_array($result_test_temp);
				//extract($row_test_temp);
				//echo $ProductionDt_cost; exit;
				$query = "SELECT CopyData_TempAssemble('".$SMode."', ".$SPrdId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$result = $result[0];
					
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT Production_Reference, Costcenter_Code, Project_Code FROM Production WHERE Production_id = $SPrdId ";
					$result  = selectData($connection, $query);
					$vPrdRef = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
					
					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vPrdRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vPrdRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}	
					if ($vPrdRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							
						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';
							
						fbegin();
						$vPrdRef = get_nextsequence('production_reference',$vProjCostCent,$connection);	
						fcommit();
							
						$query = " UPDATE Production SET ".
								 " Production_Reference = $vPrdRef ".
								 " WHERE Production_id = $SPrdId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
					}

					if ($Module_PostToJournal == 1 && $Module_DirectStockPD == 1)	
						$message = Create_AssembleJv($SPrdId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
					
						
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempAssemble Function'; 
					frollback();
					
				}
			
			}
			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPrdId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'production', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
			
		} 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();
	}	
}

//Add non Stock Item Mode
else if($mode == "addNonStock" && $SPrdId != ''){
	$itemnCode_NonStock = $_POST['itemnCode_NonStock'];
	$txtProjectCode		= $_POST['txtProjectCode'];
	$txtCostCentCode	= $_POST['txtCostCentCode'];
	$nonStockPer		= $_POST['nonStockPer'];
	
	$ErrorExists = 0;
	
	if ($itemnCode_NonStock != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$itemnCode_NonStock."' and ifnull(Item_NonStock,0) = 1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	
	if ($ErrorExists == 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), Project_Code, CostCent_Code ".
					 " FROM Items WHERE Item_Code = '".$itemnCode_NonStock."'";
		$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];
		$ItemProject     = $sub_result[7];
		$ItemCostCent    = $sub_result[8];
		
		if ($Module_ProjectDt == 1) {
			if (empty($ItemProject)) {
				if (empty($txtProjectCode))
					$vPrdDtProject = 'Null';
				else
					$vPrdDtProject = "'".$txtProjectCode."'";   
			}	
			else {
				$vPrdDtProject = "'".$ItemProject."'";
			}	
		
		} else {
			if (empty($txtProjectCode))
				$vPrdDtProject = 'Null';
			else
				$vPrdDtProject = "'".$txtProjectCode."'";   
		}
		
		$txtCostCentCode = "".$txtCostCentCode;
		if ($Module_CostCenterDt == 1) {
			if (empty($ItemCostCent)) {
				if ($txtCostCentCode == '')
					$vPrdDtCostCent = 'Null';
				else
					$vPrdDtCostCent = "'".$txtCostCentCode."'";   
			}	
			else {
				$vPrdDtCostCent = "'".$ItemCostCent."'";
			}	
		
		} else {
			if ($txtCostCentCode == '')
				$vPrdDtCostCent = 'Null';
			else
				$vPrdDtCostCent = "'".$txtCostCentCode."'";   
		}
		
		$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
						 
		$sub_result = selectData($connection, $sub_query);
		
		$vTranStpDirectStkDbt 	 = $sub_result[0];
		$vTranStpDirectStkCrd 	 = $sub_result[1];
		$vTranStpDirectStkCur 	 = $sub_result[2];
		$vTranStpWasteDbtAcc  	 = $sub_result[3];
		$vTranStpWasteCrdAcc  	 = $sub_result[4];
		$vTranStpWasteDifAcc  	 = $sub_result[5];
		$vTranStpNonRmVatAcc  	 = $sub_result[6];
		$vTranStpRmVatAcc     	 = $sub_result[7];
		$vTranStpNonRmTTCIncAcc  = $sub_result[8];
		$vTranStpRmTTCIncAcc     = $sub_result[9];
		$vTranStpNonRmAcc        = $sub_result[10];
		$vTranStpRmAcc           = $sub_result[11];
				
		$vPrdDtDirectStkDbt 	 = $vTranStpDirectStkDbt;
		$vPrdDtDirectStkCrd 	 = $vTranStpDirectStkCrd;
		$vPrdDtDirectStkCur 	 = $vTranStpDirectStkCur;
		$vPrdDtWasteDbtAcc  	 = $vTranStpWasteDbtAcc;
		$vPrdDtWasteCrdAcc  	 = $vTranStpWasteCrdAcc;
		
		if ($ItemVat > 0) {
			if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
		}
		else {
			if ($ItemProd == 1) {
				if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
			}	
			else {
				if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
			}
		}
		
		$vPrdDtQty		= 1;
		$vPrdDtQtyIdeal = 0; 
		$vPrdDtWaste    = 0;
		$vPrdDtiniQty   = 0;
		$vPrdDtaddQty	= 0;
		
		$vPrdDtCost		= 0;
		
		$queryCost = "select sum(ProductionDt_Quantity*ProductionDt_cost), production.Production_Date, production.Currency_Code, production.Warehouse_Code
					from temp_productiondt
					inner join temp_production as production on production.production_id = temp_productiondt.production_id
					where production.production_id = $SPrdId and ifnull(prodcutiondt_isNonStock,0) <> 1 
					group by production.production_id ";
		$resCost 	= mysql_query($queryCost, $connection);
		$rowCost 	= mysql_fetch_row($resCost);
		$vPrdDtCost = $rowCost[0]*$nonStockPer/100;
		
		$vPrdDtCostBase1 = ConvertCurrency($rowCost[2], $base1, $rowCost[1], $vPrdDtCost, $connection);	
		$vPrdDtCostBase2 = ConvertCurrency($rowCost[2], $base2, $rowCost[1], $vPrdDtCost, $connection);	
		
		fbegin();
		$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
		fcommit();			
			 
		fbegin();	 
		$queryins = " INSERT INTO temp_productiondt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
				 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ProductionDt_CostBase1, ".
				 " ProductionDt_CostBase2, ProductionDt_Remark, ProductionDt_ItemAccount, ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ".
				 " ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ProductionDt_Checked, Logged_Code, ".
				 " productiondt_initialQty, productiondt_addition, productiondt_oldItem, prodcutiondt_isNonStock, prodcutiondt_nonStockPer ) ".
				 " VALUES ( ".$vPrdDtId.", ".$SPrdId.", '".$rowCost[2]."', '".$rowCost[1]."', $vPrdDtProject, $vPrdDtCostCent, '".$rowCost[3]."', ".
				 "          '".ereg_replace("'", "\'", trim($itemnCode_NonStock))."',  Null, 0, $vPrdDtQty, $vPrdDtQtyIdeal, $vPrdDtWaste, $vPrdDtCost, $vPrdDtCostBase1, $vPrdDtCostBase2, ".
				 "          Null, '".$vPrdDtItemAcc."', '".$vPrdDtDirectStkDbt."', '".$vPrdDtDirectStkCrd."', '".$vPrdDtDirectStkCur."', '".$vPrdDtWasteDbtAcc."', '".$vPrdDtWasteCrdAcc."', ".
				 "          1, '".$_SESSION['useraccount']."', $vPrdDtiniQty,$vPrdDtaddQty,  '".ereg_replace("'", "\'", trim($itemnCode_NonStock))."', 1, $nonStockPer) ";
		
		$resultins=mysql_query($queryins,$connection);
		
		if ($resultins){
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	}
}
else if ($mainmode == 'duplicateProduction' && $SPrdId != ''){
	
	fbegin();	
		$vPrdId = get_nextsequence('Production_id','',$connection);
	fcommit();
	
	$errorExist = 0;
	fbegin();		
	$queryheader = "insert into temp_production (Production_id, Production_Reference, Production_Date, Item_Code, SerialNo_Code, Warehouse_Code, Production_quantity, Currency_Code, Project_code,
				Costcenter_Code, Production_Remark, Journal_id, Production_Total, Production_TotalBase1, Production_TotalBase2, Production_ExpireDate, ProductionDt_Id,
				Production_edit, Size_Measure, Color_code, Production_MeanOrLastCost, Production_ItemAccount, Production_BelongsToGroup, PreProduction_id, Production_idealqty,
				Production_IdealTotal, SERIALNO_CODEREF, Production_DirectStkDbt, Production_DirectStkCrd, Production_DirectStkCur, Production_posted, Sendreceive_reference,
				Synchronized, Barcode, Production_waste, TimeStart, TimeStop, CounterStart, CounterStop, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff,
				Production_Reversed, Item_UnitCoef, Item_Unit2Qty, production_type, subgroup_code, production_WIDTH, production_WIDTHTrim, production_WIDTHTrimPer,
				production_ActualNetWidth, production_thick, production_ActualNetWeight, production_BabyQuantity, BRANCH_CODE, Production_BatchNo,
				packingdt_amountAct2, packingdt_nbrAct2, Client_Code, Quantity_Ill, production_gloss, production_Adhesion, production_Alkali, production_scuff,
				Production_investper, production_shadeStrd, production_strengthStrd, production_shadeAct, production_strengthAct, production_prevBatchno, production_referenceStd,
				production_viscosityDirect, production_viscosityReduced, packingdt_amountStrd, packingdt_nbrStrd, packingdt_amountAct, packingdt_nbrAct, User_account, Logged_Code)
				select $vPrdId, NULL, now(), Item_Code, SerialNo_Code, Warehouse_Code, Production_quantity, Currency_Code, Project_code,
				Costcenter_Code, Production_Remark, Journal_id, Production_Total, Production_TotalBase1, Production_TotalBase2, Production_ExpireDate, ProductionDt_Id,
				Production_edit, Size_Measure, Color_code, Production_MeanOrLastCost, Production_ItemAccount, Production_BelongsToGroup, PreProduction_id, Production_idealqty,
				Production_IdealTotal, SERIALNO_CODEREF, Production_DirectStkDbt, Production_DirectStkCrd, Production_DirectStkCur, Production_posted, Sendreceive_reference,
				Synchronized, Barcode, Production_waste, TimeStart, TimeStop, CounterStart, CounterStop, Production_WasteDebit, Production_WasteCredit, Production_WasteDiff,
				Production_Reversed, Item_UnitCoef, Item_Unit2Qty, production_type, subgroup_code, production_WIDTH, production_WIDTHTrim, production_WIDTHTrimPer,
				production_ActualNetWidth, production_thick, production_ActualNetWeight, production_BabyQuantity, BRANCH_CODE, Production_BatchNo,
				packingdt_amountAct2, packingdt_nbrAct2, Client_Code, Quantity_Ill, production_gloss, production_Adhesion, production_Alkali, production_scuff,
				Production_investper, production_shadeStrd, production_strengthStrd, production_shadeAct, production_strengthAct, production_prevBatchno, production_referenceStd,
				production_viscosityDirect, production_viscosityReduced, packingdt_amountStrd, packingdt_nbrStrd, packingdt_amountAct, packingdt_nbrAct, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'
				from production where production_id = $SPrdId ";
	$resheader = mysql_query($queryheader, $connection);
	if ($resheader){
		$errorExist = 0;	
		fcommit();
	} else {
		$message  = mysql_error(); 
		frollback();
		$errorExist = 1;	
	}	
	
	if ($errorExist == 0){
		
		$querydt = "select Production_Date, Item_Code, SerialNo_Code, Warehouse_Code, ProductionDt_Quantity, Currency_Code, ProductionDt_cost, ProductionDt_CostBase1, 
					ProductionDt_CostBase2, Project_code, Costcenter_Code, ProductionDt_ExpireDate, Size_Measure, Color_Code, Item_Barcode, Productiondt_ItemAccount, Productiondt_idealqty, ProductionDt_DirectStkDbt, 
					ProductionDt_DirectStkCrd, ProductionDt_DirectStkCur, Item_CodePacked, Item_qtyPacked, Synchronized, Production_DefaultSerial, Productiondt_Remark, ProductionDt_Waste, ProductionDt_WasteDebit, 
					ProductionDt_WasteCredit, Item_UnitCoef, Item_Unit2Qty, Productionmaster_id, item_special, productiondt_Weight, productiondt_width, ProductionDt_BatchNo, ProductionDt_Checked, productiondt_heatno, 
					productiondt_stage, productiondt_initialQty, productiondt_addition, '".$_SESSION['useraccount']."', productiondt_oldItem 
					from productiondt where production_id = $SPrdId ";
		$resdt = mysql_query($querydt, $connection);	
		while ($rwdt = mysql_fetch_array($resdt))	{
			fbegin();
				$vPrdDtId = get_nextsequence('ProductionDt_id','',$connection);
			fcommit();
			$queryins = " insert into temp_productiondt (ProductionDt_id, Production_id, Production_Date, Item_Code, SerialNo_Code, Warehouse_Code, ProductionDt_Quantity, Currency_Code, ProductionDt_cost, ProductionDt_CostBase1, 
					ProductionDt_CostBase2, Project_code, Costcenter_Code, ProductionDt_ExpireDate, Size_Measure, Color_Code, Item_Barcode, Productiondt_ItemAccount, Productiondt_idealqty, ProductionDt_DirectStkDbt, 
					ProductionDt_DirectStkCrd, ProductionDt_DirectStkCur, Item_CodePacked, Item_qtyPacked, Synchronized, Production_DefaultSerial, Productiondt_Remark, ProductionDt_Waste, ProductionDt_WasteDebit, 
					ProductionDt_WasteCredit, Item_UnitCoef, Item_Unit2Qty, Productionmaster_id, item_special, productiondt_Weight, productiondt_width, ProductionDt_BatchNo, ProductionDt_Checked, productiondt_heatno, 
					productiondt_stage, productiondt_initialQty, productiondt_addition, Logged_Code, productiondt_oldItem) values ".
					"($vPrdDtId, $vPrdId, ".strformat($rwdt[0]).", ".strformat($rwdt[1]).", ".strformat($rwdt[2]).", ".strformat($rwdt[3]).", ".strformat($rwdt[4]).", ".strformat($rwdt[5]).", ".strformat($rwdt[6]).", ".strformat($rwdt[7]).", 
					".strformat($rwdt[8]).", ".strformat($rwdt[9]).", ".strformat($rwdt[10]).", ".strformat($rwdt[11]).", ".strformat($rwdt[12]).", ".strformat($rwdt[13]).", ".strformat($rwdt[14]).", ".strformat($rwdt[15]).", 
					".strformat($rwdt[16]).", ".strformat($rwdt[17]).", 
					".strformat($rwdt[18]).", ".strformat($rwdt[19]).", ".strformat($rwdt[20]).", ".strformat($rwdt[21]).", ".strformat($rwdt[22]).", ".strformat($rwdt[23]).", ".strformat($rwdt[24]).", ".strformat($rwdt[25]).", 
					".strformat($rwdt[26]).", 
					".strformat($rwdt[27]).", ".strformat($rwdt[28]).", ".strformat($rwdt[29]).", ".strformat($rwdt[30]).", ".strformat($rwdt[31]).", ".strformat($rwdt[32]).", ".strformat($rwdt[33]).", 
					".strformat($rwdt[34]).", ".strformat($rwdt[35]).", ".strformat($rwdt[36]).", 
					".strformat($rwdt[37]).", ".strformat($rwdt[38]).", ".strformat($rwdt[39]).", '".$_SESSION['useraccount']."', ".strformat($rwdt[41])." )";
			$resins = mysql_query($queryins, $connection);	
				
		}
	}
	
	if ($errorExist == 0)	
		header ("Location: ./Form_AssembleSearch.php?message=Production%20has%20been%20Copied!");
	else header ("Location: ./Form_AssembleSearch.php?message=".$message);
	exit;
}

if($SPrdId != '' && $Production_extraInfo==1 && ($mode == "submitrecord-ajax" || $mode == "editdt-ajax")){
$queryCalcQty = "select sum(Productiondt_Quantity) from temp_productiondt B inner join items A on A.item_code=B.Item_Code 
				where A.Group_code != 'PKG' and Production_ID = $SPrdId;";
$resCalcQty = mysql_query($queryCalcQty,$connection);
$rowCalcQty = mysql_fetch_row($resCalcQty);		
$totalQty = 	$rowCalcQty[0];

}

$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")
	//header ("Location: ./Form_Assemble.php?actionmode=post&mainaction=&PrPrdId=".$SPrdId."&PrPrdRef=".$vPrdRef."&message=".$message);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Assemble.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPrdId=".$SPrdId."&PrPrdRef=".$vPrdRef."&message=".$message);
	else
		header ("Location: ./Form_Assemble.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);

}	

else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_AssembleSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_AssembleSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_Assemble.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_Assemble.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_AssembleDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPrdId=".$SPrdId."&PPrdDate=".$PPrdDate."&PPrdDtId=".$SPrdDtId."&message=".$message);		
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_AssembleSearch.php?PMode=1");	
else if ($mode == "loadmaterials" || $mode == 'loadmaterialsproj' || $mode == 'addNonStock')		
	header ("Location: ./Form_Assemble.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);	
else if ($mode == "" && $mainmode == "loadpreprod" )			
	header ("Location: ./Form_Assemble_LoadPreprod.php?PMode=1&actionmode=".$mode."&mainaction=".$mainmode."&GeneratedId=".$SPrdId."&message=".$message);
else if ($mode == "editqty" && $mainmode == "" )
	header ("Location: ./Form_AssembleSerialNo.php?SRPrdId=".$SPrdId."&PMode=1&message=".$message);	
else if ($mode == "changecurrency")	
	header ("Location: ./Form_Assemble.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);
else if ($mode == "changeprodqty" or $mode == "changeprodqtyideal" )	
	header ("Location: ./Form_Assemble.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPrdId=".$SPrdId."&message=".$message);
else if($mode == "submitrecord") {
    header ("Location: ./Form_AssembleDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPrdId=".$PPrdId."&PPrdDate=".$PPrdDate.
			"&PPrdExpireDate=".$PPrdExpireDate."&PPrdItemCode=".$PPrdItemCode."&PPrdWhCode=".$PPrdWhCode."&PPrdCurr=".$PPrdCurr.
			"&PPrdProjectCode=".$PPrdProjectCode."&PPrdCostCentCode=".$PPrdCostCentCode."&PPrdQty=".$PPrdQty."&PPrdQtyIdeal=".$PPrdQtyIdeal.
			"&PPrdWaste=".$PPrdWaste."&PPrdRemark=".$PPrdRemark."&message=".$message);
}else if ($mode == "" && $mainmode == "loadsorder" )		
	header ("Location: ./Form_Production_LoadSorder.php?PMode=1&GeneratedId=".$SPrdId."&message=".$message."&SSorId=".$SSorId);
else if ($mode == "transferDataFG")		
	header ("Location: ./Form_AssembleSearch.php?PMode=0");	


	//echo $mode; exit;
	//echo $mainmode;exit;
	
$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SPrdId;
$row_array['totalQty'] = $totalQty;	

array_push($return_arr,$row_array);
echo json_encode($return_arr);



function Calculate_MasterAmounts($PId, $PRate, $PRate1, $PRate2, $connection) {


		
	$vPrdTotalCost      = 0;
	$vPrdTotalCostBase1 = 0;
	$vPrdTotalCostBase2 = 0;
	$vPrdTotalCostIdeal = 0;

	//Calculating Master Amounts
	$sub_query = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)*ifNull(ProductionDt_Cost,0)),0) As TotalCost,  ".
				 " ifNull(Sum(ifNull(ProductionDt_IdealQty,0)*ifNull(ProductionDt_Cost,0)),0) As TotalCostIdeal ".
				 " From Temp_ProductionDt ".
				 " Where Production_ID = ".$PId;
	$sub_result = selectData($connection, $sub_query);
										 
	//echo $sub_query;exit;
					
	$vPrdTotalCost       = $sub_result[0];
	$vPrdTotalCostIdeal  = $sub_result[1];
	$vPrdTotalCostBase1  = ($vPrdTotalCost*$PRate)/$PRate1;
	$vPrdTotalCostBase2  = ($vPrdTotalCost*$PRate)/$PRate2;
					

	fbegin();
	
	$sub_query1 = " UPDATE temp_production SET ".
				  " Production_Total = $vPrdTotalCost, Production_TotalBase1 = $vPrdTotalCostBase1, ".
				  " Production_TotalBase2 = $vPrdTotalCostBase2, Production_IdealTotal = $vPrdTotalCostIdeal ".
				  " WHERE Production_ID = ".$PId;
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


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

function NonStuckItem_Recalculation($SPrdId, $base1, $base2, $connection){
	$vPrdDtCost		= 0;
		
	$queryCost = "select sum(ProductionDt_Quantity*ProductionDt_cost), production.Production_Date, production.Currency_Code
				from temp_productiondt
				inner join temp_production as production on production.production_id = temp_productiondt.production_id
				where production.production_id = $SPrdId and ifnull(prodcutiondt_isNonStock,0) <> 1 
				group by production.production_id ";
	$resCost 	= mysql_query($queryCost, $connection);
	$rowCost 	= mysql_fetch_row($resCost);
	$totCost 	= $rowCost[0];
	$ProdDate 	= $rowCost[1];
	$ProdCurr 	= $rowCost[2];
	
	$queryItems = "select ProductionDt_id, prodcutiondt_nonStockPer from temp_productiondt where production_id = $SPrdId and ifnull(prodcutiondt_isNonStock,0) = 1  ";
	$resItems = mysql_query($queryItems, $connection);
	while ($rowItems = mysql_fetch_array($resItems)){
		
		$vPrdDtCost = $totCost*$rowItems[1]/100;
		$vPrdDtCostBase1 = ConvertCurrency($ProdCurr, $base1, $ProdDate, $vPrdDtCost, $connection);	
		$vPrdDtCostBase2 = ConvertCurrency($ProdCurr, $base2, $ProdDate, $vPrdDtCost, $connection);	
		
		if ($vPrdDtCost == '') 		$vPrdDtCost = 0;
		if ($vPrdDtCostBase1 == '') $vPrdDtCostBase1 = 0;
		if ($vPrdDtCostBase2 == '') $vPrdDtCostBase2 = 0;
		
		$update = "update temp_productiondt set ProductionDt_Cost = $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2				
					where ProductionDt_id = $rowItems[0] ";
		$res = mysql_query($update, $connection);			
	}
	
}

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

HERE;
*/

?>