<?php

session_start();

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

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

//Set Time Execution For the Report
ini_set('max_execution_time', $config['ReportTimeExecution']);

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



$querylog=" select FI_PurchasesVATMod, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(Login_location,0) As Login_location ".
		  " 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, ".
			 " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage 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_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
			 " 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_rawmaterial,0) As Module_RawMaterial, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_SerialNo,0) As Module_SerialNo , ifNull(module_locationGrn,0) As module_locationGrn".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Read From PurchaseSetup Table
$queryPurchaseSetup="Select PurchaseTTC From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}




$mode 		= $_GET["mode"]; if ($mode == ""){$mode = $_POST["mode"];}   
$mainmode   = $_GET["mainmode"]; if ($mainmode == ""){$mainmode = $_POST["mainmode"];}   

$SPurType    		= $_GET["SPurType"]; if ($SPurType == ""){$SPurType = $_POST["SPurType"];} 
$SPurId    			= $_GET["SPurId"]; if ($SPurId == ""){$SPurId = $_POST["SPurId"];} 
$SPurDtId			= $_GET["SPurDtId"]; if ($SPurDtId == ""){$SPurDtId = $_POST["SPurDtId"];} 

$txtPurId    		= $_GET["txtPurId"]; if ($txtPurId == ""){$txtPurId = $_POST["txtPurId"];} 
$txtDate 			= $_GET["txtDate"]; if ($txtDate == ""){$txtDate = $_POST["txtDate"];} 
$txtRequestDate 	= $_GET["txtRequestDate"]; if ($txtRequestDate == ""){$txtRequestDate = $_POST["txtRequestDate"];} 
$txtMaturityDate 	= $_GET["txtMaturityDate"]; if ($txtMaturityDate == ""){$txtMaturityDate = $_POST["txtMaturityDate"];} 
$txtSupplier 	   	= $_GET["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_POST["txtSupplier"];} 
$txtCurr   			= $_GET["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_POST["txtCurr"];} 
$txtPurCategory   	= $_GET["txtPurCategory"]; if ($txtPurCategory == ""){$txtPurCategory = $_POST["txtPurCategory"];} 
$txtRemark  		= $_GET["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_POST["txtRemark"];} 
$txtProjectCode 	= $_GET["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_POST["txtProjectCode"];} 
$txtCostCentCode	= $_GET["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_POST["txtCostCentCode"];} 
$txtInvoiceNo		= $_GET["txtInvoiceNo"]; if ($txtInvoiceNo == ""){$txtInvoiceNo = $_POST["txtInvoiceNo"];} 
$txtFormMNo			= $_GET["txtFormMNo"]; if ($txtFormMNo == ""){$txtFormMNo = $_POST["txtFormMNo"];} 
$txtPackRef			= $_GET["txtPackRef"]; if ($txtPackRef == ""){$txtPackRef = $_POST["txtPackRef"];} 

$PPurId    			= $_GET["PPurId"]; if ($PPurId == ""){$PPurId = $_POST["PPurId"];} 
$PPurDate 			= $_GET["PPurDate"]; if ($PPurDate == ""){$PPurDate = $_POST["PPurDate"];} 
$PPurCurr 			= $_GET["PPurCurr"]; if ($PPurCurr == ""){$PPurCurr = $_POST["PPurCurr"];} 
$PPurMaturityDate   = $_GET["PPurMaturityDate"]; if ($PPurMaturityDate == ""){$PPurMaturityDate = $_POST["PPurMaturityDate"];} 
$PPurSupplier 	   	= $_GET["PPurSupplier"]; if ($PPurSupplier == ""){$PPurSupplier = $_POST["PPurSupplier"];} 
$PPurCategory   	= $_GET["PPurCategory"]; if ($PPurCategory == ""){$PPurCategory = $_POST["PPurCategory"];} 
$PPurRemark  		= $_GET["PPurRemark"]; if ($PPurRemark == ""){$PPurRemark = $_POST["PPurRemark"];} 
$PPurProjectCode 	= $_GET["PPurProjectCode"]; if ($PPurProjectCode == ""){$PPurProjectCode = $_POST["PPurProjectCode"];} 
$PPurCostCentCode	= $_GET["PPurCostCentCode"]; if ($PPurCostCentCode == ""){$PPurCostCentCode = $_POST["PPurCostCentCode"];} 
$PPurInvoiceNo		= $_GET["PPurInvoiceNo"]; if ($PPurInvoiceNo == ""){$PPurInvoiceNo = $_POST["PPurInvoiceNo"];} 
$PPurFormMNo		= $_GET["PPurFormMNo"]; if ($PPurFormMNo == ""){$PPurFormMNo = $_POST["PPurFormMNo"];} 
$PPurPackRef		= $_GET["PPurPackRef"]; if ($PPurPackRef == ""){$PPurPackRef = $_POST["PPurPackRef"];} 


$lstWarehouse	= $_GET["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_POST["lstWarehouse"];} 
$lstLocation	= $_GET["lstLocation"]; if ($lstLocation == ""){$lstLocation = $_POST["lstLocation"];} 
$txtItemCode	= $_GET["txtItemCode"]; if ($txtItemCode == ""){$txtItemCode = $_POST["txtItemCode"];} 
$txtPurDtRemark	= $_GET["txtPurDtRemark"]; if ($txtPurDtRemark == ""){$txtPurDtRemark = $_POST["txtPurDtRemark"];} 
$txtPurDtQty	= $_GET["txtPurDtQty"]; if ($txtPurDtQty == ""){$txtPurDtQty = $_POST["txtPurDtQty"];} 
$txtPurDtQty2	= $_GET["txtPurDtQty2"]; if ($txtPurDtQty2 == ""){$txtPurDtQty2 = $_POST["txtPurDtQty2"];} 
$txtProjectCodeDt	= $_GET["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_POST["txtProjectCodeDt"];} 
$purchasedt_heatno	= $_GET["purchasedt_heatno"]; if ($purchasedt_heatno == ""){$purchasedt_heatno = $_POST["purchasedt_heatno"];} 
$txtCostCentCodeDt	= $_GET["txtCostCentCodeDt"]; if ($txtCostCentCodeDt == ""){$txtCostCentCodeDt = $_POST["txtCostCentCodeDt"];} 
$txtPurDtVolume		= $_GET["txtPurDtVolume"]; if ($txtPurDtVolume == ""){$txtPurDtVolume = $_POST["txtPurDtVolume"];} 
$txtPurDtBatchNo	= $_GET["txtPurDtBatchNo"]; if ($txtPurDtBatchNo == ""){$txtPurDtBatchNo = $_POST["txtPurDtBatchNo"];} 
$txtPurDtExpireDate	= $_GET["txtPurDtExpireDate"]; if ($txtPurDtExpireDate == ""){$txtPurDtExpireDate = $_POST["txtPurDtExpireDate"];} 
$txtgrncostprice	= $_GET["txtgrncostprice"]; if ($txtgrncostprice == ""){$txtgrncostprice = $_POST["txtgrncostprice"];} 



/*
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='insertpurchase' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SPurType' value='$SPurType'>
<input type='text' name='SPurId' value='$SPurId'>
<input type='text' name='SPurDtId' value='$SPurDtId'>
HERE;
*/
$message='';

if (!isset($PPurCurr))
   $PPurCurr = $base2;
	   
//Submit Record Mode

if ($mode == 'updateWarehouse' && $SPurId != ''){
	$warehouse_code = $_GET['warehouse_code'];
	$update = "update temp_grnpurchasesdt set Warehouse_Code = '".$warehouse_code."' where Purchase_id = $SPurId ";
	$result = mysql_query($update, $connection);
	echo "[BRK]";
	echo mysql_error();
	exit;
}
if ($mode == "submitrecord" || $mode == "submitrecord-ajax" ){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (empty($PPurCategory))
		$PPurCategory = 0;
			
	if (empty($PPurCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if (empty($PPurProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'";   

	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($PPurCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PPurCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PPurProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PPurProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PPurSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$PPurSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Supplier Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	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($module_locationGrn == 1){
	if ($lstLocation != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstLocation."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Location Code.';
		}
	}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	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 ($PPurProjectCode != '') {
		$prjwarehouse = "select 1 from warehouseProject where project_code = '".$PPurProjectCode."' group by project_code";
		$reswarehouse = mysql_query($prjwarehouse, $connection);
		$rwwarehouse = mysql_num_rows($reswarehouse);	
		
		if ($rwwarehouse > 0){
			$sub_query = " Select Count(1) From warehouseProject ".
						 " Where Project_Code = '".$PPurProjectCode."' and 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.';
			}
		}
	}
	//Insert Master Table
	if ($SPurId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$PPurId = get_nextsequence('Grn_Id','',$connection);
		fcommit();
		
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$PPurCurr."') As DebitCur ".
					 " FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$Supp_Query = " SELECT ifNull(Supplier_VAT, 0) ".
					  " FROM Suppliers ".
					  " WHERE Ledger_Number = '".ereg_replace("'", "\'", trim($PPurSupplier))."'";
		$Supp_Result = selectData($connection, $Supp_Query);
		if (empty($Supp_Result[0])) $Supp_Result[0] = 0;
				
		fbegin();     
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_VatChkbx, Purchase_Mode, Journal_Type, Journal_Id, Purchase_BelongsToGroup, ".
				 " Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitAccount, Purchase_DebitCur, Purchase_Import, Purchase_Type, Purchase_Grn, Purchase_PackingListRef, Purchase_FormMNo, ".
				 " User_Account, Logged_Code,date_received, Purchase_ManualNo) ".
				 " VALUES ( ".$PPurId.", Null, CONCAT('".displayParadoxDate(insertDate($PPurDate))." ', RIGHT(NOW(), 8)), '".ereg_replace("'", "\'", trim($PPurRemark))."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', ".
				 "          '".$PPurCurr."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."', '".insertMySQLDate($PPurMaturityDate)."' , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 0, 0, $Supp_Result[0], 0, 'PI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', ".
				 "          '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$PPurCategory."', '".$PPurType."', 1, '".ereg_replace("'", "\'", trim($PPurPackRef))."', '".ereg_replace("'", "\'", trim($PPurFormMNo))."', ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','".insertMySQLDate($PPorRequestDate)."', '".ereg_replace("'", "\'", trim($txtManualNo))."' )";
		
		//echo $query."<br>";exit;					 
		$result=mysql_query($query,$connection);
		
		
		if ($result){
			$SPurId = $PPurId;
			fcommit();
		}else{
			$PPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	//Insert Detail Tables
	if ($SPurId != "" && $SPurDtId == ""  && $ErrorExists == 0){
	
		
		if (empty($txtPurDtQty))
		    $txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
		    $txtPurDtQty2 = 0;	
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
			
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	
		
		if (empty($txtPurDtPackagingNo))
			$txtPurDtPackagingNo = 0;      		
		if (empty($txtPurDtNbrUnit))
			$txtPurDtNbrUnit = 0;		
				
		$vPurDtDirectStkDbt = '';
		$vPurDtDirectStkCrd = '';
		$vPurDtDirectStkCur = '';
		$vPurDtVatAcc	    = '';
		$vPurDtItemAcc      = '';
		$vPurStpDirectStkDbt = '';
		$vPurStpDirectStkCrd = '';
		$vPurStpDirectStkCur = '';
		$vPurStpVatAcc       = '';
		$vPurStpDebitAcc     = '';
		$vTranStpDirectStkDbt = '';
		$vTranStpDirectStkCrd = '';
		$vTranStpDirectStkCur = '';
		$vTranStpVatAcc       = '';
		$vTranStpNonRmVatAcc  = '';
		$vTranStpRmVatAcc     = '';
		$vTranStpNonRmTTCIncAcc  = '';
		$vTranStpRmTTCIncAcc     = '';
		$vTranStpNonRmAcc  = '';
		$vTranStpRmAcc     = '';
		
		$vItemCodeFinished     = '';
		$vItemCodeSemiFinished = '';
				
		
		$WarningMsg = '';
		
		$query = " SELECT ifNull(Item_Production, 0), ifNull(Item_SemiFinished, 0), ifNull(Item_Pack, 0) ".
			     " FROM Items WHERE item_Code = '".$txtItemCode."'";
		$result = selectData($connection, $query);
		$ItemFinished   = $result[0];
		$ItemSemiFinish = $result[1];
		$ItemPack	    = $result[2];
				
				   
		if ($ItemFinished == 1) {
			$vItemCodeFinished     = "'".$txtItemCode."'";
			$vItemCodeSemiFinished = 'Null';
		}
		else if ($ItemSemiFinish == 1) {
			$vItemCodeFinished     = 'Null';
			$vItemCodeSemiFinished = "'".$txtItemCode."'";
		}
		else {
			$vItemCodeFinished     = 'Null';
			$vItemCodeSemiFinished = 'Null';
		}
		
		
		// Case Not Pack Item
		//if ($txtItemCodePacked == '') {
		/*if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || 
		    $lstItemType == "NonStock" || $lstItemType == "FinishGoodSingle" || $lstItemType == "SemiFinishSingle" || 
			$lstItemType == "RawMaterial" || $lstItemType == "All") {*/
		if ($ItemPack != 1) {	

			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
			        " FROM Items WHERE item_Code = '".$txtItemCode."'";
			$result = selectData($connection, $query);
			$ItemVat 	    = $result[0];
			$Item_MaxQty    = $result[1];
			$ItemGroupCode  = $result[2];
			$ItemProd       = $result[3];
			$ItemTTCInc     = $result[4];
			$ItemUnit       = $result[5];
			$ItemNonStock   = $result[6];
				   
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $txtPurDtQty2;
			}
				
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock  ".
					 " FROM purchasesetup ";
						 
			$result = selectData($connection, $query);
				
			$vPurStpDirectStkDbt   = $result[0];
			$vPurStpDirectStkCrd   = $result[1];
			$vPurStpDirectStkCur   = $result[2];	
			$vPurStpVatAcc         = $result[3];	
			$vPurStpDebitAcc       = $result[4];	
			$vPurStpVatNonStockAcc = $result[5];	
				
				
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PI' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
						 
			$result = selectData($connection, $query);
				
			$vTranStpDirectStkDbt = $result[0];
			$vTranStpDirectStkCrd = $result[1];
			$vTranStpDirectStkCur = $result[2];
			$vTranStpVatAcc       = $result[3];
			$vTranStpNonRmVatAcc  = $result[4];
			$vTranStpRmVatAcc     = $result[5];
			$vTranStpNonRmTTCIncAcc  = $result[6];
			$vTranStpRmTTCIncAcc     = $result[7];
			$vTranStpNonRmAcc  = $result[8];
			$vTranStpRmAcc     = $result[9];
				
			if ($Module_RawMaterial == 1) {
				$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPurDtDirectStkCur = $vTranStpDirectStkCur;
				$vPurDtVatAcc       = $vTranStpVatAcc;
					
				if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
					}
				}	
			} 
			else {
				$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
				$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
				
				if ($ItemNonStock == 1)		
					$vPurDtVatAcc = $vPurStpVatNonStockAcc;
				else
					$vPurDtVatAcc = $vPurStpVatAcc;
					
				if ($ItemVat > 0)
					$vPurDtItemAcc = $vPurStpVatAcc;
				else
					$vPurDtItemAcc = $vPurStpDebitAcc;	
			}
				
			$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
			
			if($txtgrncostprice != '') {
				$txtgrncostprice1 =  ConvertCurrency($PPurCurr, $base1, insertMySQLDate($PPurDate), $txtgrncostprice, $connection);
				$txtgrncostprice2 = ConvertCurrency($PPurCurr, $base2, insertMySQLDate($PPurDate), $txtgrncostprice, $connection);				
			} else {
				$txtgrncostprice = 0;
				$txtgrncostprice1 = 0;
				$txtgrncostprice2 = 0;
			}
			
			fbegin();
			$txtPurDtId = get_nextsequence('Grndt_Id','',$connection);	
			fcommit();
				
			fbegin();
			$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, ".
					 " PurchaseDt_Price, PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, ".
					 " Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, ".
					 " PurchaseDt_PriceTTCbase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, Item_CodeFinished, Item_CodeSemiFinished, ".
					 " Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code, purchasedt_heatno, grnpurchasesdt_packagingno, grnpurchasesdt_nbrUnit  ";
			if($lstLocation != '')		 
			$query =$query." , Location_code ";
			$query =$query." ,PurchaseDt_cost,PurchaseDt_costBase1,PurchaseDt_costBase2) VALUES ( ".$txtPurDtId.", ".$PPurId.", '".$PPurCurr."', CONCAT('".displayParadoxDate(insertDate($PPurDate))." ', RIGHT(NOW(), 8)), '".ereg_replace("'", "\'", trim($PPurSupplier))."', 'PI',  ".
					 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$txtItemCode."', $txtPurDtQty, 0, 0, 0, 0, 0, 0, 0, $ItemVat, $txtPurDtVolume, ".
					 "          '".ereg_replace("'", "\'", trim($txtPurDtRemark))."' ,  '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."',  Null, 0, 0, 0, 0, ".
					 "          0, 0, 0, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
					 "          $vItemCodeFinished, $vItemCodeSemiFinished, $vItemUnitCoef, $vItemUnit2Qty, $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', ".
					 "         '".$_SESSION['useraccount']."', '".$purchasedt_heatno."', $txtPurDtPackagingNo, $txtPurDtNbrUnit ";
			
				
			if($lstLocation != '')		 
			$query =$query." , '".$lstLocation."' ";
		
			
			$query =$query.",'".$txtgrncostprice."','".$txtgrncostprice1."','".$txtgrncostprice2."' ) ";
		
		
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
				
			if ($result){
				fcommit();
			
			}else{
				$txtPurDtId = "";
				$message  = mysql_error(); 
				frollback();
			}				
			
		}	// End Case Not Pack Item
		else {
			
				fbegin();
				
				if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack") {
					$querypackdt = " SELECT PackDt1.Item_Code, PackDt1.Item_CodePackDt, PackDt1.PackDt_Quantity, PackDt1.PackDt_CostPercentage ".
								   " FROM PackDt, PackDt As PackDt1, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = PackDt1.Item_Code ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 1 ".
								   " UNION ".
								   " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.PackDt_Quantity, PackDt.PackDt_CostPercentage ".
								   " FROM PackDt, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 0 ";
				} else {
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
				}
				
				//echo $querypackdt;
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
				
					if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack")	$vItemCodePacked = '';
					else $vItemCodePacked = $rowspackdt[0];
					
					$vItemCode       = $rowspackdt[1];
					$vPackDtQty      = $rowspackdt[2];
					$vPackDtCostPer  = $rowspackdt[3];
						   
					
					fbegin();
					$vPurDtId = get_nextsequence('Grndt_Id','',$connection);
					fcommit();

					$vPurDtQty = $txtPurDtQty*$vPackDtQty;
					
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
					         " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$ItemVat 	   = $result[0];
					$Item_MaxQty   = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd 	   = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemUnit  	   = $result[5];
					$ItemNonStock  = $result[6];
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						$vItemUnitCoef = $ItemUnit;
						
						if ($Module_Unit1Method == 1)
							$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
						else	
							$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
					}
						
						
					$vPurDtDirectStkDbt = '';
					$vPurDtDirectStkCrd = '';
					$vPurDtDirectStkCur = '';
					$vPurDtVatAcc	    = '';
					$vPurDtItemAcc      = '';
					$vPurStpDirectStkDbt = '';
					$vPurStpDirectStkCrd = '';
					$vPurStpDirectStkCur = '';
					$vPurStpVatAcc       = '';
					$vPurStpDebitAcc     = '';
					$vTranStpDirectStkDbt = '';
					$vTranStpDirectStkCrd = '';
					$vTranStpDirectStkCur = '';
					$vTranStpVatAcc       = '';
					$vTranStpNonRmVatAcc  = '';
					$vTranStpRmVatAcc     = '';
					$vTranStpNonRmTTCIncAcc  = '';
					$vTranStpRmTTCIncAcc     = '';
					$vTranStpNonRmAcc  = '';
					$vTranStpRmAcc     = '';
					
									
				
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock  ".
							 " FROM purchasesetup ";
							 
					$result = selectData($connection, $query);
					
					$vPurStpDirectStkDbt   = $result[0];
					$vPurStpDirectStkCrd   = $result[1];
					$vPurStpDirectStkCur   = $result[2];	
					$vPurStpVatAcc         = $result[3];	
					$vPurStpDebitAcc       = $result[4];	
					$vPurStpVatNonStockAcc = $result[5];
					
					
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PI' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
							 
					$result = selectData($connection, $query);
					
					$vTranStpDirectStkDbt = $result[0];
					$vTranStpDirectStkCrd = $result[1];
					$vTranStpDirectStkCur = $result[2];
					$vTranStpVatAcc       = $result[3];
					$vTranStpNonRmVatAcc  = $result[4];
					$vTranStpRmVatAcc     = $result[5];
					$vTranStpNonRmTTCIncAcc  = $result[6];
					$vTranStpRmTTCIncAcc     = $result[7];
					$vTranStpNonRmAcc  = $result[8];
					$vTranStpRmAcc     = $result[9];
					
					if ($Module_RawMaterial == 1) {
						$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPurDtDirectStkCur = $vTranStpDirectStkCur;
						$vPurDtVatAcc       = $vTranStpVatAcc;
						
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
							}
						}
					} 
					else {
						$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
						$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
						
						if ($ItemNonStock == 1)		
							$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else
							$vPurDtVatAcc = $vPurStpVatAcc;
						
						if ($ItemVat > 0)
							$vPurDtItemAcc = $vPurStpVatAcc;
						else
							$vPurDtItemAcc = $vPurStpDebitAcc;	
					}
					
					$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
					
					$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, ".
							 " PurchaseDt_Price, PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, ".
							 " Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, Item_qtyPacked, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, ".
							 " PurchaseDt_PriceTTCbase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, Item_CodeFinished, Item_CodeSemiFinished, Item_UnitCoef, Item_Unit2Qty, ".
							 " PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code, purchasedt_heatno, grnpurchasesdt_packagingno, grnpurchasesdt_nbrUnit ";
					if($lstLocation != '')		 
					$query =$query." , Location_code ";			 
					$query =$query." ) VALUES ( ".$vPurDtId.", ".$PPurId.", '".$PPurCurr."', CONCAT('".displayParadoxDate(insertDate($PPurDate))." ', RIGHT(NOW(), 8)) , '".ereg_replace("\'", "''", trim($PPurSupplier))."', 'PI', ".
							 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$vItemCode."',  $vPurDtQty, 0, 0, 0, 0, 0, 0, 0, $ItemVat, $txtPurDtVolume, ".
							 "          '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."',  if('".$vItemCodePacked."'='', Null, '".$vItemCodePacked."'), ".
							 "          $txtPurDtQty, 0, 0, 0, 0, 0, 0, 0, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
							 "          $vItemCodeFinished, $vItemCodeSemiFinished, $vItemUnitCoef, $vItemUnit2Qty, $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', '".$_SESSION['useraccount']."', '".$purchasedt_heatno."',".
							 " 			$txtPurDtPackagingNo, $txtPurDtNbrUnit ";			
					if($lstLocation != '')		 
					$query =$query." , '".$lstLocation."' ";
					$query =$query." ) ";	 
			
					$result=mysql_query($query,$connection);
							
					//echo $query;
				} // End Loop Of Packdt
				
				
				
				if ($result){

					fcommit();
				}else{
					$txtPurDtId = "";
					$message  = mysql_error(); 
					frollback();
				}	
			
			
		} // End CasePack Item
		
	} // End Case Insert In Detail Tables

} 


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

	$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 ($lstLocation != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstLocation."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Location Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	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 ($PPurProjectCode != '') {
		$prjwarehouse = "select 1 from warehouseProject where project_code = '".$PPurProjectCode."' group by project_code";
		$reswarehouse = mysql_query($prjwarehouse, $connection);
		$rwwarehouse = mysql_num_rows($reswarehouse);	
		
		if ($rwwarehouse > 0){
			$sub_query = " Select Count(1) From warehouseProject ".
						 " Where Project_Code = '".$PPurProjectCode."' and 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 ($ErrorExists == 0) {
	
		if (empty($txtPurDtQty))
			$txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
			$txtPurDtQty2 = 0;		
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
			
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}	
			
		if (empty($txtPurDtPackagingNo))
			$txtPurDtPackagingNo = 0;      		
		if (empty($txtPurDtNbrUnit))
			$txtPurDtNbrUnit = 0;		
		
		$sub_query = "SELECT ifNull(Item_NonStock,0), ifNull(Item_WithSerialNo,0) FROM Items WHERE item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'";
		$sub_result = selectData($connection, $sub_query);
		$ItemNonStock = $sub_result[1];
		$ItemSerialNo = $sub_result[2];
		
		
		//Edit Item Code/Warehouse Check If Item Is Purchased
		$sub_query = " Select Count(*) From PurchasesDt ".
					 " Where PurchasesDt.RelatedDt_Id = '".$SPurDtId."' ".
					 " And PurchasesDt.Journal_Type = 'PI' ";
		$sub_result = selectData($connection, $sub_query);
		$PurchaseExists = 0;
		$PurchaseExists = $sub_result[0];
		
		//Check GrnPurchasesDt If Has Serial No Used
		$SerialUsedExists = 0;
		if ($Module_SerialNo == 1 && $ItemSerialNo == 1) {
			$sub_query = " Select Count(SerialNo_Code) From Purchasesserialno  ".
						 " Where Purchasesserialno.GrnDt_Id = '".$SPurDtId."' ".
						 " And ifNull(SerialNo_Used,0) = 1 ".
						 " And Purchasesserialno.Journal_Type = 'PI' ";
			$sub_result = selectData($connection, $sub_query);
			$SerialUsedExists = $sub_result[0];
		}	
		
		$NegativeQtyExists = 0;
		if ($SerialUsedExists == 0 && ($Module_NegativeQuantity == 0 || $Login_negativeQty == 0)) {
			//Check PurchaseDt Item For Quantity Exists If Negative
			$sub_query = " Select Count(Item_Code) ".
						 " From ( ".
						 " 		Select Item_Code, Warehouse_Code, PurchaseDt_Quantity, ".
						 " 		QtyExistsWSorder(Item_Code, Warehouse_Code, Now(), PurchaseDt_Id, 'PI', '', '') QtyExists ".
						 " 		From GrnPurchasesDt ".
						 " 		Where GrnPurchasesDt.PurchaseDt_ID = '".$SPurDtId."' ".
						 " ) Q1 Where QtyExists < 0 ";
	 
			$sub_result = selectData($connection, $sub_query);
			$ItemQtyExists = $sub_result[0];
			
			if ($ItemQtyExists > 0 ){
				$NegativeQtyExists = 1;
			}
		
		}
							
		fbegin();	
								
		$query = " UPDATE temp_grnpurchasesdt SET  ".
				 " PurchaseDt_Quantity = $txtPurDtQty, Item_Unit2Qty = $txtPurDtQty2, PurchaseDt_Volume = $txtPurDtVolume, ".
				 " Purchasedt_Remark = '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', PurchaseDt_ExpireDate = $vPurDtExpireDate, ".
				 " PurchaseDt_BatchNo = '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', grnpurchasesdt_packagingno = $txtPurDtPackagingNo, grnpurchasesdt_nbrUnit = $txtPurDtNbrUnit ";
				 
		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCent_Code = $CostCentCodeDt ";
		
			//$query=$query.",PurchaseDt_cost=$txtgrncostprice ,PurchaseDt_costBase1='".ConvertCurrency($PPurCurr, $base1, insertMySQLDate($PPurDate), $txtgrncostprice, $connection)."',PurchaseDt_costBase2='".ConvertCurrency($PPurCurr, $base2, insertMySQLDate($PPurDate), $txtgrncostprice, $connection)."'";
		//Edit Item Code/Warehouse If Item Is Not Purchased
		if ($PurchaseExists == 0 && $SerialUsedExists == 0){
			$query = $query.", Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."' ";
			if($lstLocation != '') $query = $query.", Location_Code = '".$lstLocation."' ";
		}
			
		$query = $query." Where PurchaseDt_ID = ".$SPurDtId;		 
		
								 
		//echo $query; exit;
		$result=mysql_query($query,$connection);
		if ($result){
			fcommit();
						
		}else{
			$message  = mysql_error(); 
			frollback();
		}				
			
	}
}

//Edit ItemQuantity
else if(($mode == "editqty" || $mode == "editqty1") && $SPurId != "" && $SPurDtId != ''){

	fbegin();	
							
	$query = " UPDATE temp_grnpurchasesdt SET  ".
	         " PurchaseDt_Quantity = $QItemQty ";
			
	if ($Module_DoubleUnit == 1 && $Module_Unit1Method == 1) {
		$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*ifNull(PurchaseDt_Quantity,0) ";
	}
	else if ($Module_DoubleUnit == 1 && $Module_Unit1Method == 0) {
		$query = $query.", Item_Unit2Qty = ifNull(PurchaseDt_Quantity,0)/ifNull(Item_UnitCoef,0) ";
	}
	
	$query = $query." Where PurchaseDt_ID = '".$SPurDtId."' ".
					" And Purchase_ID = '".$SPurId."'";
	
							 
	//echo $query; exit;
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();
					
	}else{
		$message  = mysql_error(); 
		frollback();
	}

}
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$message  = '';
	
	
	
	if ($AllowDelete == 0) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_GrnPurchasesDt As GrnPurchasesDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.GrnDt_Id = GrnPurchasesDt.PurchaseDt_Id ".
				 " Where GrnPurchasesDt.PurchaseDt_ID = ".$SPurDtId.
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'PI' ";
 
		$result = selectData($connection, $query);
		$PurSerNoUsedExists = $result[0];
		
		if ($PurSerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial no in use.';
			$AllowDelete = 1;
		}
	
	}
	
	if ($AllowDelete == 0) {
		//Check Each GrnDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where GrnPurchasesDt.PurchaseDt_ID = ".$SPurDtId;

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Delete not allowed, Good receive note exists in purchases.';
			$AllowDelete = 1;
		}
	
	}
	
	if ($AllowDelete == 0 && $Module_NegativeQuantity == 0) {
		//Check Each PurchaseDt Item For Quantity Exists If Negative
		$query = " Select Count(Item_Code) ".
				 " From ( ".
				 " Select Item_Code, WareHouse_Code, PurchaseDt_Quantity, ".
				 " QtyExistsWSorder(Item_Code, WareHouse_Code, Now(), PurchaseDt_Id, 'PI', '', '') QtyExists ".
				 " From GrnPurchasesDt ".
				 " Where GrnPurchasesDt.PurchaseDt_ID = ".$SPurDtId.
				 " ) Q1 Where QtyExists < 0 ";
 
		$result = selectData($connection, $query);
		$ItemQtyExists = $result[0];
		
		if ($ItemQtyExists > 0 ){
			$message  = 'Delete not allowed, negative quantity exists.';
			$AllowDelete = 1;
		}
	
	}
	


	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		
		$ErrorExists    = 0;

		$querypack = " SELECT GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code ".
					 " FROM Temp_GrnPurchasesDt As GrnPurchasesDt ".
					 " Where GrnPurchasesDt.PurchaseDt_ID = '".$SPurDtId."'";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
								   
		$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 TempPucrhasesSerialNo For Selected Record
			$query = " DELETE FROM Temp_Purchasesserialno ".
					 " WHERE GrnDt_id  = ".$SPurDtId.
					 " AND Journal_Type = 'PI' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
					
					
			// Delete From TempPucrhaseDt For Selected Record
			$query = " DELETE FROM Temp_GrnPurchasesDt ".
					 " WHERE PurchaseDt_id = ".$SPurDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querypurdt = " Select PurchaseDt_ID, GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code  ".
						  " From Temp_GrnPurchasesDt As GrnPurchasesDt  ".
						  " Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
						  " And GrnPurchasesDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
						  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultpurdt=mysql_query($querypurdt, $connection) or die(mysql_error());
			while($rowspurdt=mysql_fetch_array($resultpurdt)){		   
					
				$vPurDtId =	$rowspurdt[0];
					
				// Delete From TempPucrhasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						 " WHERE GrnDt_id  = ".$vPurDtId.
						 " AND Journal_Type = 'PI' ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
								 
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
							
						
				// Delete From TempPucrhaseDt For Selected Record
				$query = " DELETE FROM Temp_GrnPurchasesDt ".
						 " WHERE PurchaseDt_id = ".$vPurDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		

	} // End If No Constraints Found On Delete
	
	
}

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

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Purchase Is Posted
	$query = "SELECT ifNull(Purchase_Posted,0) As PurchasePosted FROM GrnPurchases WHERE Purchase_id = ".$SPurId;
	$result = selectData($connection, $query);
	$PurPosted = $result[0];
	
	if ($PurPosted == 1 ){
		$message  = 'Delete not allowed, purchase posted.';
		$AllowDelete = 0;
	}
	
	if ($AllowDelete == 1) {
		//Check Each GrnPurchasesDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where GrnPurchasesDt.Purchase_id = ".$SPurId;

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Delete not allowed, GRN converted to purchase.';
			$AllowDelete = 0;
		}
	
	}
	
	/*if ($AllowDelete == 1) {
		//Check If The GRN Becomes Purchase
		$query = " Select ifNull(GrnPurchases.Purchase_Type,'PI') As PurchaseType ".
				 " From GrnPurchases ".
				 " Where Purchase_id = '".$SPurId."' ".
				 "   And Journal_Type = 'PI' ";
 
		$result = selectData($connection, $query);
		$PurType = $result[0];
		
		if ($PurType != 'GRN' ){
			$message  = 'Delete not allowed, GRN converted to purchase.';
			$AllowDelete = 0;
		}
	
	}*/
	
	
	if ($AllowDelete == 1) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From GrnPurchasesDt ".
				 " Inner Join Purchasesserialno on Purchasesserialno.GrnDt_Id = GrnPurchasesDt.PurchaseDt_Id ".
				 " Where GrnPurchasesDt.Purchase_id = ".$SPurId.
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'PI' ";
 
		$result = selectData($connection, $query);
		$PurSerNoUsedExists = $result[0];
		
		if ($PurSerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial no in use.';
			$AllowDelete = 0;
		}
	
	}
	
	if ($AllowDelete == 1 && $Module_NegativeQuantity == 0) {
		//Check Each PurchaseDt Item For Quantity Exists If Negative
		$query = " Select Count(Item_Code) ".
				 " From ( ".
				 " Select Item_Code, WareHouse_Code, PurchaseDt_Quantity, ".
				 " QtyExistsWSorder(Item_Code, WareHouse_Code, Now(), PurchaseDt_Id, 'PI', '', '') QtyExists ".
				 " From GrnPurchasesDt ".
				 " Where GrnPurchasesDt.Purchase_id = ".$SPurId.
				 " ) Q1 Where QtyExists < 0 ";
 
		$result = selectData($connection, $query);
		$ItemQtyExists = $result[0];
		
		if ($ItemQtyExists > 0 ){
			$message  = 'Delete not allowed, negative quantity exists.';
			$AllowDelete = 0;
		}
	
	}
	


	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
		// Delete From PucrhasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE GrnDt_id In (Select PurchaseDt_id From GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ".
				 " AND Journal_Type = 'PI' ";
					 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPurId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'grn', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		
		// Delete From PucrhasesDt For Selected Record
		$query = " DELETE FROM GrnPurchasesDt ".
				 " WHERE Purchase_id = ".$SPurId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From Pucrhases For Selected Record
			$query = " DELETE FROM GrnPurchases ".
					 " WHERE Purchase_id = ".$SPurId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
		
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

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

			 
	// Delete From TempPucrhasesSerialNo For Selected Record
	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE GrnDt_id In (Select PurchaseDt_id From Temp_GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ".
			 " AND Journal_Type = 'PI' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
			
	// Delete From TempPucrhasesDt For Selected Record
	$query = " DELETE FROM Temp_GrnPurchasesDt ".
			 " WHERE Purchase_id = ".$SPurId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (updateData($connection, $query, true)) {
		// Delete From TempPucrhases For Selected Record
		$query = " DELETE FROM Temp_GrnPurchases ".
				 " WHERE Purchase_id = ".$SPurId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SPurId != ''){
	
	$ErrorExists = 0;
	$AllowEdit = 1;
	$message  = '';
	
	//Check If The GRN Becomes Purchase
	/*$query = " Select ifNull(GrnPurchases.Purchase_Type,'PI') As PurchaseType ".
			 " From Purchases ".
			 " Where Purchase_id = '".$SPurId."' ".
			 " And Journal_Type = 'PI' ";
 
	$result = selectData($connection, $query);
	$PurType = $result[0];
		
	if ($PurType != 'GRN' ){
		$message  = 'Edit not allowed, GRN converted to purchase.';
		$AllowEdit = 0;
	}*/
	
	if ($AllowEdit == 1) {
		//Check Each GrnPurchasesDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where GrnPurchasesDt.Purchase_id = ".$SPurId;

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Edit not allowed, GRN converted to purchase.';
			$AllowEdit = 0;
		}
	
	}
	

	if ($AllowEdit == 1) {
	
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, ".
				 " Journal_Type, Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, ".
				 " Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_VatChkbx, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, Purchase_PackingListRef, Purchase_FormMNo, User_Account,date_received, ".
				 " Purchase_ManualNo, Logged_Code) ".
				 " SELECT Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, ".
				 " Journal_Type, Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, ".
				 " Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_VatChkbx, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, Purchase_PackingListRef, Purchase_FormMNo, User_Account,date_received, ".
				 " Purchase_ManualNo, '".$_SESSION['useraccount']."' ".
				 " FROM GrnPurchases ".
				 " WHERE Purchase_id = ".$SPurId;
		
		if (!updateData($connection, $query, true)) {
			  $ErrorExists = 1;
			  $message  = mysql_error(); 	
		}
			
		//echo $message.$query; exit;				 
		
		if ($ErrorExists == 0) {
			$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
					 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, ".
					 " PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, PurchaseDt_Charges, PurchaseDt_ChargesBase1, ".
					 " PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, ".
					 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, RelatedDt_Id, Item_CodeFinished, Item_CodeSemiFinished, Item_qtyPacked, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code, purchasedt_heatno,Location_code, ".
					 " grnpurchasesdt_packagingno , grnpurchasesdt_nbrUnit,PurchaseDt_cost ) ".
					 " SELECT PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
					 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, ".
					 " PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, PurchaseDt_Charges, PurchaseDt_ChargesBase1, ".
					 " PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, ".
					 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, RelatedDt_Id, Item_CodeFinished, Item_CodeSemiFinished, Item_qtyPacked, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, '".$_SESSION['useraccount']."', purchasedt_heatno  ".
					" ,Location_code, grnpurchasesdt_packagingno , grnpurchasesdt_nbrUnit,PurchaseDt_cost ".					
					" FROM GrnPurchasesdt ".
					 " WHERE Purchase_id = ".$SPurId;
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 			

			$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_id, GrnDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
					 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.PurchaseDt_id, Purchasesserialno.GrnDt_ID, Purchasesserialno.Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ".
					 " SerialNo_Quantity, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$_SESSION['useraccount']."' ".
					 " FROM Purchasesserialno ".
					 " Inner Join Temp_GrnPurchasesDt on Purchasesserialno.GrnDt_id = Temp_GrnPurchasesDt.PurchaseDt_id ".
					 //" WHERE PurchaseDt_id In ( Select PurchaseDt_id From Temp_GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ". 
					 " WHERE Purchase_id = ".$SPurId.
					 " AND Purchasesserialno.Journal_Type = 'PI' ";
					 
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 		

		}
	}
	
}

//Load Porder
else if($mainmode == "loadporder" ){
	

	
	
	//Insert Master Table
	if ($SPurId == "" && $SelectedRec != ""){
		
			 
		fbegin();	
		$vPurId = get_nextsequence('Grn_Id','',$connection);	
		fcommit();
	
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, DebitCur ".
					 " FROM purchasesetup ";			 
					 
		$Acc_Result = selectData($connection, $Acc_Query);
	
		fbegin();	
				 
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_VatChkbx, Purchase_Mode, Journal_Type, Journal_Id, Purchase_BelongsToGroup, ".
				 " Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitAccount, Purchase_DebitCur, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, ".
				 " User_Account, Logged_Code, grnpurchases_othercharges,date_received) ".
				 " SELECT $vPurId, Null, now(), Porder_Remark, Porder.Supplier_code, Porder.Currency_Code, Porder.Project_Code, Porder.Costcent_code, Null, ADDDATE(now(), ifNull(Suppliers.Supplier_PaymentTerms,0)), 0, ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, Porder_DiscountBase2, ".
				 " Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, 0, 'PI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', ".
				 " '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', Porder_Import, 'GRN', 1, Porder_Reference, Porder_Reference, '".$_SESSION['useraccount']."',  ".
				 " '".$_SESSION['useraccount']."', porder_othercharges,date_received ".
				 " FROM Porder Inner Join Suppliers on Porder.Supplier_code = Suppliers.Ledger_Number ".
				 " WHERE Porder_id = ".$SelectedRec;

			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPurId = $vPurId;
			fcommit();
		}else{
			$vPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	
	$vPurDiscountPer = 0;
	$vPurVatChkbx    = 0;
	$vPurCurrCode    = '';
	$vPurDate        = '';
	$vPurSuppCode    = '';
	
	
	if ($SPurId != '') {
	
		$vPurId = $SPurId;
		
		$ErrorExists = 0;
		
		$sub_query11 = " SELECT Currency_Code, Date_Format(Purchase_Date,'%d/%m/%Y') As Purchase_Date, Supplier_Code, ".
					   " Project_Code, CostCent_Code, ifNull(Purchase_DiscountPer,0), ifNull(Purchase_VatChkbx,0) ".
					   " FROM Temp_GrnPurchases ".
					   " WHERE Purchase_ID = '".$vPurId."' ";
		$sub_result11 = selectData($connection, $sub_query11);
		
		$vPurCurrCode    = $sub_result11[0];
		$vPurDate        = $sub_result11[1];
		$vPurSuppCode    = $sub_result11[2];
		$vPurDiscountPer = $sub_result11[5];	
		$vPurVatChkbx	 = $sub_result11[6];	
		
		if (empty($vPurDiscountPer)) $vPurDiscountPer = 0;
		
		$sub_query = " SELECT PorderDt_Id, Currency_Code, Warehouse_Code, Item_code, Item_CodePacked, ifNull(PorderDt_Quantity,0), ".
					 " ifNull(PorderDt_Price,0), ifNull(PorderDt_PriceBase1,0), ifNull(ProderDt_PriceBase2,0), ifNull(PorderDt_Discount,0), ".
					 " ifNull(Item_Vat,0), ifNull(PorderDt_PriceTTC,0), ifNull(PorderDt_PriceTTCBase1,0), ifNull(PorderDt_PriceTTCBase2,0), ".
					 " PorderDt_Remark, ifNull(Item_UnitCoef,1), ifNull(Item_Unit2Qty,0), PorderDt.Project_Code, PorderDt.CostCent_Code, ".
					 " porderdt_cost, porderdt_freight ".
					 " FROM PorderDt ";
		
		if($SPurDtId != '')			 
			$sub_query = $sub_query." WHERE PorderDt.PorderDt_Id In (".$SPurDtId.")";
		else 
			$sub_query = $sub_query." WHERE PorderDt.Porder_Id = '".$SelectedRec."'";		
			
		$sub_query = $sub_query." AND ifNull(PorderDt.PorderDt_GRNRejected,0) = 0 ";
		
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
		
		    $vPurDtQty           = 0;
			$vPurDtPrice         = 0;
			$vPurDtPriceBase1    = 0;
			$vPurDtPriceBase2    = 0;
			$vPurDtDiscPer       = 0;
			$vPurDtPriceTTC      = 0;
			$vPurDtPriceTTCBase1 = 0;
			$vPurDtPriceTTCBase2 = 0;
			$vPurDtDiscAmt       = 0;
			$vPurDtDiscAmtBase1  = 0;
			$vPurDtDiscAmtBase2  = 0;
					
			$vPurDtDirectStkDbt = '';
			$vPurDtDirectStkCrd = '';
			$vPurDtDirectStkCur = '';
			$vPurDtVatAcc	    = '';
			$vPurDtItemAcc      = '';
			$vPurStpDirectStkDbt = '';
			$vPurStpDirectStkCrd = '';
			$vPurStpDirectStkCur = '';
			$vPurStpVatAcc       = '';
			$vPurStpDebitAcc     = '';
			$vTranStpDirectStkDbt = '';
			$vTranStpDirectStkCrd = '';
			$vTranStpDirectStkCur = '';
			$vTranStpVatAcc       = '';
			$vTranStpNonRmVatAcc  = '';
			$vTranStpRmVatAcc     = '';
			$vTranStpNonRmTTCIncAcc  = '';
			$vTranStpRmTTCIncAcc     = '';
			$vTranStpNonRmAcc  = '';
			$vTranStpRmAcc     = '';
			
			$vSupTax1 = 0;
			$vSupTax2 = 0;
			$vSupTax3 = 0;
			$vSupTax4 = 0;
			$vSupTax5 = 0;
			$vPurDtTax1 = 0;
			$vPurDtTax2 = 0;
			$vPurDtTax3 = 0;
			$vPurDtTax4 = 0;
			$vPurDtTax5 = 0;
			
			
			  
			$sub_query4 = " Select Sum(ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
					      " From GrnPurchasesDt ".
						  " Where GrnPurchasesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And GrnPurchasesDt.Journal_Type = 'PI' ".
						  " And GrnPurchasesDt.Purchase_Id != '".$vPurId."' ";
			$sub_result4 = selectData($connection, $sub_query4);
			if ($sub_result4[0] == '') $sub_result4[0] = 0;
	
			$sub_query5 = " Select Sum(ifNull(Temp_GrnPurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchasedTemp ".
					      " From Temp_GrnPurchasesDt ".
					      " Where Temp_GrnPurchasesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And Temp_GrnPurchasesDt.Journal_Type = 'PI' ".
						  " And Temp_GrnPurchasesDt.Purchase_Id = '".$vPurId."' ";
			$sub_result5 = selectData($connection, $sub_query5);
			if ($sub_result5[0] == '') $sub_result5[0] = 0;		  
			     
			
			$sub_query6 = " Select Sum(ifNull(ReturnPurchasesDt.PurchaseDt_Quantity,0)) As QuantityReturned ".
					      " From GrnPurchasesDt ReturnPurchasesDt ".
					      " Where ReturnPurchasesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And ReturnPurchasesDt.Journal_Type = 'PR' ";
			$sub_result6 = selectData($connection, $sub_query6);
			if ($sub_result6[0] == '') $sub_result6[0] = 0;		  
			

			//Get The Remaining Qty
			$vPurDtQty = ($row[5] - ($sub_result4[0] + $sub_result5[0]) + $sub_result6[0]);
			
			if ($vPurDtQty > 0 ) {
				
			
				$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0) ".
						 " FROM Items WHERE item_Code = '".$row[3]."'";
				$result = selectData($connection, $query);
				$ItemVat 	   = $result[0];
				$Item_MaxQty   = $result[1];
				$ItemGroupCode = $result[2];
				$ItemProd      = $result[3];
				$ItemTTCInc    = $result[4];
				$ItemUnit      = $result[5];
				$ItemPromo     = $result[6];
				$ItemNonStock  = $result[7];
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
							
					if ($Module_Unit1Method == 1)
						$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
					else	
						$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
				} 
				
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPurCurrCode."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPurCurrCode."' )";
				$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 If Currency of Detail Differs From Currency of The Header Then Convert Currency	
				if ($row[1] != $vPurCurrCode) {
					$vPurDtPrice    = $row[6];
					$vPurDtPriceTTC = $row[11];
					
					$vPurDtPrice    = ConvertCurrency($row[1], $vPurCurrCode, insertMySQLDate($vPurDate), $vPurDtPrice, $connection);
					$vPurDtPriceTTC = ConvertCurrency($row[1], $vPurCurrCode, insertMySQLDate($vPurDate), $vPurDtPriceTTC, $connection);
							
					$vPurDtPriceBase1    = ($vPurDtPrice*$rate_dt)/$rate_dt1;
					$vPurDtPriceBase2    = ($vPurDtPrice*$rate_dt)/$rate_dt2;
					$vPurDtPriceTTCBase1 = ($vPurDtPriceTTC*$rate_dt)/$rate_dt1;
					$vPurDtPriceTTCBase2 = ($vPurDtPriceTTC*$rate_dt)/$rate_dt2;
					
				} else {	
					
					$vPurDtPrice         = $row[6];
					$vPurDtPriceBase1    = $row[7];
					$vPurDtPriceBase2    = $row[8];
					
					$vPurDtPriceTTC      = $row[11];
					$vPurDtPriceTTCBase1 = $row[12];
					$vPurDtPriceTTCBase2 = $row[13];
				}
				
				$vPurDtDiscPer       = $row[9];
				
				// Calculation For Detail Discount Amount
				$vPurDtDiscAmt       = (($vPurDtPrice*$vPurDtQty) - ($vPurDtPrice*$vPurDtQty*$vPurDtDiscPer/100))*$vPurDiscountPer;
				$vPurDtDiscAmtBase1  = ($vPurDtDiscAmt*$rate_dt)/$rate_dt1;
				$vPurDtDiscAmtBase2  = ($vPurDtDiscAmt*$rate_dt)/$rate_dt2;

				if ($Module_AdditionalTaxes == 1) {
					// Calculation of Item Tax Amounts
					$query = " SELECT ifNull(Supplier_Tax1,0), ifNull(Supplier_Tax2,0), ifNull(Supplier_Tax3,0), ifNull(Supplier_Tax4,0), ifNull(Supplier_Tax5,0) ".
							 " FROM Suppliers ".
							 " WHERE Ledger_number = '".$vPurSuppCode."'";
												 
					$result = selectData($connection, $query);
					$vSupTax1 = $result[0];
					$vSupTax2 = $result[1];
					$vSupTax3 = $result[2];
					$vSupTax4 = $result[3];
					$vSupTax5 = $result[4];
										
					$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
							 " FROM Items ".
							 " WHERE Item_Code = '".$row[3]."'";
												 
					$result = selectData($connection, $query);

							
					if ($vSupTax1 != 0)	$vPurDtTax1 = $result[0];
					if ($vSupTax2 != 0)	$vPurDtTax2 = $result[1];
					if ($vSupTax3 != 0)	$vPurDtTax3 = $result[2];
					if ($vSupTax4 != 0)	$vPurDtTax4 = $result[3];
					if ($vSupTax5 != 0)	$vPurDtTax5 = $result[4];
								
				}
		
		
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock  ".
						 " FROM purchasesetup ";
							 
				$result = selectData($connection, $query);
					
				$vPurStpDirectStkDbt   = $result[0];
				$vPurStpDirectStkCrd   = $result[1];
				$vPurStpDirectStkCur   = $result[2];	
				$vPurStpVatAcc         = $result[3];	
				$vPurStpDebitAcc       = $result[4];	
				$vPurStpVatNonStockAcc = $result[5];
					
					
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'PI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
							 
				$result = selectData($connection, $query);
					
				$vTranStpDirectStkDbt = $result[0];
				$vTranStpDirectStkCrd = $result[1];
				$vTranStpDirectStkCur = $result[2];
				$vTranStpVatAcc       = $result[3];
				$vTranStpNonRmVatAcc  = $result[4];
				$vTranStpRmVatAcc     = $result[5];
				$vTranStpNonRmTTCIncAcc  = $result[6];
				$vTranStpRmTTCIncAcc     = $result[7];
				$vTranStpNonRmAcc  = $result[8];
				$vTranStpRmAcc     = $result[9];
					
				if ($Module_RawMaterial == 1) {
					$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vPurDtDirectStkCur = $vTranStpDirectStkCur;
					$vPurDtVatAcc       = $vTranStpVatAcc;
						
					if ($ItemVat > 0) {
						if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
						}
					}	
				} 
				else {
					$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
					$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
					
					if ($ItemNonStock == 1)		
						$vPurDtVatAcc = $vPurStpVatNonStockAcc;
					else
						$vPurDtVatAcc = $vPurStpVatAcc;
						
					if ($ItemVat > 0)
						$vPurDtItemAcc = $vPurStpVatAcc;
					else
						$vPurDtItemAcc = $vPurStpDebitAcc;	
				}
						
						
				$sub_queryVat = " SELECT GetVATAccount('".$sub_result11[2]."','".$vPurDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];		
				
				fbegin();
				$vPurDtId = get_nextsequence('Grndt_Id','',$connection);	
				fcommit();
				
					 
				fbegin();
				
				$sub_query1 = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, RelatedDt_Id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
							  " PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, ".
							  " Purchasedt_Remark, Purchase_invoiceNo, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, ".
							  " Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_UnitCoef, Item_Unit2Qty, ".
							  "	grnpurchasesdt_cost,grnpurchasesdt_freight,Logged_Code ) ".
							  " VALUES ( $vPurDtId, $vPurId, '".$row[0]."', '".$sub_result11[0]."', CONCAT('".displayParadoxDate(insertDate($sub_result11[1]))." ', RIGHT(NOW(), 8)), '".$sub_result11[2]."', 'PI', '".$row[17]."', '".$row[18]."', '".$row[2]."', '".$row[3]."', '".$row[4]."', ".
							  "          '".$vPurDtQty."', $vPurDtPrice, $vPurDtPriceBase1, $vPurDtPriceBase2, $vPurDtDiscPer, $vPurDtDiscAmt, $vPurDtDiscAmtBase1, $vPurDtDiscAmtBase2, '".$row[10]."', Null, ".
							  "          '".ereg_replace("'", "\'", $row[14])."', Null, 0, 0, 0, 0, $vPurDtPriceTTC, $vPurDtPriceTTCBase1, $vPurDtPriceTTCBase2, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', ".
							  "          '".$vPurDtItemAcc."', $vPurDtTax1, $vPurDtTax2, $vPurDtTax3, $vPurDtTax4, $vPurDtTax5, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$row[19]."','".$row[20]."', '".$_SESSION['useraccount']."' ) ";
				
				//echo $sub_query1; exit;
				$sub_result1=mysql_query($sub_query1,$connection);
			
			
				if ($sub_result1){
					$ErrorExists = 0;		
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} // End if($vPurDtQty > 0)
		}  //End Loop of PorderDt Query
		
		
		
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($vPurId, $vPurDate, $vPurVatChkbx, $vPurDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, 'U', $connection);
			$message  = $message . $CalculateResult;
		
		}
		
		if($SPurDtId != '' && $ErrorExists == 0) {	
			
			// Getting Porder references For Related Items
			$vPorderAllRef = '';
				
			$sub_query = " SELECT Distinct Porder.Porder_Reference ".
						 " FROM PorderDt ".
						 " Inner Join Porder on Porder.Porder_ID = PorderDt.Porder_ID ".
						 " Inner Join Temp_GrnPurchasesDt As GrnPurchasesDt on GrnPurchasesDt.RelatedDt_ID = PorderDt.PorderDt_ID ".
						 " WHERE GrnPurchasesDt.Purchase_Id  = ".$vPurId;

			$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_row=mysql_fetch_array($sub_result)){
				
				$pos = strrpos($vPorderAllRef, $sub_row[0]);
				if ($pos === false) { 
					$vPorderAllRef = $vPorderAllRef.','.$sub_row[0];
				}
					
			}
				
			$sub_query1 = " UPDATE temp_grnpurchases SET ".
						  " Purchase_PorderReferences   = Substr('".$vPorderAllRef."',2,length('".$vPorderAllRef."')) ".
						  " WHERE Purchase_ID = ".$vPurId;
			//echo $sub_query1; exit;		 
			$sub_result1=mysql_query($sub_query1,$connection);
		}
			
			
		
	}

}

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

	if (!isset($txtCurr))
	   $txtCurr = $base2;
	
	if (empty($txtPurCategory))
		$txtPurCategory = 0;
	//echo $txtPurCategory; exit;		
	if (empty($txtCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
	
	$SaveAllow   = 1;
	$ErrorExists = 0;
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_grnpurchasesdt ".
				 " Where Purchase_ID = '".$SPurId."' ".
				 " 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(PurchaseDt_Quantity,0)) As PurchaseDtQuantity ".
								  " From temp_grnpurchasesdt ".
								  " Where Purchase_ID = '".$SPurId."' ".
								  " 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 Save
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	if ($txtSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$txtSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Supplier Code.';
		}
	}
	
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_GrnPurchasesDt As GrnPurchasesDt Left Join Items on GrnPurchasesDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on GrnPurchasesDt.PurchaseDt_ID = Temp_Purchasesserialno.GrnDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'PI' ".
					 " 	And Temp_Purchasesserialno.PurchaseDt_ID Is Not Null ".
					 " 	Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By GrnPurchasesDt.PurchaseDt_ID ".
					 " 	Having ifNull(PurchaseDt_Quantity,0) != CountSerialNo ".
					 " ) 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 Serials.';
		}		 
	}				 
					 
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity ".
					 " 	From Temp_GrnPurchasesDt As GrnPurchasesDt ".
					 " 	Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
					 " 	And ifNull(PurchaseDt_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($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;
	
	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
		$sub_query = " UPDATE temp_grnpurchasesdt SET ".
					 " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
					 " Purchase_Date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)) ";
					 
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCent_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Purchase_id = $SPurId ";			 

		//echo $sub_query."<br>";exit;		   
		if (!updateData($connection, $sub_query, true))		 
			$message  = mysql_error(); 
			
		$sub_query1 = " SELECT Porder_Ref, Currency_Code, Purchase_Date, ifNull(Purchase_DiscountPer,0), ifNull(Purchase_VatChkbx,0) ".
					  " FROM Temp_GrnPurchases ".
					  " WHERE Purchase_ID = '".$SPurId."' ";
		$sub_result1 = selectData($connection, $sub_query1);
		
		$vPorderRef      = $sub_result1[0];
		$vPurCurrCode    = $sub_result1[1];
		$vPurDate        = $sub_result1[2];
		$vPurDiscountPer = $sub_result1[3];	
		$vPurVatChkbx	 = $sub_result1[4];		
		
		// In Case The GRN Is Created From Porder Then Recalculate The Master Amount Columns
		if ($vPorderRef != '') {
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPurCurrCode."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPurCurrCode."' )";
			$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];	
				
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $vPurDate, $vPurVatChkbx, $vPurDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, 'U', $connection);
			$message  = $message . $CalculateResult;
		}
		
		//Update Serials ExpireDate and BatchNo From Detail Table
		if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
			$sub_query5 = " Select PurchaseDt_Id, PurchaseDt_ExpireDate, PurchaseDt_BatchNo ".
						  " From Temp_GrnPurchasesDt As GrnPurchasesDt  ".
						  " Where GrnPurchasesDt.Purchase_ID = ".$SPurId;
						  
			//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]))		$vPurDtExpireDate = 'Null';
				else  $vPurDtExpireDate = "'".$sub_rows5[1]."'";		
		
				$query = " UPDATE temp_purchasesserialno SET ".
						 " Item_ExpireDate = $vPurDtExpireDate, Item_BatchNo = '".$sub_rows5[2]."' ".
					     " WHERE GrnDt_Id  = '".$sub_rows5[0]."' ".
						 " AND Journal_Type = 'PI' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
			
			}
		}
			
		$query = " UPDATE temp_grnpurchases SET ".
		         " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
				 " Purchase_Date = CONCAT('".displayParadoxDate(insertDate($txtDate))." ', RIGHT(NOW(), 8)), Purchase_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 " Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Purchase_InvoiceNo = '".$txtInvoiceNo."', ".
				 " Journaldt_valuedate = '".insertMySQLDate($txtMaturityDate)."', Purchase_Import = '".$txtPurCategory."', ".
				 " Purchase_PackingListRef = '".ereg_replace("'", "\'", trim($txtPackRef))."', Purchase_FormMNo = '".ereg_replace("'", "\'", trim($txtFormMNo))."' ".
				 " ,date_received = '".insertMySQLDate($txtRequestDate)."', Purchase_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."' ".
				 " WHERE Purchase_id = $SPurId ";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM GrnPurchases WHERE Purchase_id = $SPurId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_GrnPurchases where Purchase_ID = '".$SPurId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			$query_checkDelivery  = "select count(*) as GRNExist from grnpurchases where Purchase_id = '$SPurId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($GRNExist > 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 = "SELECT CopyData_TempGrnPurchases('PI', ".$SPurId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query;exit;
				$result = selectData($connection, $query);
				$result = $result[0];
				//echo $query; exit;
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT Purchase_Reference, Costcent_code, Project_Code FROM GrnPurchases WHERE Purchase_id = $SPurId ";
					$result  = selectData($connection, $query);
					$vPurRef = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
						
					if ($vPurRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1) ||
						($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1)) {
							
						if ($SPurType == 'GRN')  $RefColName = 'Grn_Reference';
						else if ($SPurType == 'RM') $RefColName = 'RmGrn_Reference';
						
						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';
						
						fbegin();
						$vPurRef = get_nextsequence($RefColName,$vProjCostCent,$connection);	
						fcommit();
							
						$query = " UPDATE GrnPurchases SET ".
								 " Purchase_Reference = $vPurRef ".
								 " WHERE Purchase_id = $SPurId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
					}
						
				
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempGrnPurchases Function'; 
					frollback();
				}
			}
			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPurId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'grn', '$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();
	}	
}


$message = ereg_replace(' ','%20',$message);
$PPurRemark    = ereg_replace(' ','%20',$PPurRemark);
$PPurInvoiceNo = ereg_replace(' ','%20',$PPurInvoiceNo);

$lstWarehouse  = ereg_replace('#','%23',$lstWarehouse);
$PPurRemark    = ereg_replace('#','%23',$PPurRemark);
$PPurInvoiceNo = ereg_replace('#','%23',$PPurInvoiceNo);

$lstWarehouse  = ereg_replace('&','%26',$lstWarehouse);
$PPurRemark    = ereg_replace('&','%26',$PPurRemark);
$PPurInvoiceNo = ereg_replace('&','%26',$PPurInvoiceNo);




//if($mode == "post")
	//header ("Location: ./Form_GoodRecNote.php?actionmode=post&mainaction=&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_GoodRecNote.php?actionmode=".$mode."&mainaction=".$mainmode."&PurType=".$SPurType."&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
	else
		header ("Location: ./Form_GoodRecNote.php?actionmode=submitrecord&mainaction=".$mainmode."&PurType=".$SPurType."&txtPurId=".$SPurId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_GoodRecNoteSearch.php?PurType=".$SPurType."&message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_GoodRecNoteSearchPending.php?PurType=".$SPurType);
else if ($mode == "cancel" )		
	header ("Location: ./Form_GoodRecNote.php?PurType=".$SPurType."&message=".$message);	
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_GoodRecNote.php?actionmode=".$mode."&mainaction=".$mainmode."&PurType=".$SPurType."&txtPurId=".$SPurId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_GoodRecNoteDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurType=".$SPurType."&PPurId=".$SPurId."&PPurDate=".$PPurDate."&PPurDtId=".$SPurDtId."&message=".$message);		
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_GoodRecNoteSearch.php?PMode=$AllowEdit&PurType=".$SPurType."&message=".$message);	
else if ($mode == "editqty1" && $mainmode == "" )			
	header ("Location: ./Form_GoodRecNoteSerialNo.php?PMode=1&PPurType=".$SPurType);	
else if ($mode == "editqty" && $mainmode == "" )
	header ("Location: ./Form_GoodRecNoteEditQty.php?PMode=1&PPurType=".$SPurType);	
else if ($mode == "" && $mainmode == "loadporder" )		
	header ("Location: ./Form_GoodRecNote_LoadPorder.php?PMode=1&PPurType=".$SPurType."&PPurId=".$SPurId."&message=".$message);				
else if($mode == "submitrecord") {
    header ("Location: ./Form_GoodRecNoteDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurType=".$SPurType."&PPurId=".$PPurId.	
			"&PPurDate=".$PPurDate."&PPurMaturityDate=".$PPurMaturityDate."&PPurSupplier=".$PPurSupplier."&PPurCurr=".$PPurCurr.
			"&PPurProjectCode=".$PPurProjectCode."&PPurCostCentCode=".$PPurCostCentCode."&PPurInvoiceNo=".$PPurInvoiceNo.
			"&lstWarehouse=".$lstWarehouse."&PPurRemark=".$PPurRemark."&message=".$message );
}


$return_arr = array();

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



function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PModuleAdditionalTaxes, $PMode, $connection) {

	$vPurDtTotal = 0;
	$vItemVat    = 0;
	
	$vPurTaxable = 0;
	$vPurNoneTaxable = 0;
	$vPurGrossTotal = 0;
	$vPurDiscountAmt = 0;
	$vPurDiscountPer = 0;
	$vPurVat = 0;
	$vPurVatBase1 = 0;
	$vPurVatBase2 = 0;
		
	$vPurTax1 = 0;
	$vPurTax2 = 0;
	$vPurTax3 = 0;
	$vPurTax4 = 0;
	$vPurTax5 = 0;
	$vPurTax1B1 = 0;
	$vPurTax2B1 = 0;
	$vPurTax3B1 = 0;
	$vPurTax4B1 = 0;
	$vPurTax5B1 = 0;
	$vPurTax1B2 = 0;
	$vPurTax2B2 = 0;
	$vPurTax3B2 = 0;
	$vPurTax4B2 = 0;
	$vPurTax5B2 = 0;

	$vPurDiscountPer = $PDiscPer;

						 
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0))-((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*ifNull(PurchaseDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " PurchaseDt_Quantity, ifNull(PurchaseDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_GrnPurchasesDt ".
				 " Where Purchase_ID = ".$PId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vPurDtTotal = $sub_rows[1];
		$vItemVat    = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vPurTaxable     = $vPurTaxable     + ($vPurDtTotal*$tax_flag);
		$vPurNoneTaxable = $vPurNoneTaxable + ($vPurDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vPurDtTotal > 0)
			$vPurVat = $vPurVat + (($vPurDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vPurDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vPurTax1 = $vPurTax1 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vPurTax2 = $vPurTax2 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vPurTax3 = $vPurTax3 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vPurTax4 = $vPurTax4 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vPurTax5 = $vPurTax5 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vPurGrossTotal = $vPurTaxable + $vPurNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vPurDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vPurDiscountPer > 0)
			$vPurDiscountAmt = (($vPurGrossTotal * $vPurDiscountPer) / 100);
	}				
				
					
	$vPurNetTotal         = $vPurGrossTotal + $vPurVat - $vPurDiscountAmt;
	$vPurTaxableBase1     = ($vPurTaxable*$PRate)/$PRate1;
	$vPurTaxableBase2     = ($vPurTaxable*$PRate)/$PRate2;
	$vPurNoneTaxableBase1 = ($vPurNoneTaxable*$PRate)/$PRate1;
	$vPurNoneTaxableBase2 = ($vPurNoneTaxable*$PRate)/$PRate2;
	$vPurDiscountAmtBase1 = ($vPurDiscountAmt*$PRate)/$PRate1;
	$vPurDiscountAmtBase2 = ($vPurDiscountAmt*$PRate)/$PRate2;
	$vPurGrossTotalBase1  = ($vPurGrossTotal*$PRate)/$PRate1;
	$vPurGrossTotalBase2  = ($vPurGrossTotal*$PRate)/$PRate2;
	$vPurVatBase1 		  = ($vPurVat*$PRate)/$PRate1;
	$vPurVatBase2 		  = ($vPurVat*$PRate)/$PRate2;
					

	$vPurTax1B1  = ($vPurTax1*$PRate)/$PRate1;
	$vPurTax1B2  = ($vPurTax1*$PRate)/$PRate2;		
	$vPurTax2B1  = ($vPurTax2*$PRate)/$PRate1;
	$vPurTax2B2  = ($vPurTax2*$PRate)/$PRate2;		
	$vPurTax3B1  = ($vPurTax3*$PRate)/$PRate1;
	$vPurTax3B2  = ($vPurTax3*$PRate)/$PRate2;		
	$vPurTax4B1  = ($vPurTax4*$PRate)/$PRate1;
	$vPurTax4B2  = ($vPurTax4*$PRate)/$PRate2;		
	$vPurTax5B1  = ($vPurTax5*$PRate)/$PRate1;
	$vPurTax5B2  = ($vPurTax5*$PRate)/$PRate2;	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_grnpurchases SET ".
				  " Purchase_Taxable = $vPurTaxable, Purchase_TaxableBase1 = $vPurTaxableBase1, Purchase_TaxableBase2 = $vPurTaxableBase2, ".
				  " Purchase_NoneTaxable = $vPurNoneTaxable, Purchase_NoneTaxableBase1 = $vPurNoneTaxableBase1, Purchase_NoneTaxableBase2 = $vPurNoneTaxableBase2, ".
				  " Purchase_DiscountAmount = $vPurDiscountAmt, Purchase_DiscountBase1 = $vPurDiscountAmtBase1, Purchase_DiscountBase2 = $vPurDiscountAmtBase2, ".
				  " Purchase_DiscountPer = $vPurDiscountPer, Purchase_VAT = $vPurVat, Purchase_VATBase1 = $vPurVatBase1, Purchase_VATBase2 = $vPurVatBase2, ".
				  " Purchase_Total = $vPurGrossTotal, Purchase_TotalBase1 = $vPurGrossTotalBase1, Purchase_TotalBase2 = $vPurGrossTotalBase2, ".
				  " Purchase_Tax1 = $vPurTax1, Purchase_Tax1Base1 = $vPurTax1B1, Purchase_Tax1Base2 = $vPurTax1B2,  ".
				  " Purchase_Tax2 = $vPurTax2, Purchase_Tax2Base1 = $vPurTax2B1, Purchase_Tax2Base2 = $vPurTax2B2,  ".
				  " Purchase_Tax3 = $vPurTax3, Purchase_Tax3Base1 = $vPurTax3B1, Purchase_Tax3Base2 = $vPurTax3B2,  ".
				  " Purchase_Tax4 = $vPurTax4, Purchase_Tax4Base1 = $vPurTax4B1, Purchase_Tax4Base2 = $vPurTax4B2,  ".
				  " Purchase_Tax5 = $vPurTax5, Purchase_Tax5Base1 = $vPurTax5B1, Purchase_Tax5Base2 = $vPurTax5B2  ".
				  " WHERE Purchase_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;		

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

HERE;
*/

?>