<?php


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

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

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

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

set_time_limit(0);

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$querylog=" select FI_PurchasesVATMod, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(Login_Purchase_Pending,0) As Login_Purchase_Pending, ".
		  " ifnull(FI_PostPurchase,0) as FI_PostPurchase, 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);
}
//fady
$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";
//echo $querycostcent	;		   
$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;

//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
             " ifNull(Module_rawmaterial,0) As Module_RawMaterial, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_SerialNo,0) As Module_SerialNo, ".
			 " ifNull(Module_PurchaseCheckTotal,0) As Module_PurchaseCheckTotal,ifNull(module_purchasezero,0) Module_PurchaseZero,ifNull(Module_Purchase_Pending,0) Module_Purchase_Pending, ifNull(module_locationPurchases,0) As module_locationPurchases ".
			 " , ifNull(Module_PurchasesJvWHT,0) As Module_PurchasesJvWHT, ifNull(Module_ChargesPurchase,0) As Module_ChargesPurchase ".	
			 " 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, PurchaseDefaultType, ifnull(auto_paymentrqst,0) as auto_paymentrqst, ifnull(Restricted_Posting,0) as Restricted_Posting 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"];}   

$SPurId    			= $_GET["SPurId"]; if ($SPurId == ""){$SPurId = $_POST["SPurId"];} 
$SPurDtId			= $_GET["SPurDtId"]; if ($SPurDtId == ""){$SPurDtId = $_POST["SPurDtId"];} 
$SPurVatChkbx 		= $_GET["SPurVatChkbx"]; if ($SPurVatChkbx == ""){$SPurVatChkbx = $_POST["SPurVatChkbx"];} 
$txtPaymentCondidions	= $_POST["txtPaymentCondidions"]; if ($txtPaymentCondidions == ""){$txtPaymentCondidions = $_GET["txtPaymentCondidions"];} 
$txtPurId    		= $_GET["txtPurId"]; if ($txtPurId == ""){$txtPurId = $_POST["txtPurId"];} 
$txtDate 			= $_GET["txtDate"]; if ($txtDate == ""){$txtDate = $_POST["txtDate"];} 
$txtMaturityDate 	= $_GET["txtMaturityDate"]; if ($txtMaturityDate == ""){$txtMaturityDate = $_POST["txtMaturityDate"];} 
$txtInvoiceDate		= $_GET["txtInvoiceDate"]; if ($txtInvoiceDate == ""){$txtInvoiceDate = $_POST["txtInvoiceDate"];} 
$txtSupplier 	   	= $_GET["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_POST["txtSupplier"];} 
$txtSupplier1 	   	= $_GET["txtSupplier1"]; if ($txtSupplier1 == ""){$txtSupplier1 = $_POST["txtSupplier1"];} 
$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"];} 
$txtSrvNo			= $_GET["txtSrvNo"]; if ($txtSrvNo == ""){$txtSrvNo = $_POST["txtSrvNo"];} 
$txtWaybillNo		= $_GET["txtWaybillNo"]; if ($txtWaybillNo == ""){$txtWaybillNo = $_POST["txtWaybillNo"];} 
$txtPurDiscountAmt	= $_GET["txtPurDiscountAmt"]; if ($txtPurDiscountAmt == ""){$txtPurDiscountAmt = $_POST["txtPurDiscountAmt"];} 
$txtPurDiscount		= $_GET["txtPurDiscount"]; if ($txtPurDiscount == ""){$txtPurDiscount = $_POST["txtPurDiscount"];} 
$txtPurVatBase1		= $_GET["txtPurVatBase1"]; if ($txtPurVatBase1 == ""){$txtPurVatBase1 = $_POST["txtPurVatBase1"];} 
$txtTotalAmount		= $_GET["txtTotalAmount"]; if ($txtTotalAmount == ""){$txtTotalAmount = $_POST["txtTotalAmount"];} 

$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"];} 
$PPurSupplier1 	   	= $_GET["PPurSupplier1"]; if ($PPurSupplier1 == ""){$PPurSupplier1 = $_POST["PPurSupplier1"];} 
$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"];} 
$PPurSrvNo			= $_GET["PPurSrvNo"]; if ($PPurSrvNo == ""){$PPurSrvNo = $_POST["PPurSrvNo"];} 
$PPurWaybillNo		= $_GET["PPurWaybillNo"]; if ($PPurWaybillNo == ""){$PPurWaybillNo = $_POST["PPurWaybillNo"];} 

$PPurTotalAmount 	= $_GET["PPurTotalAmount"]; if ($PPurTotalAmount == ""){$PPurTotalAmount = $_POST["PPurTotalAmount"];} 
$PPurDiscount 		= $_GET["PPurDiscount"]; if ($PPurDiscount == ""){$PPurDiscount = $_POST["PPurDiscount"];} 
$PPurDiscountAmt	= $_GET["PPurDiscountAmt"]; if ($PPurDiscountAmt == ""){$PPurDiscountAmt = $_POST["PPurDiscountAmt"];} 
$PPurVatBase1 		= $_GET["PPurVatBase1"]; if ($PPurVatBase1 == ""){$PPurVatBase1 = $_POST["PPurVatBase1"];} 
$PPurVatChkbx 		= $_GET["PPurVatChkbx"]; if ($PPurVatChkbx == ""){$PPurVatChkbx = $_POST["PPurVatChkbx"];} 

$lstWarehouse	= $_GET["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_POST["lstWarehouse"];} 
$lstLocation	= $_GET["lstLocation"]; if ($lstLocation == ""){$lstLocation = $_POST["lstLocation"];} 
$txtItemBarcode	= $_GET["txtItemBarcode"]; if ($txtItemBarcode == ""){$txtItemBarcode = $_POST["txtItemBarcode"];} 
$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"];} 
$txtPurDtPrice	= $_GET["txtPurDtPrice"]; if ($txtPurDtPrice == ""){$txtPurDtPrice = $_POST["txtPurDtPrice"];} 
$txtPurDtDiscount	= $_GET["txtPurDtDiscount"]; if ($txtPurDtDiscount == ""){$txtPurDtDiscount = $_POST["txtPurDtDiscount"];} 
$txtPurDtChargePer	= $_GET["txtPurDtChargePer"]; if ($txtPurDtChargePer == ""){$txtPurDtChargePer = $_POST["txtPurDtChargePer"];} 
$txtPurDtChargeAmt	= $_GET["txtPurDtChargeAmt"]; if ($txtPurDtChargeAmt == ""){$txtPurDtChargeAmt = $_POST["txtPurDtChargeAmt"];} 
$txtProjectCodeDt	= $_GET["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_POST["txtProjectCodeDt"];} 
$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"];} 
$purchasedt_heatno	= $_GET["purchasedt_heatno"]; if ($purchasedt_heatno == ""){$purchasedt_heatno = $_POST["purchasedt_heatno"];} 
$txtPur_Othercharges = $_GET["txtPur_Othercharges"]; if ($txtPur_Othercharges == ""){$txtPur_Othercharges = $_POST["txtPur_Othercharges"];} 
$actionmode = $_GET["actionmode"]; if ($actionmode == ""){$actionmode = $_POST["actionmode"];}
if($txtPur_Othercharges == '') $txtPur_Othercharges = 0;

if($txtPur_Othercharges != ''){
	$Purchase_otherchargesB1 = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $txtPur_Othercharges, $connection);
	$Purchase_otherchargesB2 = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $txtPur_Othercharges, $connection);
} else{
	$Purchase_otherchargesB1 = 0;
	$Purchase_otherchargesB2 = 0;
}
$ajxused = $_GET['ajxused'];

/*
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='SPurId' value='$SPurId'>
<input type='text' name='SPurDtId' value='$SPurDtId'>
<input type='text' name='SPorVatChkbx' value='$SPurVatChkbx'>
HERE;
*/
$message='';


if ($actionmode=='getItemImage' ){
	$queryinfoImg = "select Item_Picture from items where upper(item_code)='".trim(strtoupper($item_code))."'";
	$resinfoImg = mysql_query($queryinfoImg, $connection);
	$rwinfoImg = mysql_fetch_row($resinfoImg);
	
	echo "[BRK]";
	echo $rwinfoImg[0];
	echo "[BRK]"; 
	exit;
}
if ($actionmode=='getItemLocation' ){
	$queryinfoImg = "select CONCAT(item_location.description1, ' - ',item_location.description2, ' - ',item_location.description3) from item_location where  item_code='".trim(strtoupper($item_code))."'";
	$resinfoImg = mysql_query($queryinfoImg, $connection);
	$rwinfoImg = mysql_fetch_row($resinfoImg);
	
	echo "[BRK]";
	echo $rwinfoImg[0];
	echo "[BRK]"; 
	exit;
}

//Submit Record Mode
if ($mode == "getsuppliername"){
	
		$query = "SELECT Ledger_number,Ledger_name 
					FROM Suppliers ";
					
		if($choice==0)
			$query = $query." WHERE Upper(Ledger_number) = Upper('".str_replace('\\','\\\\',$suppliercode)."') ";
		else
			$query = $query." WHERE Upper(Ledger_name) = Upper('".str_replace('\\','\\\\',$suppliercode)."') ";
					
		$result = selectData($connection, $query);
		$suppliercode = $result[0];
		$suppliername = $result[1];
		
		echo"[BRK]";
		echo $suppliercode;
		echo"[BRK]";
		echo $suppliername;
		
 
exit;
}
if ($mode == "checkduplicate" ){

$query = " select  1 from temp_purchasesdt where item_code='".$PItem."' and purchase_id = ".$SSaId;
$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_array($result);
echo $row[0];
exit;
}
else
if ($mode == "submitrecord"  || $mode == "submitrecord-ajax" || $mode == "submitbarcode"){
	//echo $PWHTAcc; exit;
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (!isset($PPurCurr))	  		$PPurCurr = $base1;
	if (empty($PPurCategory))		$PPurCategory = 0;
	if (empty($PPurDiscountAmt))	$PPurDiscountAmt = 0;
	if (empty($PPurDiscount))		$PPurDiscount = 0;
	if (empty($PPurTotalAmount))	$PPurTotalAmount = 0;
			   
			   
	$PPurCostCentCode = "".$PPurCostCentCode;
	$PPurProjectCode = "".$PPurProjectCode;
	
	if ($PPurCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if ($PPurProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'";   

	if (empty($PPurVatChkbx)) $PPurVatChkbx = 0;
	
	//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 = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($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.';
		}
	}
	
	
	//fady
	if (trim(strtoupper($txtItemCode)) != '') {
		$sub_query = "select count(*) From transactionsetup where group_code = (select group_code from items where upper(item_code) = '".strtoupper($txtItemCode)."' ) and journal_type = 'PI'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Group Setup .';
		}
	}
	
	
	
	
	
	if($module_locationPurchases == 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.';
		}
	}
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	if($txtInvoiceDate == '') $txtInvoiceDate = $PPurDate;
	/* if($Module_PurchasesJvWHT == 1){
	if ($PWHTAcct != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtWHTAcc."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}	
	} */
	//Insert Master Table
	if ($SPurId == "" && $ErrorExists == 0){
			
		fbegin();	
		$PPurId = get_nextsequence('Purchase_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, ".
					 " FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
					 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, ".
					 " TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, ".
					 " CustomsDebitAccount, CustomsCreditAccount ".
					 " FROM purchasesetup ";
						 
		$Acc_Result = selectData($connection, $Acc_Query);
		
		
		$Rate_Query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPurCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPurCurr."' )";
		$Rate_Result = selectData($connection, $Rate_Query);
		$vPurchaseRate = $Rate_Result[0];
		if (empty($vPurchaseRate)) $vPurchaseRate = 1;
		
		$Rate_Query1 = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$Rate_Result1 = selectData($connection, $Rate_Query1);
		$vPurchaseRateBase2 = $Rate_Result1[0];
		if (empty($vPurchaseRateBase2)) $vPurchaseRateBase2 = 0;
		
		else if ($PPurCurr == $base1) $vPurchaseRateBase1 = 1;
		else $vPurchaseRateBase1 = 0;
		
		if($costcent_applyvat==0) $PPurVatChkbx=0;
		
		fbegin();
		$query = " INSERT INTO temp_purchases (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_FreightCur, Purchase_CommissionsCur, ".
				 " Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
				 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount, ".
				 " Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, SrvNo, WaybillNo, Purchase_TotalAmount, User_Account, Logged_Code, purchase_paymentcondition,auto_paymentrqst,Purchase_shippedIn,InvoiceDate,Supplier_code1) ".
				 " VALUES ( ".$PPurId.", Null, '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurRemark))."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', ".
				 "          '".$PPurCurr."', $ProjectCode, $CostCentCode, '".$PPurInvoiceNo."', '".insertMySQLDate($PPurMaturityDate)."', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPurDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPurVatChkbx, 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."', '".$PurchaseDefaultType."', 0, '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', ".
				 "          '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$Acc_Result[7]."', '".$Acc_Result[8]."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', ".
				 "          '".$Acc_Result[12]."', '".$Acc_Result[13]."', '".$Acc_Result[14]."', '".$Acc_Result[15]."', '".$Acc_Result[16]."', '".$Acc_Result[17]."', '".$Acc_Result[18]."', ".
				 "          '".$Acc_Result[19]."', '".$Acc_Result[20]."', $vPurchaseRate, $vPurchaseRateBase1, $vPurchaseRateBase2, '".ereg_replace("'", "\'", trim($PPurSrvNo))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPurWaybillNo))."', $PPurTotalAmount, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','".ereg_replace("'", "\'", trim($txtPaymentCondidions))."',$autopaymentrqst, ".
				 " 			'".ereg_replace("'", "\'", trim($PPurShippedIn))."', '".insertMySQLDate($txtInvoiceDate)."'	, '".ereg_replace("'", "\'", trim($PPurSupplier1))."')";
						 
		//echo $query."<br>";exit;
		$result=mysql_query($query,$connection);
			
		//$message = $query;
		if ($result){
			$SPurId = $PPurId;
			fcommit();
			
		}else{
			$PPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SPurId != "" && $SPurDtId == "" && $ErrorExists == 0){
		 if($Module_PurchasesJvWHT == 1){
				if($PWHTChk == 1){
				$queryupdate = "update temp_purchases set Purchase_WHTChk = $PWHTChk, Purchase_WHTAccount = '$PWHTAcct', Purchase_WHTPer = $PWHTPer, Purchase_WHTAmt = $PWHTAmt where Purchase_id = $SPurId";
				//echo $queryupdate; exit;
				$resupdate  = mysql_query($queryupdate, $connection);
				}
			} 
		if (empty($PPurDiscountAmt))
			$PPurDiscountAmt = 0;
		if (empty($PPurDiscount))
			$PPurDiscount = 0;
		
		if($Module_PurchasesJvWHT == 1){
		if (empty($PWHTChk))		$PWHTChk = 0;
		if (empty($PWHTPer))		$PWHTPer = 0;
		if (empty($PWHTAmt))	    $PWHTAmt = 0;
		}
		
		if (empty($txtPurDtPrice))
			$txtPurDtPrice = 0;
		if (empty($txtPurDtDiscount))
		    $txtPurDtDiscount = 0;
		if (empty($txtPurDtQty))
		    $txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
		    $txtPurDtQty2 = 0;      			
		if (empty($txtPurDtChargePer))
		    $txtPurDtChargePer = 0;
		if (empty($txtPurDtChargeAmt))
		    $txtPurDtChargeAmt = 0; 
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
					
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";		
		
		$PPurCostCentCode = "".$PPurCostCentCode;	
		if ($PPurCostCentCode == '')	$CostCentCode = 'Null';
		else	$CostCentCode = "'".$PPurCostCentCode."'";
			
		if (empty($PPurProjectCode))	$ProjectCode = 'Null';
		else	$ProjectCode = "'".$PPurProjectCode."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			$txtCostCentCodeDt = "".$txtCostCentCodeDt;
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}		
		
		
		
		$vPurDtPriceTTC      = 0;
		$vPurDtPriceTTCBase1 = 0;
		$vPurDtPriceTTCBase2 = 0;					
		$vPurDtPrice      	 = 0;
		$vPurDtPriceBase1 	 = 0;
		$vPurDtPriceBase2 	 = 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;
		
		if($txtUnitPrice == '') $txtUnitPrice = 0;
		if($txtFreight == '') $txtFreight = 0;
		
		$WarningMsg = '';
		
		
		//Case Scanning Barcode
		if ($mode == "submitbarcode"){
			$sub_query = " SELECT Item_Code FROM Items WHERE (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."')
						and ifnull(item_active,0) = 1";
			$sub_result = selectData($connection, $sub_query);
			$txtItemCode = $sub_result[0];
			
			if ($txtItemCode == '' || empty($txtItemCode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
			}
			
			if ($ErrorExists == 0){
				$sub_query = " SELECT if($PurchaseTTC = 1, PurchaseDt_PriceTTC, PurchaseDt_Price) FROM PurchasesDt WHERE Item_code = '".$txtItemCode."' And ifNull(PurchaseDt_Price,0) > 0 ".
							 " Order By Purchase_Date Desc Limit 1 ";
				$sub_result = selectData($connection, $sub_query);
				$txtPurDtPrice = $sub_result[0];
				if(empty($txtPurDtPrice)) $txtPurDtPrice = 0;
			}		
		}
		
		$sub_query = " SELECT Count(*) FROM Items WHERE Item_Code = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1";
		$sub_result = selectData($connection, $sub_query);
		
		//Item Code Not Exists Then Check For Barcode
		if ($sub_result[0] == 0) {
			$sub_query = " SELECT Item_Code FROM Items WHERE (item_barcode = '".$txtItemCode."' or item_barcode2 = '".$txtItemCode."' or item_barcode3 = '".$txtItemCode."') and ifnull(item_active,0) = 1";
			$sub_result = selectData($connection, $sub_query);
			$txtItemCode = $sub_result[0];
			
			if ($txtItemCode == '' || empty($txtItemCode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
			}	
		}
		
		//Get Purchase Rates
		$PurRates = GetPurchaseRates($SPurId,$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		
		
		// Case Not Pack Item
		if ($ErrorExists == 0){
		
			$query = " SELECT ifNull(Item_Pack, 0) ".
					 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
			$result   = selectData($connection, $query);
			$ItemPack = $result[0];
		
			//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $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), ifNull(Item_VatType, 1) ".
						" FROM Items WHERE item_Code = '".$txtItemCode."'";
				$result = selectData($connection, $query);
				$item_vat 	   = $result[0];
				$Item_MaxQty   = $result[1];
				$ItemGroupCode = $result[2];
				$ItemProd 	   = $result[3];
				$ItemTTCInc	   = $result[4];
				$ItemUnit      = $result[5];
				$ItemNonStock  = $result[6];
				$ItemVatType   = $result[7];
				//$item_vat = $item_vat/100;
				$tax_flag = 0;
				$notax_flag = 1;
				if ($item_vat > 0){
					$tax_flag = 1;
					$notax_flag = 0;
				}	
				
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
					$vItemUnit2Qty = $txtPurDtQty2;
				}	   
				
				fbegin();
				$txtPurDtId = get_nextsequence('Purchasedt_Id','',$connection);	
				fcommit();

				if ($PurchaseTTC == 1) {
					$vPurDtPriceTTC      = $txtPurDtPrice;
					$vPurDtPriceTTCBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
					$vPurDtPriceTTCBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
					
					//Added 2011/09/26
					if ($PPurVatChkbx == 1)	$vPurDtPrice = ($vPurDtPriceTTC / (1 + $item_vat/100));
					else $vPurDtPrice = $txtPurDtPrice;
						
					$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
					$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
							
				} else	{
					$vPurDtPrice      = $txtPurDtPrice;
					$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
					$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
					
					$vPurDtPriceTTC      = 0;
					$vPurDtPriceTTCBase1 = 0;
					$vPurDtPriceTTCBase2 = 0;
							
				}	
					
				$queryqtyexists = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', Now(), ".$txtPurDtId.", 'PI', '', '') QtyExists From Dual ";
				$result = selectData($connection, $queryqtyexists);
				$vItemQtyExists = 0;
				$vItemQtyExists = $result[0];
				$vItemQtyExists = $vItemQtyExists + $txtPurDtQty; 
					
				if ($vItemQtyExists > $Item_MaxQty)
					$WarningMsg = 'Quantity ('.$vItemQtyExists.') exceeds max quantity, Max= '.$Item_MaxQty.' for Item= '.$txtItemCode;
						
				
				// Calculation For Detail Discount Amount
				$vPurDtDiscAmt       = (($vPurDtPrice*$txtPurDtQty) - ($vPurDtPrice*$txtPurDtQty*$txtPurDtDiscount/100))*$PPurDiscount;
				$vPurDtDiscAmtBase1  = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
				$vPurDtDiscAmtBase2  = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
					
				$txtPurDtChargeAmtB1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $txtPurDtChargeAmt, $connection);
				$txtPurDtChargeAmtB2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $txtPurDtChargeAmt, $connection);


				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 = '".$PPurSupplier."'";
												 
					$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 = '".$txtItemCode."'";
												 
					$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,  ".
						 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
						 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
						 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport ".
						 " FROM purchasesetup ";
							 
				$result = selectData($connection, $query);
					
				$vPurStpDirectStkDbt    = $result[0];
				$vPurStpDirectStkCrd    = $result[1];
				$vPurStpDirectStkCur    = $result[2];	
				$vPurStpVatAcc          = $result[3];	
				$vPurStpDebitAcc        = $result[4];	
				$vPurStpVatNonStockAcc  = $result[5];	
				$vPurStpVatAcc2         = $result[6];
				$vPurStpVatAcc3         = $result[7];
				$vPurStpVatNonStockAcc2 = $result[8];
				$vPurStpVatNonStockAcc3 = $result[9];
				$vPurStpDebitAcc2       = $result[10];
				$vPurStpDebitAcc3       = $result[11];
				$vPurStpDebitVatAcc     = $result[12];
				$vPurStpDebitVatAcc2    = $result[13];
				$vPurStpDebitVatAcc3    = $result[14];
				$vPurStpDebitNonStockAcc  	 = $result[15];
				$vPurStpDebitNonStockAcc2 	 = $result[16];
				$vPurStpDebitNonStockAcc3 	 = $result[17];
				$vPurStpDebitVatNonStockAcc  = $result[18];
				$vPurStpDebitVatNonStockAcc2 = $result[19];
				$vPurStpDebitVatNonStockAcc3 = $result[20];
				$vPurStpDebitExportAcc	 	 = $result[21];
				
				$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number =  '".ereg_replace("'", "\'", trim($PPurSupplier))."' ";	
				$resexp = mysql_query($queryexp,$connection);
				$rwexp = mysql_fetch_row($resexp);
				$supplierexp = $rwexp[0];
	
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export, ".
						 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
						 " 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];
				$vTransExport			= $result[10];
				$vSaDtWasteDbt 			= $result[11]; 
				$vSaDtWasteCrd 			= $result[12]; 
				$vSaDtExportAcc 		= $result[13]; 
					
				if ($Module_RawMaterial == 1) {
					$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vPurDtDirectStkCur = $vTranStpDirectStkCur;
					$vPurDtVatAcc       = $vTranStpVatAcc;
										
					if ($item_vat > 0 && $PPurVatChkbx == 1) {
						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;
						}
					}	
					if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 
				} 
				else {
					$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
					$vPurDtDirectStkCur = $vPurStpDirectStkCur;	

					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}	
				
					if ($item_vat > 0 && $PPurVatChkbx == 1) {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
						}
					}	
					else {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
						}						
					}
					if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 					
				}
				
				
				
				$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkDbt."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtDirectStkDbt = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkCrd."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtDirectStkCrd = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteDbt."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteCrd."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
								
				fbegin();
				$query = " INSERT INTO temp_purchasesdt (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_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
						 " Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code,purchasedt_heatno,purchasedt_unitPrice,purchasedt_freight,purchasedt_cost ";
				if($lstLocation != '')
				$query = $query." , Location_code ";
				$query = $query." ) ";
				$query = $query." VALUES ( ".$txtPurDtId.", ".$PPurId.", '".$PPurCurr."', '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', 'PI',  ".
						 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".trim(strtoupper($txtItemCode))."', $txtPurDtQty, $vPurDtPrice, $vPurDtPriceBase1, $vPurDtPriceBase2, $txtPurDtDiscount, $vPurDtDiscAmt, $vPurDtDiscAmtBase1, $vPurDtDiscAmtBase2, '$item_vat', ".
						 "          $txtPurDtVolume, '".ereg_replace("'", "\'", trim($txtPurDtRemark))."' ,  '".$PPurInvoiceNo."',  Null, $txtPurDtChargePer, $txtPurDtChargeAmt, $txtPurDtChargeAmtB1, $txtPurDtChargeAmtB2, ".
						 "          $vPurDtPriceTTC, $vPurDtPriceTTCBase1, $vPurDtPriceTTCBase2, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
						 "          $vPurDtTax1, $vPurDtTax2, $vPurDtTax3, $vPurDtTax4, $vPurDtTax5, $vItemUnitCoef, $vItemUnit2Qty, $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', '".$_SESSION['useraccount']."' , '".$purchasedt_heatno."', ".
						 " $txtUnitPrice,$txtFreight,'$txtporcost' ";
				//$message  = $query; 
				//	frollback();
				if($lstLocation != '')
				$query = $query." , '".$lstLocation."' ";
				$query = $query." ) ";			
				//echo $query."<br>";exit;				
				$result=mysql_query($query,$connection);
								
					
				if ($result){
					fcommit();
				}else{
					$txtPurDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}				
				
			}	// End Case Not Pack Item
			else {
				
					fbegin();
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
								   
					$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
					while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
						$vItemCodePacked = $rowspackdt[0];
						$vItemCode = $rowspackdt[1];
						$vPackDtQty = $rowspackdt[2];
						$vPackDtCostPer = $rowspackdt[3];
						
						fbegin();
						$vPurDtId = get_nextsequence('Purchasedt_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), ifNull(Item_VatType, 1) ".
								 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$item_vat	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd 	   = $result[3];
						$ItemTTCInc    = $result[4];
						$ItemUnit  	   = $result[5];
						$ItemNonStock  = $result[6];
						$ItemVatType   = $result[7];
						
						//$item_vat = $item_vat/100;
						$tax_flag = 0;
						$notax_flag = 1;
						if ($item_vat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}	
						
						
						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
						if ($Module_DoubleUnit == 1) {
							$vItemUnitCoef = $ItemUnit;
							
							if ($Module_Unit1Method == 1)
								$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
							else	
								$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
						}
						
						$vPurDtPriceTTC      = 0;
						$vPurDtPriceTTCBase1 = 0;
						$vPurDtPriceTTCBase2 = 0;					
						$vPurDtPrice      	 = 0;
						$vPurDtPriceBase1 	 = 0;
						$vPurDtPriceBase2 	 = 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;

						
						if ($PurchaseTTC == 1) {
							$vPurDtPriceTTC      = (($txtPurDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vPurDtPriceTTCBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
							$vPurDtPriceTTCBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
							
							//Added 2011/09/26
							if ($PPurVatChkbx == 1)	$vPurDtPrice = ($vPurDtPriceTTC / (1 + $item_vat/100));
							else $vPurDtPrice = $vPurDtPriceTTC;
							
							$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
							$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
							
						} else	{
							$vPurDtPrice      = (($txtPurDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
							$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
							
							$vPurDtPriceTTC      = 0;
							$vPurDtPriceTTCBase1 = 0;
							$vPurDtPriceTTCBase2 = 0;
							
						}
						
						
					
						$queryqtyexists = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', Now(), ".$vPurDtId.", 'PI', '', '') QtyExists From Dual ";
						$result = selectData($connection, $queryqtyexists);
						$vItemQtyExists = 0;
						$vItemQtyExists = $result[0];
						$vItemQtyExists = $vItemQtyExists + $vPurDtQty; 
						
						if ($vItemQtyExists > $Item_MaxQty)
							$WarningMsg = 'Quantity ('.$vItemQtyExists.') exceeds max quantity, Max= '.$Item_MaxQty.' for Item= '.$vItemCode;
						
						
						// Calculation For Detail Discount Amount
						$vPurDtDiscAmt       = (($vPurDtPrice*$vPurDtQty) - ($vPurDtPrice*$vPurDtQty*$txtPurDtDiscount/100))*$PPurDiscount;
						$vPurDtDiscAmtBase1  = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
						$vPurDtDiscAmtBase2  = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
						
						$vPurDtChargeAmt   = $txtPurDtChargeAmt;
						$vPurDtChargeAmtB1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtChargeAmt, $connection);
						$vPurDtChargeAmtB2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtChargeAmt, $connection);
						


						
						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 = '".$PPurSupplier."'";
														 
							$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 = '".$vItemCode."'";
														 
							$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,  ".
								 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
								 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
								 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport ".
								 " FROM purchasesetup ";
								 
						$result = selectData($connection, $query);
						
						$vPurStpDirectStkDbt    = $result[0];
						$vPurStpDirectStkCrd    = $result[1];
						$vPurStpDirectStkCur    = $result[2];	
						$vPurStpVatAcc          = $result[3];	
						$vPurStpDebitAcc        = $result[4];	
						$vPurStpVatNonStockAcc  = $result[5];
						$vPurStpVatAcc2         = $result[6];
						$vPurStpVatAcc3         = $result[7];
						$vPurStpVatNonStockAcc2 = $result[8];
						$vPurStpVatNonStockAcc3 = $result[9];
						$vPurStpDebitAcc2       = $result[10];
						$vPurStpDebitAcc3       = $result[11];
						$vPurStpDebitVatAcc     = $result[12];
						$vPurStpDebitVatAcc2    = $result[13];
						$vPurStpDebitVatAcc3    = $result[14];
						$vPurStpDebitNonStockAcc  	 = $result[15];
						$vPurStpDebitNonStockAcc2 	 = $result[16];
						$vPurStpDebitNonStockAcc3 	 = $result[17];
						$vPurStpDebitVatNonStockAcc  = $result[18];
						$vPurStpDebitVatNonStockAcc2 = $result[19];
						$vPurStpDebitVatNonStockAcc3 = $result[20];
						$vPurStpDebitExportAcc		 = $result[21];
						
						$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number =  '".ereg_replace("'", "\'", trim($PPurSupplier))."' ";	
						$resexp = mysql_query($queryexp,$connection);
						$rwexp = mysql_fetch_row($resexp);
						$supplierexp = $rwexp[0]; 
						
						$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
								 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export, ".
								 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
								 " 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];
						$vTransExport			= $result[10];
						$vSaDtWasteDbt 			= $result[11]; 
						$vSaDtWasteCrd 			= $result[12]; 
						$vSaDtExportAcc 		= $result[13]; 
						
						if ($Module_RawMaterial == 1) {
							$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vPurDtDirectStkCur = $vTranStpDirectStkCur;
							$vPurDtVatAcc       = $vTranStpVatAcc;
							
							if ($item_vat > 0 && $PPurVatChkbx == 1) {
								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;
								}
							}
							if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 
						} 
						else {
							$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
							$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
							$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
								
							if ($ItemNonStock == 1)	{
								if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
								else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
								else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
							}	
							else {
								if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
								else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
								else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
							}	
						
							if ($item_vat > 0 && $PPurVatChkbx == 1) {
								if ($ItemNonStock == 1)	{
									if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
									else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
									else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
								}	
								else {
									if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
									else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
									else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
								}
							}	
							else {
								if ($ItemNonStock == 1)	{
									if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
									else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
									else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
								}	
								else {
									if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
									else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
									else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
								}						
							}
							if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 		
						}
						
											
						$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
						
						$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkDbt."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vPurDtDirectStkDbt = $sub_resultVat[0];
						
						$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkCrd."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vPurDtDirectStkCrd = $sub_resultVat[0];
						
						$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteDbt."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
						
						$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteCrd."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
						
						$query = " INSERT INTO temp_purchasesdt (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_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Item_UnitCoef, Item_Unit2Qty,purchasedt_freight,purchasedt_cost, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code ) ".
								 " VALUES ( ".$vPurDtId.", ".$PPurId.", '".$PPurCurr."', '".insertMySQLDate($PPurDate)."', '".ereg_replace("\'", "''", trim($PPurSupplier))."', 'PI', ".
								 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".trim(strtoupper($vItemCode))."',  $vPurDtQty, $vPurDtPrice, $vPurDtPriceBase1, $vPurDtPriceBase2, $txtPurDtDiscount, $vPurDtDiscAmt, $vPurDtDiscAmtBase1, $vPurDtDiscAmtBase2, $item_vat, ".
								 "          $txtPurDtVolume, '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', '".$PPurInvoiceNo."',  '".$vItemCodePacked."', $txtPurDtQty, $txtPurDtChargePer, $vPurDtChargeAmt, $vPurDtChargeAmtB1, $vPurDtChargeAmtB2, ".
								 "          $vPurDtPriceTTC, $vPurDtPriceTTCBase1, $vPurDtPriceTTCBase2, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
								 "          $vPurDtTax1, $vPurDtTax2, $vPurDtTax3, $vPurDtTax4, $vPurDtTax5, $vItemUnitCoef, $vItemUnit2Qty,'$txtFreight','$txtporcost', $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', '".$_SESSION['useraccount']."' ) ";			
								 
						$result=mysql_query($query,$connection);
							//$message  = $query; 
						//frollback();	
						//echo $query;
					} // End Loop Of Packdt
					
						
					
					if ($result){
						fcommit();
					}else{
						$txtPurDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}	
				
				
			} // End CasePack Item
		
}
		
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $PPurDate, $PPurVatChkbx, $PPurDiscount, 0, $PPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
		
	} // End Case Insert In Detail Tables

} 


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

	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if ($SPurId != "" && $SPurDtId != "" && $ErrorExists == 0) {
		
		if (empty($PPurDiscountAmt))
			$PPurDiscountAmt = 0;
		if (empty($PPurDiscount))
			$PPurDiscount = 0;
			
		if (empty($txtPurDtPrice))
			$txtPurDtPrice = 0;
		if (empty($txtPurDtDiscount))
		    $txtPurDtDiscount = 0;
		if (empty($txtPurDtQty))
		    $txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
		    $txtPurDtQty2 = 0;	
		if (empty($txtPurDtChargePer))
		    $txtPurDtChargePer = 0;
		if (empty($txtPurDtChargeAmt))
		    $txtPurDtChargeAmt = 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 ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}
		
		if($txtUnitPrice == '') $txtUnitPrice = 0;
		if($txtFreight == '') $txtFreight = 0;
		
		if($auto_paymentrqst == 1){
		$queryup = "update temp_purchases set auto_paymentrqst = $autopaymentrqst where purchase_id = $SPurId";
		$resup = mysql_query($queryup,$connection);
		}
		
		$query = "SELECT Item_Vat, ifNull(Item_WithSerialNo,0) FROM Items WHERE item_Code = '".$txtItemCode."'";
		$result = selectData($connection, $query);
		$item_vat = $result[0];
		$ItemSerialNo = $result[1];
		//$item_vat = $item_vat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
			
		$vPurDiscount = 0;
		$vPurDiscountAmt = 0;
		$WarningMsg = '';
		$vPurSuppCode = '';
		
		$vPurDtPriceTTC      = 0;
		$vPurDtPriceTTCBase1 = 0;
		$vPurDtPriceTTCBase2 = 0;					
		$vPurDtPrice      	 = 0;
		$vPurDtPriceBase1 	 = 0;
		$vPurDtPriceBase2 	 = 0;
		$vPurDtDiscAmt       = 0;
		$vPurDtDiscAmtBase1  = 0;
		$vPurDtDiscAmtBase2  = 0;
				
		
		$vSupTax1 = 0;
		$vSupTax2 = 0;
		$vSupTax3 = 0;
		$vSupTax4 = 0;
		$vSupTax5 = 0;
		$vPurDtTax1 = 0;
		$vPurDtTax2 = 0;
		$vPurDtTax3 = 0;
		$vPurDtTax4 = 0;
		$vPurDtTax5 = 0;
		
			
		$query = " Select Currency_code, ifNull(Purchase_Taxable,0), ifNull(Purchase_NoneTaxable,0), ifNull(Purchase_DiscountPer,0), Supplier_code ".
				 " From Temp_Purchases As Purchases ".
				 " Where Purchase_ID = ".$SPurId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
				 
		
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);
		
		$vPurCurr        = $rows[0];
		//$vPurTaxable     = $rows[1];
		//$vPurNoneTaxable = $rows[2];
		$vPurDiscount    = $rows[3];
		$vPurSuppCode    = $rows[4];
		
		
		//Get Purchase Rates
		$PurRates = GetPurchaseRates($SPurId,$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		
		
		
		if ($PurchaseTTC == 1) {
			$vPurDtPriceTTC      = $txtPurDtPrice;
			$vPurDtPriceTTCBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
			$vPurDtPriceTTCBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
				
			//Added 2011/09/26
			if ($PPurVatChkbx == 1)	$vPurDtPrice = ($vPurDtPriceTTC / (1 + $item_vat/100));
			else $vPurDtPrice = $txtPurDtPrice;
			
			$vPurDtPriceBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
			$vPurDtPriceBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
			
		} else	{
			$vPurDtPrice      = $txtPurDtPrice;
			$vPurDtPriceBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
			$vPurDtPriceBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
		
			$vPurDtPriceTTC      = 0;
			$vPurDtPriceTTCBase1 = 0;
			$vPurDtPriceTTCBase2 = 0;
			
		}	
		
            
		// Calculation For Detail Discount Amount
		$vPurDtDiscAmt       = (($vPurDtPrice*$txtPurDtQty) - ($vPurDtPrice*$txtPurDtQty*$txtPurDtDiscount/100))*$vPurDiscount;
		$vPurDtDiscAmtBase1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
		$vPurDtDiscAmtBase2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
				
		$txtPurDtChargeAmtB1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $txtPurDtChargeAmt, $connection);
		$txtPurDtChargeAmtB2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $txtPurDtChargeAmt, $connection);


		//Check PurchasesDt If Has Serial No Used
		$SerialUsedExists = 0;
		if ($Module_SerialNo == 1 && $ItemSerialNo == 1) {
			$sub_query = " Select Count(SerialNo_Code) From Purchasesserialno  ".
						 " Where Purchasesserialno.PurchaseDt_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 PurchasesDt ".
						 " 		Where PurchasesDt.PurchaseDt_ID = '".$SPurDtId."' ".
						 " ) Q1 Where QtyExists < 0 ";
	 
			$sub_result = selectData($connection, $sub_query);
			$ItemQtyExists = $sub_result[0];
			
			if ($ItemQtyExists > 0 ){
				$NegativeQtyExists = 1;
			}
		
		}
						
		fbegin();	
					
		if ($SerialUsedExists == 0 && $NegativeQtyExists == 0)	{
			$query = " UPDATE Temp_Purchasesserialno SET ".
					 " Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."' ".
					 " WHERE PurchaseDt_id  = ".$SPurDtId.
					 " AND Journal_Type = 'PI' ";
							 
			$result=mysql_query($query,$connection);
		}	
							
		$query = " UPDATE temp_purchasesdt SET  ".
		         " PurchaseDt_Quantity = $txtPurDtQty, Item_Unit2Qty = $txtPurDtQty2, PurchaseDt_Price = $vPurDtPrice, ".
				 " PurchaseDt_PriceBase1 = $vPurDtPriceBase1, PurchaseDt_PriceBase2 = $vPurDtPriceBase2, PurchaseDt_DiscountPer = $txtPurDtDiscount, ".
				 " PurchaseDt_PriceTTC = $vPurDtPriceTTC, PurchaseDt_PriceTTCbase1 = $vPurDtPriceTTCBase1, PurchaseDt_PriceTTCbase2 = $vPurDtPriceTTCBase2,  ".
				 " Item_VAT = '$item_vat', PurchaseDt_Volume = $txtPurDtVolume, Purchasedt_Remark = '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', ".
                 " PurchaseDt_ChargePer = $txtPurDtChargePer, PurchaseDt_ChargesAmnt = $txtPurDtChargeAmt, PurchaseDt_ChargesAmntB1 = $txtPurDtChargeAmtB1, ".
				 " PurchaseDt_ChargesAmntB2 = $txtPurDtChargeAmtB2, PurchaseDt_DiscountAmount = $vPurDtDiscAmt, PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, ".
				 " PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2, PurchaseDt_ExpireDate = $vPurDtExpireDate, PurchaseDt_BatchNo = '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."' ".
				 " ,Purchasedt_heatno = '".$purchasedt_heatno."', purchasedt_unitPrice=$txtUnitPrice, purchasedt_freight=$txtFreight,purchasedt_cost = '$txtporcost', item_Code = '".trim(strtoupper($txtItemCode))."'";
				 
		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCent_Code = $CostCentCodeDt ";
			
		//Edit Item Code/Warehouse If Item Has No Serial Used
		if ($SerialUsedExists == 0 && $NegativeQtyExists == 0){
			$query = $query.", Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."' ";
			if($lstLocation != '') $query = $query.", Location_Code = '".$lstLocation."' ";
		}
		$query = $query." Where PurchaseDt_ID = ".$SPurDtId;
		

			//$message  = $query; 
			//frollback();				 
		//echo $query; exit;
		$result=mysql_query($query,$connection);
		if ($result){
			fcommit();
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $PPurDate, $PPurVatChkbx, $vPurDiscount, 0, $PPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'U', $connection);
			$message  = $message . $CalculateResult;

		}else{
			$message  = mysql_error(); 
			frollback();
		}				
			
	}
}
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$message  = '';
	
	//Check Each PurchaseDt If Has RelatedId and Type PR
	$query = " Select Count(PurchasesDt.PurchaseDt_id), Purchases.Purchase_reference ".
			 " From PurchasesDt, PurchasesDt As PurchasesDt1, Purchases ".
			 " Where PurchasesDt.PurchaseDt_ID = ".$SPurDtId.
			 " And PurchasesDt1.Journal_Type = 'PR' ".
			 " And PurchasesDt1.RelatedDt_Id = PurchasesDt.PurchaseDt_id ".
			 " And PurchasesDt1.Purchase_id = Purchases.Purchase_id ".
			 " Group By Purchases.Purchase_reference ";

	$result = selectData($connection, $query);
	$PurReturnExists = $result[0];
		
	if ($PurReturnExists > 0 ){
		$message  = 'Delete not allowed, return purchase exists reference= '.$result[1];
		$AllowDelete = 1;
	}
	
	
	
	if ($AllowDelete == 0) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_PurchasesDt As PurchasesDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = PurchasesDt.PurchaseDt_Id ".
				 " Where PurchasesDt.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 && $Module_NegativeQuantity == 0  && $Login_negativeQty == 1) {
		//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 PurchasesDt ".
				 " Where PurchasesDt.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) {

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

		//Get Purchase Rates
		$PurRates = GetPurchaseRates($SPurId,$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		
						
		$ErrorExists    = 0;

				
		$querypack = " SELECT PurchasesDt.Item_CodePacked, PurchasesDt.Item_code ".
					 " FROM Temp_PurchasesDt As PurchasesDt ".
					 " Where PurchasesDt.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 PurchaseDt_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_PurchasesDt ".
					 " 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, PurchasesDt.Item_CodePacked, PurchasesDt.Item_code  ".
						  " From Temp_PurchasesDt As PurchasesDt  ".
						  " Where PurchasesDt.Purchase_ID = ".$SPurId.
						  " And PurchasesDt.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 PurchaseDt_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_PurchasesDt ".
						 " 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
		
		if ( $ErrorExists == 0 ){ 
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $txtDate, $SPurVatChkbx, $txtPurDiscount, 0, $txtPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'D', $connection);
			$message  = $message . $CalculateResult;

		} // End If No Error Exists 
		
	
	} // End If No Constraints Found On Delete
	
	$txtPurId = $SPurId;
}

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

	$AllowDelete = 0;
	$message  = '';
	
	//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);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(Purchase_Date,'%d/%m/%Y') FROM Purchases WHERE Purchase_id = ".$SPurId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
		if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
	
	
	
	//Check If Purchase Is Posted
	$query = "SELECT ifNull(Purchase_Posted,0) As PurchasePosted FROM Purchases WHERE Purchase_id = ".$SPurId;
	$result = selectData($connection, $query);
	$PurPosted = $result[0];
	
	if ($PurPosted == 1 ){
		$message  = 'Delete not allowed, purchase posted.';
		$AllowDelete = 1;
	}
	
	if ($AllowDelete == 0) {
		//Check Each PurchaseDt If Has RelatedId and Type PR
		$query = " Select Count(PurchasesDt.PurchaseDt_id) ".
				 " From PurchasesDt, PurchasesDt As PurchasesDt1 ".
				 " Where PurchasesDt.Purchase_id = ".$SPurId.
				 " And PurchasesDt1.Journal_Type = 'PR' ".
				 " And PurchasesDt1.RelatedDt_Id = PurchasesDt.PurchaseDt_id ";

		$result = selectData($connection, $query);
		$PurReturnExists = $result[0];
		
		if ($PurReturnExists > 0 ){
			$message  = 'Delete not allowed, return purchase exists.';
			$AllowDelete = 1;
		}
	
	}
	
	if ($AllowDelete == 0) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From PurchasesDt ".
				 " Inner Join Purchasesserialno on Purchasesserialno.PurchaseDt_Id = PurchasesDt.PurchaseDt_Id ".
				 " Where PurchasesDt.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 = 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 PurchasesDt ".
				 " Where PurchasesDt.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 = 1;
		}
	
	}
	


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

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

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

	// Delete From TempPucrhaseCharges For Selected Record
	$query = " DELETE FROM Temp_PurchaseCharges ".
			 " WHERE Purchase_id = ".$SPurId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempPucrhasesSerialNo For Selected Record
		$query = " DELETE FROM Temp_Purchasesserialno ".
				 " WHERE PurchaseDt_id In (Select PurchaseDt_id From Temp_PurchasesDt 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_PurchasesDt ".
				 " WHERE Purchase_id = ".$SPurId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
		if (updateData($connection, $query, true)) {
			// Delete From TempPucrhases For Selected Record
			$query = " DELETE FROM Temp_Purchases ".
					 " WHERE Purchase_id = ".$SPurId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
		}
		else
			$message  = mysql_error(); 	
	}
	else
        $message  = mysql_error(); 

}

else if($mode == 'editheader' && $SPurId != ''){
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (!isset($PPurCurr))	  		$PPurCurr = $base1;
	if (empty($PPurCategory))		$PPurCategory = 0;	   
	if (empty($PPurTotalAmount))	$PPurTotalAmount = 0;		   
	
	$PPurCostCentCode = "".$PPurCostCentCode;	
	if ($PPurCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if (empty($PPurProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'";   

	if (empty($PPurVatChkbx)) $PPurVatChkbx = 0;
	
	//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 ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";// $message = $sub_query;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if($module_locationPurchases == 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($ErrorExists == 0){
		fbegin();
		$query = " update temp_purchases set Purchase_Date = '".insertMySQLDate($PPurDate)."', Purchase_Remark = '".ereg_replace("'", "\'", trim($PPurRemark))."', Supplier_code =  '".ereg_replace("'", "\'", trim($PPurSupplier))."'".
				 " , Supplier_code1 =  '".ereg_replace("'", "\'", trim($PPurSupplier1))."', ".
				 " Currency_Code = '".$PPurCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Purchase_InvoiceNo = '".$PPurInvoiceNo."', Journaldt_valuedate = '".insertMySQLDate($PPurMaturityDate)."', ".
				 " SrvNo = '".ereg_replace("'", "\'", trim($PPurSrvNo))."', WaybillNo = '".ereg_replace("'", "\'", trim($PPurWaybillNo))."', purchase_paymentcondition = '".ereg_replace("'", "\'", trim($txtPaymentCondidions))."' ".
				 " ,Purchase_shippedIn = '".ereg_replace("'", "\'", trim($PPurShippedIn))."',InvoiceDate =  '".insertMySQLDate($txtInvoiceDate)."', Purchase_TotalAmount = $PPurTotalAmount ".
				 " where purchase_id = $SPurId ";
						 
		//$message = $query;
		$result=mysql_query($query,$connection);
			
		//$message = $query;
		if ($result){
			fcommit();
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}
	}
}
//Search Mode	
else if($mainmode == "search" && $SPurId != ''){
	
	$ErrorExists = 0;
	$message  = '';
	
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_purchases (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_FreightCur, Purchase_CommissionsCur, ".
			 " Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
			 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount, ".
			 " Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, SrvNo, WaybillNo, Purchase_TotalAmount, Purchase_VatCharges, Purchase_VatChargesBase1, Purchase_VatChargesBase2, User_Account, Logged_Code, Purchase_paymentcondition, ".
			 " Purchase_WHTChk, Purchase_WHTAccount, Purchase_WHTPer,Purchase_WHTAmt, Purchase_WHTAmt1, Purchase_WHTAmt2, Purchase_othercharges, Purchase_otherchargesB1, Purchase_otherchargesB2,auto_paymentrqst,Purchase_shippedIn, InvoiceDate, supplier_code1)".
			 " 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_FreightCur, Purchase_CommissionsCur, ".
			 " Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
			 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount, ".
			 " Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, SrvNo, WaybillNo, Purchase_TotalAmount, Purchase_VatCharges, Purchase_VatChargesBase1, Purchase_VatChargesBase2, User_Account, '".$_SESSION['useraccount']."', Purchase_paymentcondition, ".
			 " Purchase_WHTChk, Purchase_WHTAccount, Purchase_WHTPer,Purchase_WHTAmt, Purchase_WHTAmt1, Purchase_WHTAmt2, Purchase_othercharges, Purchase_otherchargesB1, Purchase_otherchargesB2, auto_paymentrqst,Purchase_shippedIn, InvoiceDate , supplier_code1".
			 " FROM Purchases ".
			 " WHERE Purchase_id = ".$SPurId;
	//echo $query;exit;
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}
			
	//echo $message.$query; exit;				 
		
	if ($ErrorExists == 0) {
		
		$query = " INSERT INTO temp_purchasesdt (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, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code, purchasedt_heatno,RelatedDt_Id, Location_code, purchasedt_unitPrice, purchasedt_freight,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, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, '".$_SESSION['useraccount']."', purchasedt_heatno,RelatedDt_Id  ".
				 " ,Location_code, purchasedt_unitPrice, purchasedt_freight,purchasedt_cost ".
				 " FROM Purchasesdt ".
				 " WHERE Purchase_id = ".$SPurId;
		//echo $query;exit;
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 			

		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_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.Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$_SESSION['useraccount']."' ".
				 " FROM Purchasesserialno ".
				 " Inner Join Temp_PurchasesDt on Purchasesserialno.PurchaseDt_id = Temp_PurchasesDt.PurchaseDt_id ".
				 //" WHERE PurchaseDt_id In ( Select PurchaseDt_id From Temp_PurchasesDt Where Purchase_id = ".$SPurId." ) ". 
				 " WHERE Purchase_id = ".$SPurId.
				 " AND Purchasesserialno.Journal_Type = 'PI' ";
				 
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 		

		
		$query = " INSERT INTO temp_purchasecharges (Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, Logged_Code, purchasecharges_remark, ChargesCostcent_code ) ".
				 " SELECT Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, '".$_SESSION['useraccount']."', purchasecharges_remark, ChargesCostcent_code ".
				 " FROM Purchasecharges ".
				 " WHERE Purchase_id = ".$SPurId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 
		  
	}  

}

//submit items price
else if($mainmode == "updateitemprice" && $SPurId != ''){

$PurRates = GetPurchaseRates($SPurId,$connection);
$vRate   = $PurRates[0];
$vRateB1 = $PurRates[1];
$vRateB2 = $PurRates[2];

$query = " Select Currency_code, ifNull(Purchase_Taxable,0), ifNull(Purchase_NoneTaxable,0), ifNull(Purchase_DiscountPer,0), Supplier_code, ifnull(Purchase_VatChkbx,0) ".
				 " From Temp_Purchases As Purchases ".
				 " Where Purchase_ID = ".$SPurId;
		
$result=mysql_query($query,$connection) or die(mysql_error());
$rows=mysql_fetch_array($result);

$vPurCurr        = $rows[0];
$vPurDiscount    = $rows[3];
$vPurSuppCode    = $rows[4];
$PPurVatChkbx    = $rows[5];

$i=0;	
$query = "select temp_purchasesdt.item_code,purchasedt_id, temp_purchasesdt.currency_code, Purchase_Date,PurchaseDt_Quantity, ifnull(PurchaseDt_DiscountPer,0)
		from temp_purchasesdt
		inner join items on items.item_code = temp_purchasesdt.item_code
		where purchase_id=$SPurId
		order by temp_purchasesdt.item_code"; //echo $query;exit;
$res = mysql_query($query,$connection);
 while($rows = mysql_fetch_row($res)){
	
	$txtItemCode 	= $rows[0];
	$txtpurnewprice	= 'price'.$i;
	$txtpurnewcost	= 'cost'.$i;
	$txtpurnewfreight	= 'freight'.$i;
	$PPurDate 		= $rows[3];
	$vPurCurr		= $rows[2];
	$txtPurDtQty	= $rows[4];
	$txtPurDtDiscount = $rows[5];
	
	$query = "SELECT Item_Vat, ifNull(Item_WithSerialNo,0) FROM Items WHERE item_Code = '".$txtItemCode."'";
	$result = selectData($connection, $query);
	$item_vat = $result[0];
	$ItemSerialNo = $result[1];
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}
	if($$txtpurnewprice != '') {
	if ($PurchaseTTC == 1) {
		$vPurDtPriceTTC      = $$txtpurnewprice;
		$vPurDtPriceTTCBase1 = ConvertCurrencyRate($vPurCurr, $base1, $PPurDate, $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
		$vPurDtPriceTTCBase2 = ConvertCurrencyRate($vPurCurr, $base2, $PPurDate, $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
			
		if ($PPurVatChkbx == 1)	$vPurDtPrice = ($vPurDtPriceTTC / (1 + $item_vat/100));
		else $vPurDtPrice = $$txtpurnewprice;
		
		$vPurDtPriceBase1 = ConvertCurrencyRate($vPurCurr, $base1, $PPurDate, $vRate, $vRateB1, $vPurDtPrice, $connection);
		$vPurDtPriceBase2 = ConvertCurrencyRate($vPurCurr, $base2, $PPurDate, $vRate, $vRateB2, $vPurDtPrice, $connection);
		
	} else	{
		$vPurDtPrice      = $$txtpurnewprice;
		$vPurDtPriceBase1 = ConvertCurrencyRate($vPurCurr, $base1, $PPurDate, $vRate, $vRateB1, $vPurDtPrice, $connection);
		$vPurDtPriceBase2 = ConvertCurrencyRate($vPurCurr, $base2, $PPurDate, $vRate, $vRateB2, $vPurDtPrice, $connection);
	
		$vPurDtPriceTTC      = 0;
		$vPurDtPriceTTCBase1 = 0;
		$vPurDtPriceTTCBase2 = 0;
		
	}	
	
	$vPurDtDiscAmt       = (($vPurDtPrice*$txtPurDtQty) - ($vPurDtPrice*$txtPurDtQty*$txtPurDtDiscount/100))*$vPurDiscount;
	$vPurDtDiscAmtBase1  = ConvertCurrencyRate($vPurCurr, $base1, $PPurDate, $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
	$vPurDtDiscAmtBase2  = ConvertCurrencyRate($vPurCurr, $base2, $PPurDate, $vRate, $vRateB2, $vPurDtDiscAmt, $connection);

	$queryup = " update temp_purchasesdt set PurchaseDt_Price = $vPurDtPrice, PurchaseDt_PriceBase1 = $vPurDtPriceBase1, PurchaseDt_PriceBase2 = $vPurDtPriceBase2, ".
			   " PurchaseDt_PriceTTC = $vPurDtPriceTTC, PurchaseDt_PriceTTCbase1 = $vPurDtPriceTTCBase1, PurchaseDt_PriceTTCbase2 = $vPurDtPriceTTCBase2,  ".
			   " PurchaseDt_DiscountAmount = $vPurDtDiscAmt, PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1,PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2, ".
			   " purchasedt_freight = '".$$txtpurnewfreight."' , purchasedt_cost = '".$$txtpurnewcost."' ".
			   " where purchasedt_id = $rows[1]"; 
	$resup = mysql_query($queryup,$connection);
	} 
	$i++;
}

	$CalculateResult = Calculate_MasterAmounts($SPurId, $PPurDate, $PPurVatChkbx, $vPurDiscount, 0, $PPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'I', $connection);
	$message  = $message . $CalculateResult;
}
//LoadGRN Mode	
else if($mainmode == "LoadGrn" && $SelectedRec != ''){
	
	$ErrorExists = 0;
	$message  = '';
	 
	if($vPurId==''){
		fbegin();	
		$vPurId = get_nextsequence('Purchase_Id','',$connection);	
		fcommit();
		
		$SPurId = $vPurId;
			
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_purchases (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, User_Account, Logged_Code, Purchase_othercharges) ".
				 " SELECT $vPurId, Null, now(), Purchase_Remark, GRNPurchases.Supplier_code, GRNPurchases.Currency_Code, GRNPurchases.Project_Code, GRNPurchases.Costcent_code, Purchase_InvoiceNo, ADDDATE(now(), ifNull(Suppliers.Supplier_PaymentTerms,0)), 0, ".
				 " 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, 'PI', Purchase_Grn, User_Account, '".$_SESSION['useraccount']."', grnpurchases_othercharges ".
				 " FROM GRNPurchases ".
				 " Inner Join Suppliers on GRNPurchases.Supplier_code = Suppliers.Ledger_Number ".
				 " WHERE Purchase_id = ".$SelectedRec;
		
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			$message  = mysql_error($connection); 	
		}
			
	//echo $query; exit;				 
	} else $SPurId=$vPurId;
	
	if ($ErrorExists == 0) {
		
		$sub_query = " SELECT PurchaseDt_id, Purchase_id  ".
					 " FROM GRNPurchasesdt ".
					 " WHERE Purchase_id = ".$SelectedRec;
					 
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
		
			fbegin();
			$vPurDtId = get_nextsequence('Purchasedt_Id','',$connection);	
			fcommit();
		
		
			$sub_query1 = " INSERT INTO temp_purchasesdt (PurchaseDt_id, Purchase_id, RelatedDt_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, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo,purchasedt_cost,purchasedt_freight, Logged_Code ) ".
						  " SELECT $vPurDtId, $vPurId, $sub_row[0], Currency_Code, now(), 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, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo,grnpurchasesdt_cost,grnpurchasesdt_freight, '".$_SESSION['useraccount']."'  ".
						  " FROM GRNPurchasesdt ".
						  " WHERE Purchase_Id = '".$SelectedRec."' ".
						  " AND PurchaseDt_Id = '".$sub_row[0]."'";
		
			$sub_result1 = mysql_query($sub_query1,$connection);
			
			if ($sub_result1){
				 
				$sub_query2 = " SELECT Serial_ID, purchasesserialno.Item_Code, purchasesserialno.Warehouse_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ifNull(SerialNo_Quantity,0), Item_ExpireDate, Item_BatchNo  ".
							  " FROM purchasesserialno ".
							  " WHERE purchasesserialno.PurchaseDt_ID  = '".$sub_row[0]."' ".
							  " AND purchasesserialno.Journal_Type = 'PI' ";
								  
				//echo $sub_query2; exit;
				$sub_result2 = mysql_query($sub_query2,$connection) or die(mysql_error());
				while($sub_row2=mysql_fetch_array($sub_result2)){
					fbegin();
					$vSerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
							
					$sub_query3 = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
								  " VALUES ( ".$vSerId.", 'PI', $vPurDtId, '".$sub_row2[1]."', '".$sub_row2[3]."', 0, '".$sub_row2[0]."', '".$sub_row2[6]."', '".$sub_row2[2]."', '".$sub_row2[7]."', '".$sub_row2[8]."', '".$_SESSION['useraccount']."' ) ";
					//echo $sub_query3; exit;
					$sub_result3 = mysql_query($sub_query3,$connection);
				}
					
			} else {
				$ErrorExists = 1;
				$message  = mysql_error($connection); 
			}
	  
		}  
	}
}


//Edit ItemQuantity
else if(($mode == "editqty" || $mode == "editqty1") && $SPurId != "" && $SPurDtId != ''){
	
	
	
	if ($SPurId != "" && $SPurDtId != "") {
		
		
		$vPurTaxable = 0;
		$vPurNoneTaxable = 0;
		$vPurDtTotalOld = 0;
		$vPurDtTotalTTCOld = 0;
		$vPurDtPrice    = 0;
		$vPurDtDiscount = 0;
		$vPurGrossTotal = 0;
		$vPurDiscount   = 0;
		$vPurDiscountAmt = 0;
		$vPurDtDiscAmt       = 0;
		$vPurDtDiscAmtBase1  = 0;
		$vPurDtDiscAmtBase2  = 0;
		$vPurVat = 0;
		$vPurVatChkbx = 0;
		$vPurVatBase1 = 0;
		$vPurVatBase2 = 0;
		$vItemCode = '';
		$vPurDate  = '';
		$vPurSuppCode = '';
		
		
	
		$query = " Select Currency_code, ifNull(Purchase_Taxable,0), ifNull(Purchase_NoneTaxable,0), ".
				 " ifNull(Purchase_DiscountPer,0), Date_Format(Purchase_Date,'%d/%m/%Y'), ifNull(Purchase_VatChkbx,0), ".
				 " Supplier_code ".
				 " From Temp_Purchases As Purchases ".
				 " Where Purchase_ID = ".$SPurId;
				// " And Logged_Code = '".$_SESSION['useraccount']."' ";			 
				 
		//echo $query; exit;
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);
		
		$vPurCurr        = $rows[0];
		//$vPurTaxable     = $rows[1];
		//$vPurNoneTaxable = $rows[2];
		$vPurDiscount    = $rows[3];
		$vPurDate        = $rows[4];
		$vPurVatChkbx    = $rows[5];
		$vPurSuppCode    = $rows[6];
		
		
		//Get Purchase Rates
		$PurRates = GetPurchaseRates($SPurId,$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		
		$querydt = " Select Item_Code, ((PurchaseDt_Quantity*PurchaseDt_Price)-((PurchaseDt_Quantity*PurchaseDt_Price*PurchaseDt_DiscountPer)/100)) As Total, ".
				   " PurchaseDt_Price, PurchaseDt_DiscountPer ".
				   " From Temp_PurchasesDt As PurchasesDt  ".
				   " Where PurchasesDt.PurchaseDt_ID = ".$SPurDtId;
				   //" And Logged_Code = '".$_SESSION['useraccount']."' ";			   
		//echo $querydt;exit;
		$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
		$rowsdt=mysql_fetch_array($resultdt);
		
		$vItemCode         = $rowsdt[0];
		$vPurDtTotalOld    = $rowsdt[1];
		$vPurDtPrice       = $rowsdt[2];
		$vPurDtDiscount    = $rowsdt[3];
				
		
		
				
		// Calculation For Detail Discount Amount
		$vPurDtDiscAmt       = (($vPurDtPrice*$QItemQty) - ($vPurDtPrice*$QItemQty*$vPurDtDiscount/100))*$vPurDiscount;
		$vPurDtDiscAmtBase1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
		$vPurDtDiscAmtBase2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($vPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
				
		
		fbegin();
		
		$query = " UPDATE temp_purchasesdt 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." PurchaseDt_DiscountAmount = $vPurDtDiscAmt, PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, ".
						" PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2 ".
						" Where PurchaseDt_ID = ".$SPurDtId;
		
		//echo $query; exit;
			
		$result=mysql_query($query,$connection);
		if ($result){
			fcommit();
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $vPurDate, $vPurVatChkbx, $vPurDiscount, 0, 0, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, 0, $PurchaseTTC, 'U', $connection);
			$message  = $message . $CalculateResult;
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}				
		
			
	}
	if($ajxused == 1) {
		echo 1; exit;
	}
}	

//Load Porder
else if($mainmode == "loadporder" ){
	
if (!isset($PPurCurr))
	   $PPurCurr = $base1;
	   
	if (empty($PPurDiscountAmt))
		$PPurDiscountAmt = 0;
	if (empty($PPurDiscount))
		$PPurDiscount = 0;
	
	$PSaCostCentCode = "".$PSaCostCentCode;	
	if ($PSaCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if (empty($PSaProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'";   
		
	
	//Insert Master Table
	if ($SPurId == ""){
		
		$sub_query  = " Select Currency_Code,Supplier_code,Porder_remark,Costcent_code,Project_Code,Porder_VATChckbx, supplier_code1 From Porder Where Porder_id = ".$SelectedRec;
		echo"<br>".$sub_query."<br>";
		$sub_result = selectData($connection, $sub_query);
		$PPurCurr = $sub_result[0];
		$Supplier_code = $sub_result[1];
		$Porder_remark = $sub_result[2];
		$Costcent_code = $sub_result[3];
		$Project_Code = $sub_result[4];
		$PPurVatChkbx = $sub_result[5];
		$PPursupplier_code1 = $sub_result[6];
		// On load the currency must be the same as loaded Porder
		$vPurCurrCode = $sub_result[0];

		fbegin();	
		$vPurId = get_nextsequence('Purchase_Id','',$connection);	
		fcommit();
	
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, DebitCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, ".
					 " CommissionsCreditAccount, InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ".
					 " ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, ".
					 " OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount ".
					 " FROM purchasesetup ";
					 
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$Rate_Query1 = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPurCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPurCurr."' )";
		$Rate_Result = selectData($connection, $Rate_Query1);
		$vPurchaseRate = $Rate_Result[0];
		if (empty($vPurchaseRate)) $vPurchaseRate = 1;
		
		$Rate_Query1 = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$Rate_Result1 = selectData($connection, $Rate_Query1);
		$vPurchaseRateBase2 = $Rate_Result1[0];
		if (empty($vPurchaseRateBase2)) $vPurchaseRateBase2 = 0;
		
		//echo $vPurchaseRate;exit;
		else if ($PPurCurr == $base1) $vPurchaseRateBase1 = 1;
		else $vPurchaseRateBase1 = 0; 
	
		fbegin();	
				 /*
		$query = " INSERT INTO temp_purchases (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, ".
				 " Purchase_FreightCur, Purchase_CommissionsCur, Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, ".
				 " CommissionsCreditAccount, InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, ".
				 " CustomsCreditAccount, Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, User_Account, Logged_Code) ".
				 " 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, '".$PurchaseDefaultType."', 0, Porder_Reference, Porder_Reference, ".
				 " Porder.Currency_Code, Porder.Currency_Code, Porder.Currency_Code, Porder.Currency_Code, Porder.Currency_Code, Porder.Currency_Code, Porder.Currency_Code, '".$Acc_Result[7]."', '".$Acc_Result[8]."', ".
				 " '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[12]."', '".$Acc_Result[13]."', '".$Acc_Result[14]."', '".$Acc_Result[15]."', '".$Acc_Result[16]."', '".$Acc_Result[17]."', ".
				 " '".$Acc_Result[18]."', '".$Acc_Result[19]."', '".$Acc_Result[20]."', $vPurchaseRate, $vPurchaseRateBase1, $vPurchaseRateBase2, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
				 " FROM Porder Inner Join Suppliers on Porder.Supplier_code = Suppliers.Ledger_Number ".
				 " WHERE Porder_id = ".$SelectedRec;
*/




		if ($PPurVatChkbx=='')
			$PPurVatChkbx = 0;
			
			if ($PPurSupplier=='')
				$PPurSupplier = $Supplier_code;
			if ($PPursupplier_code1=='')
				$PPursupplier_code1 = "null";
			if ($Purchase_paymentcondition=='')
				$Purchase_paymentcondition = "''";
			if ($PPurRemark=='')
				$PPurRemark = $Porder_remark;
			if ($ProjectCode=='Null')
				$ProjectCode = "'".$Project_Code."'";
			if ($CostCentCode=='Null')
				$CostCentCode = "'".$Costcent_code."'";				
			
	
		$query = " INSERT INTO temp_purchases (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_FreightCur, Purchase_CommissionsCur, ".
				 " Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
				 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount, ".
				 " Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, SrvNo, WaybillNo, User_Account, Logged_Code, Purchase_paymentcondition, supplier_code1) ".
				 " VALUES ( ".$vPurId.", Null, '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurRemark))."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', ".
				 "          '".$PPurCurr."', $ProjectCode, $CostCentCode, '".$PPurInvoiceNo."', '".insertMySQLDate($PPurMaturityDate)."', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPurDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPurVatChkbx, 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."', '".$PurchaseDefaultType."', 0, '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', ".
				 "          '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$Acc_Result[7]."', '".$Acc_Result[8]."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', ".
				 "          '".$Acc_Result[12]."', '".$Acc_Result[13]."', '".$Acc_Result[14]."', '".$Acc_Result[15]."', '".$Acc_Result[16]."', '".$Acc_Result[17]."', '".$Acc_Result[18]."', ".
				 "          '".$Acc_Result[19]."', '".$Acc_Result[20]."', $vPurchaseRate, $vPurchaseRateBase1, $vPurchaseRateBase2, '".ereg_replace("'", "\'", trim($PPurSrvNo))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPurWaybillNo))."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', $Purchase_paymentcondition, $PPursupplier_code1 )";
					

					
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPurId = $vPurId;
			fcommit();
		}else{
			$vPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	
	
	
	
	if ($SPurDtId != '' or $SelectedRec!='') {
	
		$vPurId = $SPurId;
		
		$ErrorExists = 0;
		
		$vPurDiscountPer = 0;
		$vPurVatChkbx    = 0;
		$vPurCurrCode    = '';
		$vPurDate        = '';
		$vPurSuppCode    = '';
		
		$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_Purchases ".
					   " 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];	
		// JP select Suplier Default Curr
		if($vPurCurrCode == '') {
			$QuerySupCurr = "select currency_code from supplier where ledger_number = '".ereg_replace("'", "\'", trim($PPurSupplier))."'";
			$sub_SupCurr = selectData($connection, $QuerySupCurr);
			if($sub_SupCurr[0] != '')
				$vPurCurrCode    = $sub_SupCurr[0];
			else 
				$vPurCurrCode = $base1;

		}
		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, PorderDt.Item_Unit2Qty, PorderDt.Project_Code, PorderDt.CostCent_Code, PorderDt_heatNo ".
					 " FROM PorderDt ";
		
		if($SPurDtId != '')			 
			$sub_query = $sub_query." WHERE PorderDt.PorderDt_Id In (".$SPurDtId.")";
		else 
			$sub_query = $sub_query." WHERE PorderDt.Porder_Id = '".$SelectedRec."'";		
			
			// echo "<BR>". $sub_query;
		$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;
			
			
			$PorderDt_heatNo  = $row[18];
			
			$sub_query4 = " Select Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchased ".
					      " From PurchasesDt ".
						  " Where PurchasesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And PurchasesDt.Journal_Type = 'PI' ".
						  " And PurchasesDt.Purchase_Id != '".$vPurId."' ";
			$sub_result4 = selectData($connection, $sub_query4);
			if ($sub_result4[0] == '') $sub_result4[0] = 0;
	
			$sub_query5 = " Select Sum(ifNull(Temp_PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchasedTemp ".
					      " From Temp_PurchasesDt ".
					      " Where Temp_PurchasesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And Temp_PurchasesDt.Journal_Type = 'PI' ".
						  " And Temp_PurchasesDt.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 PurchasesDt 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), ifNull(Item_VatType, 1) ".
						 " 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];
				$ItemVatType   = $result[8];
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
					
					if ($Module_Unit1Method == 1)
						$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
					else	
						$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
				}
				
				//Get Purchase Rates
				$PurRates = GetPurchaseRates($vPurId,$connection);
				$vRate   = $PurRates[0];
				$vRateB1 = $PurRates[1];
				$vRateB2 = $PurRates[2];
		
					 
				//Check If Currency of Detail Differs From Currency of The Header Then Convert Currency	
				if ($row[1] != $vPurCurrCode) {


					$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    = ConvertCurrencyRate($vPurCurrCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
					$vPurDtPriceBase2    = ConvertCurrencyRate($vPurCurrCode, $base2, insertMySQLDate($vPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
					$vPurDtPriceTTCBase1 = ConvertCurrencyRate($vPurCurrCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
					$vPurDtPriceTTCBase2 = ConvertCurrencyRate($vPurCurrCode, $base2, insertMySQLDate($vPurDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
				} 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  = ConvertCurrencyRate($vPurCurrCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
				$vPurDtDiscAmtBase2  = ConvertCurrencyRate($vPurCurrCode, $base2, insertMySQLDate($vPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);

				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,  ".
						 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
						 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
						 " DebitAccountVATNonStock2, DebitAccountVATNonStock3 ".
						 " FROM purchasesetup ";
							 
				$result = selectData($connection, $query);
					
				$vPurStpDirectStkDbt    = $result[0];
				$vPurStpDirectStkCrd    = $result[1];
				$vPurStpDirectStkCur    = $result[2];	
				$vPurStpVatAcc          = $result[3];	
				$vPurStpDebitAcc        = $result[4];	
				$vPurStpVatNonStockAcc  = $result[5];
				$vPurStpVatAcc2         = $result[6];
				$vPurStpVatAcc3         = $result[7];
				$vPurStpVatNonStockAcc2 = $result[8];
				$vPurStpVatNonStockAcc3 = $result[9];
				$vPurStpDebitAcc2       = $result[10];
				$vPurStpDebitAcc3       = $result[11];
				$vPurStpDebitVatAcc     = $result[12];
				$vPurStpDebitVatAcc2    = $result[13];
				$vPurStpDebitVatAcc3    = $result[14];
				$vPurStpDebitNonStockAcc  	 = $result[15];
				$vPurStpDebitNonStockAcc2 	 = $result[16];
				$vPurStpDebitNonStockAcc3 	 = $result[17];
				$vPurStpDebitVatNonStockAcc  = $result[18];
				$vPurStpDebitVatNonStockAcc2 = $result[19];
				$vPurStpDebitVatNonStockAcc3 = $result[20];
					
					
				$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 && $vPurVatChkbx == 1) {
						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)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}	
				
					if ($ItemVat > 0 && $vPurVatChkbx == 1) {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
						}
					}	
					else {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
						}						
					}
	
				}
					
				$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('Purchasedt_Id','',$connection);	
				fcommit();
				
					 
				fbegin();
				
				$sub_query1 = " INSERT INTO temp_purchasesdt (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, Logged_Code, Purchasedt_heatno ) ".
							  " VALUES ( $vPurDtId, $vPurId, '".$row[0]."', '".$sub_result11[0]."', '".insertMySQLDate($sub_result11[1])."', '".$sub_result11[2]."', 'PI', '".$row[16]."', '".$row[17]."', '".$row[2]."', '".trim(strtoupper($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."', '".$_SESSION['useraccount']."','".$PorderDt_heatNo."' ) ";
				//$message  = $sub_query1; 
				//	frollback();
				// 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
		
		
		//echo $vPurDate; exit;
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($vPurId, $vPurDate, $vPurVatChkbx, $vPurDiscountPer, 0, 0, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, 0, $PurchaseTTC, '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_PurchasesDt As PurchasesDt on PurchasesDt.RelatedDt_ID = PorderDt.PorderDt_ID ".
						 " WHERE PurchasesDt.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_purchases SET ".
						  " Purchase_PorderReferences   = Substr('".$vPorderAllRef."',2,length('".$vPorderAllRef."')) ".
						  " WHERE Purchase_ID = ".$vPurId;
			//echo $sub_query1; exit;		 
			$sub_result1=mysql_query($sub_query1,$connection);
		}
			
			
		
	}

}

//Changing Purchase Rates
else if($mode == "changerates" && $SPurId != ''){  
	
		
	$query = " Select Purchase_ID, Currency_Code, Date_Format(Purchase_Date,'%d/%m/%Y'), ifNull(Purchase_DiscountPer,0), ifNull(Purchase_VatChkbx,0) ".
	         " From Temp_Purchases As Purchases ".
	         " Where Purchases.Purchase_ID = ".$SPurId;
	//echo $query;
	$rows = selectData($connection, $query);
	
	$vCurCode = $rows[1];
	$vPurDate = $rows[2];
	$vPurDiscountPer = $rows[3];
	$vPurVatChkbx    = $rows[4];
	
	$vRate   = $txtPurRate;
	$vRateB2 = $txtPurRateB2;
	
	if (empty($vRate)) 	 $vRate = 1;
	if (empty($vRateB2)) $vRateB2 = 0;
	
	else if ($vCurCode == $base1) $vRateB1 = 1;
	else $vRateB1 = 0;
	
	
	
	$query = " UPDATE temp_purchases SET ".
	         " Purchase_Rate = $vRate, Purchase_RateBase1 = $vRateB1, Purchase_RateBase2 = $vRateB2 ".
			 " WHERE Purchase_id = $SPurId ";
	$result=mysql_query($query,$connection);
	//echo $query."<br>"; exit;
				
	if ($result){
		
		$sub_query = " Select PurchaseDt_Id, Currency_Code, ifNull(PurchaseDt_Price,0), ifNull(PurchaseDt_PriceBase1,0), ifNull(PurchaseDt_PriceBase2,0), ".
					 " ifNull(PurchaseDt_PriceTTC,0), ifNull(PurchaseDt_PriceTTCBase1,0), ifNull(PurchaseDt_PriceTTCBase2,0), ifNull(PurchaseDt_DiscountAmount,0), ".
					 " ifNull(PurchaseDt_DiscountBase1,0), ifNull(PurchaseDt_DiscountBase2,0), ifNull(PurchaseDt_ChargesAmnt,0) ".
					 " From temp_purchasesdt ".
					 " Where Purchase_ID = ".$SPurId;	
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vPurDtPrice         = $sub_row[2];
			$vPurDtPriceBase1    = $sub_row[3];
			$vPurDtPriceBase2    = $sub_row[4];
			$vPurDtPriceTTC      = $sub_row[5];
			$vPurDtPriceTTCBase1 = $sub_row[6];
			$vPurDtPriceTTCBase2 = $sub_row[7];
			$vPurDtDiscAmt       = $sub_row[8];
			$vPurDtDiscAmtBase1  = $sub_row[9];
			$vPurDtDiscAmtBase2  = $sub_row[10];
			$vPurDtChgAmt        = $sub_row[11];
			
				
			$vPurDtPriceBase1    = ConvertCurrencyRate($vCurCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
			$vPurDtPriceBase2    = ConvertCurrencyRate($base1, $base2, insertMySQLDate($vPurDate), $vRateB1, $vRateB2, $vPurDtPriceBase1, $connection);
			$vPurDtPriceTTCBase1 = ConvertCurrencyRate($vCurCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
			$vPurDtPriceTTCBase2 = ConvertCurrencyRate($base1, $base2, insertMySQLDate($vPurDate), $vRateB1, $vRateB2, $vPurDtPriceTTCBase1, $connection);
			$vPurDtDiscAmtBase1  = ConvertCurrencyRate($vCurCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
			$vPurDtDiscAmtBase2  = ConvertCurrencyRate($base1, $base2, insertMySQLDate($vPurDate), $vRateB1, $vRateB2, $vPurDtDiscAmtBase1, $connection);
			$vPurDtChgAmtBase1   = ConvertCurrencyRate($vCurCode, $base1, insertMySQLDate($vPurDate), $vRate, $vRateB1, $vPurDtChgAmt, $connection);
			$vPurDtChgAmtBase2   = ConvertCurrencyRate($base1, $base2, insertMySQLDate($vPurDate), $vRateB1, $vRateB2, $vPurDtChgAmtBase1, $connection);
					
			$sub_query1 = " UPDATE temp_purchasesdt SET  ".
						  " PurchaseDt_PriceBase1 = $vPurDtPriceBase1, PurchaseDt_PriceBase2 = $vPurDtPriceBase2, ".
						  " PurchaseDt_PriceTTCbase1 = $vPurDtPriceTTCBase1, PurchaseDt_PriceTTCbase2 = $vPurDtPriceTTCBase2, ".
						  " PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2, ".
						  " PurchaseDt_ChargesAmntB1 = $vPurDtChgAmtBase1, PurchaseDt_ChargesAmntB2 = $vPurDtChgAmtBase2 ".
						  " Where PurchaseDt_ID = ".$sub_row[0];
					
			//echo $sub_query1; exit;	
			if (!updateData($connection, $sub_query1, true))		 
				$message  = mysql_error(); 
					
		}  //End Loop of PurchaseDt Query
		
		
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPurId, $vPurDate, $vPurVatChkbx, $vPurDiscountPer, 0, 0, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'U', $connection);
		$message  = $message . $CalculateResult;
			
			
	}	
}


//Changing Purchase Rates
else if($mode == "changecurrency" && $SPurId != ''){ 

	if (empty($txtPurDiscountAmt))	$txtPurDiscountAmt = 0;
	if (empty($txtPurDiscount))		$txtPurDiscount = 0; 
	if (empty($txtPurVatBase1))		$txtPurVatBase1 = 0; 
	
	$Rate_Query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$Rate_Result = selectData($connection, $Rate_Query);
	$vPurchaseRate = $Rate_Result[0];
	if (empty($vPurchaseRate)) $vPurchaseRate = 1;
		
	$Rate_Query1 = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$Rate_Result1 = selectData($connection, $Rate_Query1);
	$vPurchaseRateBase2 = $Rate_Result1[0];
	if (empty($vPurchaseRateBase2)) $vPurchaseRateBase2 = 0;
		
	else if ($txtCurr == $base1) $vPurchaseRateBase1 = 1;
	else $vPurchaseRateBase1 = 0;
	
	$Acc_Query = " SELECT if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$txtCurr."') As DebitCur FROM purchasesetup ";
	$Acc_Result = selectData($connection, $Acc_Query);
	
	$query = " UPDATE temp_purchases SET Currency_Code = '".$txtCurr."', Purchase_DebitCur = '".$Acc_Result[0]."', ".
			 " Purchase_Rate = $vPurchaseRate, Purchase_RateBase1 = $vPurchaseRateBase1, Purchase_RateBase2 = $vPurchaseRateBase2  ".
			 " WHERE Purchase_id = $SPurId ";
	$result=mysql_query($query,$connection);
	
	//echo $query; exit;
	//Get Purchase Rates
	$PurRates = GetPurchaseRates($SPurId,$connection);
	$vRate   = $PurRates[0];
	$vRateB1 = $PurRates[1];
	$vRateB2 = $PurRates[2];
		
	//Update Detail Amount Columns
	$sub_query = " Select PurchaseDt_Id, Currency_Code, ifNull(PurchaseDt_Price,0), ifNull(PurchaseDt_PriceBase1,0), ifNull(PurchaseDt_PriceBase2,0), ".
				 " ifNull(PurchaseDt_PriceTTC,0), ifNull(PurchaseDt_PriceTTCBase1,0), ifNull(PurchaseDt_PriceTTCBase2,0), ifNull(PurchaseDt_DiscountAmount,0), ".
				 " ifNull(PurchaseDt_DiscountBase1,0), ifNull(PurchaseDt_DiscountBase2,0), ifNull(PurchaseDt_ChargesAmnt,0) ".
				 " From temp_purchasesdt ".
				 " Where Purchase_ID = ".$SPurId;	
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_row=mysql_fetch_array($sub_result)){
					
		$vPurDtPrice         = $sub_row[2];
		$vPurDtPriceBase1    = $sub_row[3];
		$vPurDtPriceBase2    = $sub_row[4];
		$vPurDtPriceTTC      = $sub_row[5];
		$vPurDtPriceTTCBase1 = $sub_row[6];
		$vPurDtPriceTTCBase2 = $sub_row[7];
		$vPurDtDiscAmt       = $sub_row[8];
		$vPurDtDiscAmtBase1  = $sub_row[9];
		$vPurDtDiscAmtBase2  = $sub_row[10];
		$vPurDtChgAmt        = $sub_row[11];
			
			

					
		$vPurDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtPrice, $connection);
		$vPurDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtPriceTTC, $connection);
		$vPurDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtDiscAmt, $connection);
		$vPurDtChgAmt   = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtChgAmt, $connection);
						
		$vPurDtPriceBase1    = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
		$vPurDtPriceBase2    = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
		$vPurDtPriceTTCBase1 = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
		$vPurDtPriceTTCBase2 = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
		$vPurDtDiscAmtBase1  = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
		$vPurDtDiscAmtBase2  = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
		$vPurDtChgAmtBase1   = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtChgAmt, $connection);
		$vPurDtChgAmtBase2   = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtChgAmt, $connection);
					
		$sub_query1 = " UPDATE temp_purchasesdt SET  ".
					  " Currency_Code = '".$txtCurr."', ".
					  " PurchaseDt_Price = $vPurDtPrice, PurchaseDt_PriceBase1 = $vPurDtPriceBase1, PurchaseDt_PriceBase2 = $vPurDtPriceBase2, ".
					  " PurchaseDt_PriceTTC = $vPurDtPriceTTC, PurchaseDt_PriceTTCbase1 = $vPurDtPriceTTCBase1, PurchaseDt_PriceTTCbase2 = $vPurDtPriceTTCBase2, ".
					  " PurchaseDt_DiscountAmount = $vPurDtDiscAmt, PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2, ".
					  " PurchaseDt_ChargesAmnt = $vPurDtChgAmt,  PurchaseDt_ChargesAmntB1 = $vPurDtChgAmtBase1, PurchaseDt_ChargesAmntB2 = $vPurDtChgAmtBase2 ".
					  " Where PurchaseDt_ID = ".$sub_row[0];
					
		//echo $sub_query1; exit;	
		if (!updateData($connection, $sub_query1, true))		 
			$message  = mysql_error(); 
					
	}  //End Loop of PurchaseDt Query
		

	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($SPurId, $txtDate, $SPurVatChkbx, $txtPurDiscount, $txtPurDiscountAmt, $txtPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'P', $connection);
	$message  = $message . $CalculateResult;
			



			
		
}

else if($mode == "changedate" && $mainmode == ''){
	if($txtPaymentTerms == '') $txtPaymentTerms = 0;
	$ndate = explode('/',$txtInvoiceDate);
	$txtInvoiceDate = $ndate[2]."-".$ndate[1]."-".$ndate[0];
	
	$query = "select date_format(DATE_ADD(date_format('$txtInvoiceDate','%Y-%m-%d'),INTERVAL $txtPaymentTerms DAY), '%d/%m/%Y')  ; ";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	echo $row[0];
	exit;
}
//Post Mode	
else if($mode == "post" && $SPurId != ''){  

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

	//Get Purchase Rates
	$PurRates = GetPurchaseRates($SPurId,$connection);
	$vRate   = $PurRates[0];
	$vRateB1 = $PurRates[1];
	$vRateB2 = $PurRates[2];
	
	
	if (empty($txtPurCategory))		$txtPurCategory = 0;
	if (empty($txtPurDiscountAmt))	$txtPurDiscountAmt = 0;
	if (empty($txtPurDiscount))		$txtPurDiscount = 0;
	if (empty($txtTotalAmount))		$txtTotalAmount = 0;
	
	$txtCostCentCode = "".$txtCostCentCode;		
	if ($txtCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
	
if (empty($txtPur_Othercharges))
		$txtPur_Othercharges = 0;	
		
	$vPurTotal = 0;
	$vPurDisAmt = 0;
	
	$vPurDtPriceTTC      = 0;
	$vPurDtPriceTTCBase1 = 0;
	$vPurDtPriceTTCBase2 = 0;					
	$vPurDtPrice      	 = 0;
	$vPurDtPriceBase1 	 = 0;
	$vPurDtPriceBase2 	 = 0;
	$vPurDtDiscAmt       = 0;
	$vPurDtDiscAmtBase1  = 0;
	$vPurDtDiscAmtBase2  = 0;
	$vPurDtChgAmt        = 0;
	$vPurDtChgAmtBase1   = 0;
	$vPurDtChgAmtBase2   = 0;
	
	
	$vPurDebitAcc = '';
	$vPurDebitCur = '';
		
	
    $SaveAllow   = 1;
	$ErrorExists = 0;
	
	
	$queryModuleBatch = "select ifnull(module_batchno,0) as Module_BatchNo from module";
	$BatchRes = selectData($connection, $queryModuleBatch);
	if($BatchRes[0] == 1){
		$querydtCheck = "select count(*) from temp_purchasesdt where  Purchase_id = '".$SPurId."' and ifnull(PurchaseDt_BatchNo,'') = '' ";
		$BatchdtcheckRes = selectData($connection, $querydtCheck);
		if($BatchdtcheckRes[0] > 0){
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Batch No In details.';
		}
	}
	
	if($txtPur_Othercharges != ''){
		$queryothercharges = "update Temp_Purchases set Purchase_othercharges = $txtPur_Othercharges, Purchase_otherchargesB1 = $Purchase_otherchargesB1, 
								Purchase_otherchargesB2 = $Purchase_otherchargesB2 where Purchase_id = '".$SPurId."' ";
		$resothercharges = mysql_query($queryothercharges,$connection);
	}
	
	if($auto_paymentrqst == 1){
		$queryup = "update temp_purchases set auto_paymentrqst = $autopaymentrqst where purchase_id = $SPurId";
		$resup = mysql_query($queryup,$connection);
	}
	
	$Acc_Query = " SELECT if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$txtCurr."') As DebitCur FROM purchasesetup ";
	$Acc_Result = selectData($connection, $Acc_Query);
	
	$queryup = "update temp_purchases set Purchase_DebitCur = '".$Acc_Result[0]."'
				where purchase_id = $SPurId ";
	//echo $queryup;exit;
	$resup = mysql_query($queryup,$connection);
	
	$queryup = "update temp_purchases set Purchase_shippedIn = '".ereg_replace("'", "\'", trim($txtShippedIn))."', 
				InvoiceDate = '".insertMySQLDate($txtInvoiceDate)."' 
				where purchase_id = $SPurId ";
	//echo $queryup;exit;
	$resup = mysql_query($queryup,$connection);
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_purchasesdt ".
				 " 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_purchasesdt ".
								  " 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;
					
					
				}
			}		  
			
		} 
	}//echo $resothercharges; exit;
	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	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.';
		}
	}
	
	//Check For Price Before Insert
	if($Module_PurchaseZero==1){
		$sub_query = " Select 1  ".
					 " From Temp_PurchasesDt As PurchasesDt  ".
					 " Where PurchasesDt.Purchase_ID = ".$SPurId." And PurchaseDt_Price = 0";
						  
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] != 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Price 0.';
		}
	}
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select PurchasesDt.PurchaseDt_ID, PurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_PurchasesDt As PurchasesDt Left Join Items on PurchasesDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on PurchasesDt.PurchaseDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'PI' ".
					 " 	And Temp_Purchasesserialno.PurchaseDt_ID Is Not Null ".
					 " 	Where PurchasesDt.Purchase_ID = ".$SPurId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By PurchasesDt.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 PurchasesDt.PurchaseDt_ID, PurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity ".
					 " 	From Temp_PurchasesDt As PurchasesDt ".
					 " 	Where PurchasesDt.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].';
		}		 
	}
	
	if ($ErrorExists == 0 && $Module_PurchaseCheckTotal == 1 && $txtTotalAmount != 0) {
		
		
		$sub_query= " Select Round((Purchase_Total + IfNull(Purchase_VAT,0) - IfNull(Purchase_DiscountAmount,0) + ifNull(Purchase_Charges,0) + ifNull(Purchase_VatCharges,0) + ".
					" (ifNull(Purchase_Tax1,0) + ifNull(Purchase_Tax2,0) + ifNull(Purchase_Tax3,0) + ifNull(Purchase_Tax4,0) + ifNull(Purchase_Tax5,0))), ".$DecimalBase.") As PurchaseNetTotal  ".
					" From Temp_Purchases As Purchases ".
					" Where Purchase_ID = '".$SPurId."'";
		$sub_result = selectData($connection, $sub_query);
		$PurchaseNetTotal = $sub_result[0];
		
		
		if ($PurchaseNetTotal != $txtTotalAmount) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Total Amount Entered and The Total of Purchase.';
		}
	}
	
	//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) { 
	
		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select PurchaseDt_Id, temp_purchasesdt.Currency_Code, ifNull(PurchaseDt_Price,0), ifNull(PurchaseDt_PriceBase1,0), ifNull(PurchaseDt_PriceBase2,0), ".
					 " ifNull(PurchaseDt_PriceTTC,0), ifNull(PurchaseDt_PriceTTCBase1,0), ifNull(PurchaseDt_PriceTTCBase2,0), ifNull(PurchaseDt_DiscountAmount,0), ".
					 " ifNull(PurchaseDt_DiscountBase1,0), ifNull(PurchaseDt_DiscountBase2,0), ifNull(PurchaseDt_ChargesAmnt,0),Items.Group_Code,Items.Item_Vat, ".
					 " ifNull(Items.Item_Production, 0), ifNull(Items.Item_TTCInclude, 0), ifNull(Items.Item_NonStock, 0), ifNull(Items.Item_VatType, 1) ".
					 " From temp_purchasesdt ".
					 " Inner Join Items on temp_purchasesdt.Item_Code = Items.Item_Code ".
					 " Where Purchase_ID = ".$SPurId;	
					
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vPurDtPrice         = $sub_row[2];
			$vPurDtPriceBase1    = $sub_row[3];
			$vPurDtPriceBase2    = $sub_row[4];
			$vPurDtPriceTTC      = $sub_row[5];
			$vPurDtPriceTTCBase1 = $sub_row[6];
			$vPurDtPriceTTCBase2 = $sub_row[7];
			$vPurDtDiscAmt       = $sub_row[8];
			$vPurDtDiscAmtBase1  = $sub_row[9];
			$vPurDtDiscAmtBase2  = $sub_row[10];
			$vPurDtChgAmt        = $sub_row[11];
			$ItemGroupCode       = $sub_row[12];
			$item_vat        	 = $sub_row[13];
			$ItemProd 	   		 = $sub_row[14];
			$ItemTTCInc	   		 = $sub_row[15];
			$ItemNonStock  		 = $sub_row[16];
			$ItemVatType   		 = $sub_row[17];

					
			if ($sub_row[1] != $txtCurr) {
				$vPurDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtPrice, $connection);
				$vPurDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtPriceTTC, $connection);
				$vPurDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtDiscAmt, $connection);
				$vPurDtChgAmt   = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPurDtChgAmt, $connection);
						
				$vPurDtPriceBase1    = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
				$vPurDtPriceBase2    = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
				$vPurDtPriceTTCBase1 = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
				$vPurDtPriceTTCBase2 = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
				$vPurDtDiscAmtBase1  = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
				$vPurDtDiscAmtBase2  = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
				$vPurDtChgAmtBase1   = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtChgAmt, $connection);
				$vPurDtChgAmtBase2   = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtChgAmt, $connection);
					
				$sub_query1 = " UPDATE temp_purchasesdt SET  ".
							  " Currency_Code = '".$txtCurr."', ".
							  " PurchaseDt_Price = $vPurDtPrice, PurchaseDt_PriceBase1 = $vPurDtPriceBase1, PurchaseDt_PriceBase2 = $vPurDtPriceBase2, ".
							  " PurchaseDt_PriceTTC = $vPurDtPriceTTC, PurchaseDt_PriceTTCbase1 = $vPurDtPriceTTCBase1, PurchaseDt_PriceTTCbase2 = $vPurDtPriceTTCBase2, ".
							  " PurchaseDt_DiscountAmount = $vPurDtDiscAmt, PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2, ".
							  " PurchaseDt_ChargesAmnt = $vPurDtChgAmt,  PurchaseDt_ChargesAmntB1 = $vPurDtChgAmtBase1, PurchaseDt_ChargesAmntB2 = $vPurDtChgAmtBase2 ".
							  " Where PurchaseDt_ID = ".$sub_row[0];
					
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
					
			}
			
		
			// Get DirectStock Accounts
						
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock,  ".
						 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
						 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
						 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport ".
						 " FROM purchasesetup ";
							 
				$result = selectData($connection, $query);
					
				$vPurStpDirectStkDbt    	 = $result[0];
				$vPurStpDirectStkCrd    	 = $result[1];
				$vPurStpDirectStkCur    	 = $result[2];	
				$vPurStpVatAcc          	 = $result[3];	
				$vPurStpDebitAcc        	 = $result[4];	
				$vPurStpVatNonStockAcc  	 = $result[5];	
				$vPurStpVatAcc2         	 = $result[6];
				$vPurStpVatAcc3         	 = $result[7];
				$vPurStpVatNonStockAcc2 	 = $result[8];
				$vPurStpVatNonStockAcc3 	 = $result[9];
				$vPurStpDebitAcc2       	 = $result[10];
				$vPurStpDebitAcc3       	 = $result[11];
				$vPurStpDebitVatAcc     	 = $result[12];
				$vPurStpDebitVatAcc2    	 = $result[13];
				$vPurStpDebitVatAcc3    	 = $result[14];
				$vPurStpDebitNonStockAcc  	 = $result[15];
				$vPurStpDebitNonStockAcc2 	 = $result[16];
				$vPurStpDebitNonStockAcc3 	 = $result[17];
				$vPurStpDebitVatNonStockAcc  = $result[18];
				$vPurStpDebitVatNonStockAcc2 = $result[19];
				$vPurStpDebitVatNonStockAcc3 = $result[20];
				$vPurStpDebitExportAcc	 	 = $result[21];
				
				$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number =  '".$txtSupplier."' ";	
				$resexp = mysql_query($queryexp,$connection);
				$rwexp = mysql_fetch_row($resexp);
				$supplierexp = $rwexp[0];
				
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc,trans_export, ".
						 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'PI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
				//echo $query."<br> $SPurVatChkbx";			 
				$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];
				$vTransExport			= $result[10];
				$vSaDtWasteDbt 			= $result[11]; 
				$vSaDtWasteCrd 			= $result[12]; 
				$vSaDtExportAcc 		= $result[13];	
					
				
				if ($Module_RawMaterial == 1) {
					$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vPurDtDirectStkCur = $vTranStpDirectStkCur;
					$vPurDtVatAcc       = $vTranStpVatAcc;
						
					if ($item_vat > 0 && $SPurVatChkbx == 1) {
						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;
						}
					}	
					if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 
				} 
				else {
					$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
					$vPurDtDirectStkCur = $vPurStpDirectStkCur;	

					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}	
				
					if ($item_vat > 0 && $SPurVatChkbx == 1) {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
						}
					}	
					else {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
						}						
					}	
					if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 	
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".$txtSupplier."','".$vPurDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$txtSupplier."','".$vPurDtDirectStkDbt."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtDirectStkDbt = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$txtSupplier."','".$vPurDtDirectStkCrd."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtDirectStkCrd = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$txtSupplier."','".$vSaDtWasteDbt."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
				
				$sub_queryVat = " SELECT GetAllVATAccount('".$txtSupplier."','".$vSaDtWasteCrd."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
				
				$sub_query1 = " Update temp_purchasesDt SET ".
						 " Purchasedt_DirectStkDbt = '".$vPurDtDirectStkDbt."', Purchasedt_DirectStkCrd = '".$vPurDtDirectStkCrd."', ".
						 " Purchasedt_DirectStkCur = '".$vPurDtDirectStkCur."', PurchaseDt_VATAccount = '".$vPurDtVatAcc."', ".
						 " Purchasedt_ItemAccount = '".$vPurDtItemAcc."' ".
						 " Where PurchaseDt_ID = ".$sub_row[0];
					 
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true)){		 
					$message  = mysql_error(); 
				}				
		}  //End Loop of PurchaseDt Query
		
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0))-((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*ifNull(PurchaseDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_PurchasesDt ".
					  " Where Purchase_ID = ".$SPurId;
					  
		$sub_result3 = selectData($connection, $sub_query3);
		$vPurTotal   = $sub_result3[0];	
		$vPurDisAmt	 = $txtPurDiscountAmt;
		
		$sub_query4 = " Select PurchaseDt_ID,  ".
					  " ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0))-((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*ifNull(PurchaseDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_PurchasesDt As PurchasesDt  ".
					  " Where PurchasesDt.Purchase_ID = ".$SPurId;
					  //" And PurchasesDt.Logged_Code = '".$PLoggedCode."' ";
				   
		
		$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
		while($sub_rows4=mysql_fetch_array($sub_result4)){
		
			$vPurDtId 	 = $sub_rows4[0];
			$vPurDtTotal = $sub_rows4[1];
			
			
			
			$vPurDtDiscAmt	    = 0;
			$vPurDtDiscAmt 		= ($vPurDtTotal/$vPurTotal)*$vPurDisAmt;
			$vPurDtDiscAmtBase1 = ConvertCurrencyRate($txtCurr, $base1, insertMySQLDate($txtDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
			$vPurDtDiscAmtBase2 = ConvertCurrencyRate($txtCurr, $base2, insertMySQLDate($txtDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
			
			$queryupd =  " UPDATE temp_purchasesdt SET PurchaseDt_DiscountAmount = $vPurDtDiscAmt, ".
						 " PurchaseDt_DiscountBase1 = $vPurDtDiscAmtBase1, PurchaseDt_DiscountBase2 = $vPurDtDiscAmtBase2  ".
						 " Where PurchaseDt_ID = ".$vPurDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
			

		}
				 
		//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_PurchasesDt As PurchasesDt  ".
						  " Where PurchasesDt.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 PurchaseDt_Id  = '".$sub_rows5[0]."' ".
						 " AND Journal_Type = 'PI' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
			
			}
		}
		
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPurId, $txtDate, $SPurVatChkbx, $txtPurDiscount, $txtPurDiscountAmt, $txtPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'P', $connection);
		$message  = $message . $CalculateResult;
		
		//Check If Client Is Changed ==> Change VAT Accounts
		$sub_query7 = " Select Supplier_Code From Temp_Purchases Where Purchase_ID = '".$SPurId."'";
		$sub_result7 = selectData($connection, $sub_query7);
		$vPreSupplierCode = $sub_result7[0];
		
		if ($vPreSupplierCode != trim($txtSupplier)) {
						
			$sub_query7 = " Select PurchaseDt_ID, PurchasesDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0), ifNull(Items.Item_VatType, 1) ".
						  " From Temp_PurchasesDt as PurchasesDt ".
						  " Inner Join Items on PurchasesDt.Item_Code = Items.Item_Code ".
						  " Where Purchase_ID = '".$SPurId."'";
						  
			$sub_result7=mysql_query($sub_query7,$connection) or die(mysql_error());
			while($sub_rows7=mysql_fetch_array($sub_result7)){
				$ItemGroupCode = $sub_rows7[2];
				$ItemNonStock  = $sub_rows7[3];
				$ItemVatType   = $sub_rows7[4];
			
				// Get VAT Accounts
				$query = " SELECT VatAccount, VatAccount2, VatAccount3, VATAccountNonStock, VATAccountNonStock2, VATAccountNonStock3 FROM purchasesetup ";
				$result = selectData($connection, $query);
					
				$vPurStpVatAcc          = $result[0];	
				$vPurStpVatAcc2         = $result[1];
				$vPurStpVatAcc3         = $result[2];
				$vPurStpVatNonStockAcc  = $result[3];	
				$vPurStpVatNonStockAcc2 = $result[4];
				$vPurStpVatNonStockAcc3 = $result[5];
					
					
				$query = " SELECT Trans_VATAccount FROM transactionsetup ".
						 " WHERE Journal_type = 'PI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
							 
				$result = selectData($connection, $query);
				$vTranStpVatAcc = $result[0];
				
				if ($Module_RawMaterial == 1) {
					$vPurDtVatAcc = $vTranStpVatAcc;
				} 
				else {
					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}
									
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".trim($txtSupplier)."','".$vPurDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
				
				$query = " UPDATE temp_purchasesdt SET ".
						 " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', PurchaseDt_VATAccount = '".$vPurDtVatAcc."' ".
						 " WHERE PurchaseDt_Id = '".$sub_rows7[0]."' ";
				$result=mysql_query($query,$connection);
			
			}
			
		}
			

		$sub_query2 = " UPDATE temp_purchasesdt SET ".
					  //" Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
					  " Currency_Code = '".$txtCurr."', Purchase_Date = '".insertMySQLDate($txtDate)."', Purchase_invoiceNo = '".$txtInvoiceNo."' ";
					  
		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_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 

			
		$query = " UPDATE temp_purchases SET ".
		         " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
		         " Supplier_code1 = '".ereg_replace("'", "\'", trim($txtSupplier1))."', ".
				 " Purchase_Date = '".insertMySQLDate($txtDate)."' , Purchase_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Purchase_InvoiceNo = '".$txtInvoiceNo."', ".
				 " Journaldt_valuedate = '".insertMySQLDate($txtMaturityDate)."', Purchase_VatChkbx = $SPurVatChkbx, ".
				 " Purchase_Import = '".$txtPurCategory."', Purchase_TotalAmount = $txtTotalAmount, ".
				 " SrvNo = '".ereg_replace("'", "\'", trim($txtSrvNo))."', WaybillNo = '".ereg_replace("'", "\'", trim($txtWaybillNo))."' ".
				 " ,Purchase_paymentcondition = '".ereg_replace("'", "\'", trim($txtPaymentCondidions))."' ";
		if($Module_Purchase_Pending) $query = $query." , purchase_type = upper('$txtPurchaseType') ";
		$query = $query." ,Purchase_othercharges = $txtPur_Othercharges, Purchase_otherchargesB1 = $Purchase_otherchargesB1, Purchase_otherchargesB2 = $Purchase_otherchargesB2 ";
		$query = $query." WHERE Purchase_id = $SPurId ";
		//echo $query;
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			$txtWHTAmt1 = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $txtWHTAmt, $connection);
			$txtWHTAmt2 = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $txtWHTAmt, $connection);
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			if($Module_PurchasesJvWHT == 1){
				if($txtWHTChk == 1)
				$queryupdate = "update temp_purchases set Purchase_WHTChk = $txtWHTChk, Purchase_WHTAccount = '$txtWHTAcc', Purchase_WHTPer = $txtWHTPer, Purchase_WHTAmt = $txtWHTAmt,
								Purchase_WHTAmt1 = $txtWHTAmt1, Purchase_WHTAmt2 = $txtWHTAmt2
								where Purchase_id = $SPurId";
				else {
					
					$queryupdate = "update temp_purchases set Purchase_WHTChk = $txtWHTChk, Purchase_WHTAccount = null, Purchase_WHTPer = null, Purchase_WHTAmt = null,
								Purchase_WHTAmt1 = null, Purchase_WHTAmt2 = null
								where Purchase_id = $SPurId";
				}
				$resupdate  = mysql_query($queryupdate, $connection);
				//echo $queryupdate; exit;
			} 
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM purchases WHERE Purchase_id = $SPurId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_Purchases where Purchase_ID = '".$SPurId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			$query_checkDelivery  = "select count(*) as PurchaseExist from purchases where Purchase_id = '$SPurId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($PurchaseExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
			
				$result = Distribute_TotalCharges($SPurId, $connection, $_SESSION['useraccount']);
				//echo $result; exit;
				if ($result==''){
					fbegin();		
		
					$query = "SELECT CopyData_TempPurchases('PI', ".$SPurId.", '".$_SESSION['useraccount']."') FROM Dual ";
					//echo $query; exit;
					$result = selectData($connection, $query);
					$result = $result[0];
					
					if ($result != 0){
						fcommit();
						
						if($autopaymentrqst == 1){
							$queryamt = "select Round((if($PurchaseTTC=1,ifNull(Purchase_Taxable,0),ifNull(Purchase_Taxable,0)) + ifNull(Purchase_NoneTaxable,0) 
										+ if($PurchaseTTC=1,0,IfNull(Purchase_VAT,0)) - IfNull(Purchase_DiscountAmount,0) + (ifNull(Purchase_Tax1,0) 
										+ ifNull(Purchase_Tax2,0) + ifNull(Purchase_Tax3,0) + ifNull(Purchase_Tax4,0) + ifNull(Purchase_Tax5,0))),".$DecimalBase.") 
										As Purchase_NetTotal, Round(ifNull(Purchase_Charges,0)), ifNull(Purchase_othercharges,0), Currency_code 
										from purchases where Purchase_id = $SPurId "; 
							$resamt = mysql_query($queryamt,$connection);	
							$rwamt = mysql_fetch_row($resamt);
							if($Module_ChargesPurchase==1)	
							$totamnt = 	$rwamt[0] + $rwamt[1] + $rwamt[2];
							else $totamnt = $rwamt[0] + $rwamt[1];
							
							$totamnt1 = ConvertCurrency($rwamt[3], $base1, insertMySQLDate($txtDate), $totamnt, $connection); 
							$totamnt2 = ConvertCurrency($rwamt[3], $base2, insertMySQLDate($txtDate), $totamnt, $connection); 
							
							$queryrqst = "select PaymentRqst_id from PaymentRqst where purRelated_id = $SPurId";
							$resrqst = mysql_query($queryrqst,$connection);
							$rwrqst = mysql_fetch_row($resrqst);
						if($rwrqst[0] != ''){
							$queryupd = "update PaymentRqst, purchases, suppliers set ".
										"PaymentRqst_DATE =  Purchase_Date, ".
										"PaymentRqst_NAME =  Ledger_name, ".
										"PaymentRqst.PROJECT_CODE =  purchases.Project_Code, ".
										"PaymentRqst.COSTCENT_CODE = purchases.Costcent_code, ".
										"PaymentRqst_AMOUNT = $totamnt, ".
										"PaymentRqst_amount1 = $totamnt1, ".
										"PaymentRqst_amount2 = $totamnt2, ".
										"PaymentRqst.CURRENCY_CODE = purchases.Currency_code, ".
										"PaymentRqst_vat = ifNull(Purchase_VatChkbx,0), ".
										"PaymentRqst_valuedate = Purchase_Date, ".
										"PaymentRqst_amountC1 = $totamnt1, ".
										"PaymentRqst_amountC2 = $totamnt2, ".
										"PaymentRqst_amountD1 = $totamnt1, ".
										"PaymentRqst_amountD2 = $totamnt2, ".
										"PaymentRqst.user_account = '".$_SESSION['useraccount']."', ".
										"PaymentRqst.Logged_Code =  '".$_SESSION['useraccount']."' ".
										" where PaymentRqst_id = $rwrqst[0] and Purchase_id = purRelated_id 
										 and suppliers.Ledger_number = purchases.Supplier_code "; 
						} else{
							fbegin();	
							$vTransId = get_nextsequence('PaymentRqst_id','',$connection);	
							fcommit();
							
							if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
							else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
							else $vProjCostCent = '';
							
							fbegin();
							$vTransRef = get_nextsequence('PRqst_RefGovernment',$vProjCostCent,$connection);	
							fcommit();
							
							fbegin();
							$queryins = "insert into PaymentRqst (PaymentRqst_id, PaymentRqst_refgovernment, PaymentRqst_DATE, PaymentRqst_NAME, PROJECT_CODE, 
								COSTCENT_CODE, PaymentRqst_AMOUNT, PaymentRqst_amount1,PaymentRqst_amount2, CURRENCY_CODE, PaymentRqst_Edit, PaymentRqst_posted, 
								PaymentRqst_vat, PaymentRqst_valuedate, PaymentRqst_BelongsToGrp, PaymentRqst_Used,PaymentRqst_amountC1, PaymentRqst_amountC2, 
								PaymentRqst_amountD1, PaymentRqst_amountD2, PaymentRqst_AmntModified, Synchronized,  PaymentRqst_App,PaymentRqst_Confirmed,paymentrqst_cash,
								paymentrqst_check, paymentrqst_costshare, paymentrqst_guarantee, user_account, Logged_Code, purRelated_id) ".
								"select $vTransId, '$vTransRef', Purchase_Date, Ledger_name, purchases.Project_Code, ".
								"purchases.Costcent_code, $totamnt, $totamnt1, $totamnt2, purchases.Currency_code, 0, 0, ".
								"ifNull(Purchase_VatChkbx,0), Purchase_Date, 0, 0, $totamnt1, $totamnt2,  ".
								"$totamnt1, $totamnt2, 0, 0, 0, 0, 0, ".
								"0, 0, 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', $SPurId ".
								"from purchases ".
								"left join suppliers on suppliers.Ledger_number = purchases.Supplier_code ".
								"where Purchase_id = $SPurId"; //echo $queryins;exit;
							$resins = mysql_query($queryins,$connection);
							if($resins){
								fcommit();
							}else{
								$message  = mysql_error(); 
								frollback();								
							}
						}
							//echo "hh";exit;
						}
						$query   = " SELECT Purchase_Reference, Costcent_code, Project_Code, Upper(Purchase_Type) FROM purchases WHERE Purchase_id = $SPurId ";
						$result  = selectData($connection, $query);
						$vPurRef = $result[0];
						$vCostCentCode = $result[1];
						$vProjectCode  = $result[2];
						$vPurchaseType = $result[3];
						
						if ($vPurRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1) ||
							($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1)) {
							
							if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
							else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
							else $vProjCostCent = '';
							
							fbegin();
							$vPurRef = get_nextsequence('purchase_reference',$vProjCostCent,$connection);	
							fcommit();
							
							$query = " UPDATE purchases SET ".
									 " Purchase_Reference = $vPurRef ";
							if($txtPur_Othercharges != ''){
						$query = $query.",Purchase_othercharges = $txtPur_Othercharges, Purchase_otherchargesB1 = $Purchase_otherchargesB1, Purchase_otherchargesB2 = $Purchase_otherchargesB2 ";
						}		 
						$query = $query." WHERE Purchase_id = $SPurId ";
							
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error();
						
						}
						$pendingFlag = 1;
						if($Module_Purchase_Pending == 1 && $Login_Purchase_Pending == 1){
							if($vPurchaseType != 'PENDING') $pendingFlag = 1;
							else $pendingFlag = 1;
						}
						
					if ($Module_PostToJournal == 1 && $pendingFlag == 1 && (($FI_PostPurchase == 1 && $Restricted_Posting == 1) || $Restricted_Posting == 0)){
							$message = Create_PurchaseJv($SPurId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
						//echo $message; exit;
						}
						
						if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPurId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'purchases', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}

					// JP check Max last purchase Price and Update items
					$queryPurdetails = "select purchasedt_id, item_code , purchase_date from purchasesdt  WHERE Purchase_id = $SPurId ";
					$resPurDetails = mysql_query($queryPurdetails , $connection);
					while($rowPurDet = mysql_fetch_array($resPurDetails)){
						$querydays = "select ifnull(itemcostdays,30)  from purchasesetup";
							$resultDays  = selectData($connection, $querydays);
							$vCurdays = $resultDays[0];
 
						 
							$query ="call highestItemPurPricebyItem('".$rowPurDet[1]."','".$rowPurDet[2]."',$vCurdays)";
							if (!updateData($connection, $query, true)) {
									$message  = mysql_error();
									frollback();
								}
						// }
					}

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

else if( $mainmode == 'postToJournal' && $SPurId != ''){
	
	$message = Create_PurchaseJv($SPurId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);
	if($message == '') $message = "Purchase has been posted Successfully!";
}

if ($mode == "import"){
	
	
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (!isset($PPurCurr))	  		$PPurCurr = $base1;
	if (empty($PPurCategory))		$PPurCategory = 0;
	if (empty($PPurDiscountAmt))	$PPurDiscountAmt = 0;
	if (empty($PPurDiscount))		$PPurDiscount = 0;
	if (empty($PPurTotalAmount))	$PPurTotalAmount = 0;
			   
			   
	  $txtCostCentCodeDt = $PPurCostCentCode;
	  $txtProjectCodeDt = $PPurProjectCode;
	
	$PPurCostCentCode = "".$PPurCostCentCode;	
	if ($PPurCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if (empty($PPurProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'";   

	if (empty($PPurVatChkbx)) $PPurVatChkbx = 0;
	
	//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 ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$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.';
		}
	}*/
	
	//echo $txtCostCentCodeDt;
	
	//Insert Master Table
	if ($SPurId == "" && $ErrorExists == 0){
			
		fbegin();	
		$PPurId = get_nextsequence('Purchase_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, ".
					 " FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
					 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, ".
					 " TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, ".
					 " CustomsDebitAccount, CustomsCreditAccount ".
					 " FROM purchasesetup ";
				 
		$Acc_Result = selectData($connection, $Acc_Query);
		
		
		$Rate_Query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPurCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPurCurr."' )";
		$Rate_Result = selectData($connection, $Rate_Query);
		$vPurchaseRate = $Rate_Result[0];
		if (empty($vPurchaseRate)) $vPurchaseRate = 1;
		
		$Rate_Query1 = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$Rate_Result1 = selectData($connection, $Rate_Query1);
		$vPurchaseRateBase2 = $Rate_Result1[0];
		if (empty($vPurchaseRateBase2)) $vPurchaseRateBase2 = 0;
		
		else if ($PPurCurr == $base1) $vPurchaseRateBase1 = 1;
		else $vPurchaseRateBase1 = 0;

		fbegin();
		$query = " INSERT INTO temp_purchases (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_FreightCur, Purchase_CommissionsCur, ".
				 " Purchase_InsuranceCur, Purchase_ClearingCur, Purchase_CustomsCur, Purchase_OthersCur, Purchase_TransportCur, FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
				 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, CustomsDebitAccount, CustomsCreditAccount, ".
				 " Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, SrvNo, WaybillNo, Purchase_TotalAmount, User_Account, Logged_Code, Purchase_othercharges, Purchase_otherchargesB1, Purchase_otherchargesB2, supplier_code1) ".
				 " VALUES ( ".$PPurId.", Null, '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurRemark))."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', ".
				 "          '".$PPurCurr."', $ProjectCode, $CostCentCode, '".$PPurInvoiceNo."', '".insertMySQLDate($PPurMaturityDate)."', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPurDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPurVatChkbx, 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."', '".$PurchaseDefaultType."', 0, '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', ".
				 "          '".$PPurCurr."', '".$PPurCurr."', '".$PPurCurr."', '".$Acc_Result[7]."', '".$Acc_Result[8]."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', ".
				 "          '".$Acc_Result[12]."', '".$Acc_Result[13]."', '".$Acc_Result[14]."', '".$Acc_Result[15]."', '".$Acc_Result[16]."', '".$Acc_Result[17]."', '".$Acc_Result[18]."', ".
				 "          '".$Acc_Result[19]."', '".$Acc_Result[20]."', $vPurchaseRate, $vPurchaseRateBase1, $vPurchaseRateBase2, '".ereg_replace("'", "\'", trim($PPurSrvNo))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPurWaybillNo))."', $PPurTotalAmount, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', txtPur_Othercharges, $Purchase_otherchargesB1, $Purchase_otherchargesB2 , '".ereg_replace("'", "\'", trim($PPurSupplier1))."')";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		//$message = $query;
		if ($result){
			$SPurId = $PPurId;
			fcommit();
		}else{
			$PPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SPurId != "" && $SPurDtId == "" && $ErrorExists == 0){
	
	if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

		$image_name = addslashes($_FILES['image']['name']);
		$image_size = getimagesize($_FILES['image']['tmp_name']);
		$image_type =$_FILES['image']['type'];
		//	echo$_FILES['image']['size'];
			
		if ($image_size == FALSE) {
			$error['image'] = "That's not an image.";
		
		}
		else 
			if ($_FILES['image']['size'] > 204800) {
				$error['image'] = "Image is too large.";
			}
			else {
				$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
			}
	}
	
	$foldername='uploads';
	if (!file_exists($foldername)) {
		mkdir("./uploads", 0700);
	}

	$fileName = $_FILES["image"]["name"]; 
	$fileTmpLoc = $_FILES["image"]["tmp_name"];
	// Path and file name
	$pathAndName = "uploads/".$fileName;
	$pathAndName1 = "./uploads/".$fileName;
	// Run the move_uploaded_file() function here
	$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);



	
	require_once('Spreadsheet/Excel/Reader.php');
    $excel = new Spreadsheet_Excel_Reader();
    $excel->read($pathAndName1); 


	$x=1;
	$arrayemp = array();
	
    while($x<=$excel->sheets[0]['numRows']) { ///rowwwww
            
		$txtItemCode = $excel->sheets[0]['cells'][$x][1];
		$itemdesc = $excel->sheets[0]['cells'][$x][2];
		//$lstWarehouse = $excel->sheets[0]['cells'][$x][3];
		$txtPurDtQty = $excel->sheets[0]['cells'][$x][4];
		$txtPurDtPrice = $excel->sheets[0]['cells'][$x][5];
		
		
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1";
					 
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}

	
	
	
		if (empty($PPurDiscountAmt))
			$PPurDiscountAmt = 0;
		if (empty($PPurDiscount))
			$PPurDiscount = 0;
		
		if (empty($txtPurDtPrice))
			$txtPurDtPrice = 0;
		if (empty($txtPurDtDiscount))
		    $txtPurDtDiscount = 0;
		if (empty($txtPurDtQty))
		    $txtPurDtQty = 0;      		
		
		    $txtPurDtQty2 = 0;      			
		if (empty($txtPurDtChargePer))
		    $txtPurDtChargePer = 0;
		if (empty($txtPurDtChargeAmt))
		    $txtPurDtChargeAmt = 0; 
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
					
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";		
		
		$PPurCostCentCode = "".$PPurCostCentCode;	
		if ($PPurCostCentCode == '')	$CostCentCode = 'Null';
		else	$CostCentCode = "'".$PPurCostCentCode."'";
		
		$PPurProjectCode = "".$PPurProjectCode;	
		if ($PPurProjectCode == '')	$ProjectCode = 'Null';
		else	$ProjectCode = "'".$PPurProjectCode."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}		
		
		
		
		$vPurDtPriceTTC      = 0;
		$vPurDtPriceTTCBase1 = 0;
		$vPurDtPriceTTCBase2 = 0;					
		$vPurDtPrice      	 = 0;
		$vPurDtPriceBase1 	 = 0;
		$vPurDtPriceBase2 	 = 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;
		
		
		$WarningMsg = '';
		
		
		
		$sub_query = " SELECT Count(*) FROM Items WHERE Item_Code = '".trim(strtoupper($txtItemCode))."'";
		
		$sub_result = selectData($connection, $sub_query);
		
		//Item Code Not Exists Then Check For Barcode
		if ($sub_result[0] == 0) {
			$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$txtItemCode."' or item_barcode2 = '".$txtItemCode."' or item_barcode3 = '".$txtItemCode."'";
			$sub_result = selectData($connection, $sub_query);
			$txtItemCode = $sub_result[0];
			
			if ($txtItemCode == '' || empty($txtItemCode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
			}	
		}
		
		//Get Purchase Rates
		$PurRates = GetPurchaseRates($SPurId,$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		
		
		// Case Not Pack Item
		if ($ErrorExists == 0){
		
			$query = " SELECT ifNull(Item_Pack, 0) ".
					 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
			$result   = selectData($connection, $query);
			$ItemPack = $result[0];
		
			//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $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), Items.Item_WarehouseCode, ifNull(Item_VatType, 1) ".
						" FROM Items WHERE item_Code = '".$txtItemCode."'";
				$result = selectData($connection, $query);
				$item_vat 	   = $result[0];
				$Item_MaxQty   = $result[1];
				$ItemGroupCode = $result[2];
				$ItemProd 	   = $result[3];
				$ItemTTCInc	   = $result[4];
				$ItemUnit      = $result[5];
				$ItemNonStock  = $result[6];
				$lstWarehouse  = $result[7];
				$ItemVatType   = $result[9];
				//$item_vat = $item_vat/100;
				$tax_flag = 0;
				$notax_flag = 1;
				if ($item_vat > 0){
					$tax_flag = 1;
					$notax_flag = 0;
				}	
				
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
					$vItemUnit2Qty = $txtPurDtQty2;
				}	   
				
				fbegin();
				$txtPurDtId = get_nextsequence('Purchasedt_Id','',$connection);	
				fcommit();

				if ($PurchaseTTC == 1) {
					$vPurDtPriceTTC      = $txtPurDtPrice;
					$vPurDtPriceTTCBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPriceTTC, $connection);
					$vPurDtPriceTTCBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPriceTTC, $connection);
					
					//Added 2011/09/26
					if ($PPurVatChkbx == 1)	$vPurDtPrice = ($vPurDtPriceTTC / (1 + $item_vat/100));
					else $vPurDtPrice = $txtPurDtPrice;
						
					$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
					$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
							
				} else	{
					$vPurDtPrice      = $txtPurDtPrice;
					$vPurDtPriceBase1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtPrice, $connection);
					$vPurDtPriceBase2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtPrice, $connection);
					
					$vPurDtPriceTTC      = 0;
					$vPurDtPriceTTCBase1 = 0;
					$vPurDtPriceTTCBase2 = 0;
							
				}	
					
				$queryqtyexists = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', Now(), ".$txtPurDtId.", 'PI', '', '') QtyExists From Dual ";
				$result = selectData($connection, $queryqtyexists);
				$vItemQtyExists = 0;
				$vItemQtyExists = $result[0];
				$vItemQtyExists = $vItemQtyExists + $txtPurDtQty; 
					
				if ($vItemQtyExists > $Item_MaxQty)
					$WarningMsg = 'Quantity ('.$vItemQtyExists.') exceeds max quantity, Max= '.$Item_MaxQty.' for Item= '.$txtItemCode;
						
				
				// Calculation For Detail Discount Amount
				/*$vPurDtDiscAmt       = (($vPurDtPrice*$txtPurDtQty) - ($vPurDtPrice*$txtPurDtQty*$txtPurDtDiscount/100))*$PPurDiscount;
				$vPurDtDiscAmtBase1  = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $vPurDtDiscAmt, $connection);
				$vPurDtDiscAmtBase2  = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $vPurDtDiscAmt, $connection);
					
				$txtPurDtChargeAmtB1 = ConvertCurrencyRate($PPurCurr, $base1, insertMySQLDate($PPurDate), $vRate, $vRateB1, $txtPurDtChargeAmt, $connection);
				$txtPurDtChargeAmtB2 = ConvertCurrencyRate($PPurCurr, $base2, insertMySQLDate($PPurDate), $vRate, $vRateB2, $txtPurDtChargeAmt, $connection);
*/

				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 = '".$PPurSupplier."'";
												 
					$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 = '".$txtItemCode."'";
												 
					$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,  ".
						 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
						 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
						 " DebitAccountVATNonStock2, DebitAccountVATNonStock3 ".
						 " FROM purchasesetup ";
							 
				$result = selectData($connection, $query);
					
				$vPurStpDirectStkDbt    = $result[0];
				$vPurStpDirectStkCrd    = $result[1];
				$vPurStpDirectStkCur    = $result[2];	
				$vPurStpVatAcc          = $result[3];	
				$vPurStpDebitAcc        = $result[4];	
				$vPurStpVatNonStockAcc  = $result[5];	
				$vPurStpVatAcc2         = $result[6];
				$vPurStpVatAcc3         = $result[7];
				$vPurStpVatNonStockAcc2 = $result[8];
				$vPurStpVatNonStockAcc3 = $result[9];
				$vPurStpDebitAcc2       = $result[10];
				$vPurStpDebitAcc3       = $result[11];
				$vPurStpDebitVatAcc     = $result[12];
				$vPurStpDebitVatAcc2    = $result[13];
				$vPurStpDebitVatAcc3    = $result[14];
				$vPurStpDebitNonStockAcc  	 = $result[15];
				$vPurStpDebitNonStockAcc2 	 = $result[16];
				$vPurStpDebitNonStockAcc3 	 = $result[17];
				$vPurStpDebitVatNonStockAcc  = $result[18];
				$vPurStpDebitVatNonStockAcc2 = $result[19];
				$vPurStpDebitVatNonStockAcc3 = $result[20];
					
					
				$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 ($item_vat > 0 && $PPurVatChkbx == 1) {
						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)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}	
				
					if ($item_vat > 0 && $PPurVatChkbx == 1) {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
						}
					}	
					else {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
						}						
					}
				}
					
				$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
				if($item_vat=='')	
					$item_vat = 0;
				fbegin();
				$query = " INSERT INTO temp_purchasesdt (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_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
						 " Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code ) ".
						 " VALUES ( ".$txtPurDtId.", ".$PPurId.", '".$PPurCurr."', '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', 'PI',  ".
						 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".trim(strtoupper($txtItemCode))."', $txtPurDtQty, $vPurDtPrice, $vPurDtPriceBase1, $vPurDtPriceBase2, 0, $vPurDtDiscAmt, $vPurDtDiscAmtBase1, $vPurDtDiscAmtBase2, $item_vat, ".
						 "          Null, '' ,  '".$PPurInvoiceNo."',  Null, $txtPurDtChargePer, $txtPurDtChargeAmt, 0, 0, ".
						 "          $vPurDtPriceTTC, $vPurDtPriceTTCBase1, $vPurDtPriceTTCBase2, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
						 "          $vPurDtTax1, $vPurDtTax2, $vPurDtTax3, $vPurDtTax4, $vPurDtTax5, $vItemUnitCoef, $vItemUnit2Qty, Null, Null, '".$_SESSION['useraccount']."' ) ";
				//	$message  = $query; 
				//	frollback();exit;
				//echo $query."<br>";
				//exit;				
				$result=mysql_query($query,$connection);
								
					
				if ($result){
					fcommit();
				}else{
					$txtPurDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}				
				
			}	// End Case Not Pack Item
			
		}
		 $x++;  //end of looping in excell
	}

		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPurId, $PPurDate, $PPurVatChkbx, $PPurDiscount, 0, $PPurVatBase1, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Module_AdditionalTaxes, $FI_PurchasesVATMod, $PurchaseTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
		
	} // End Case Insert In Detail Tables

} 



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

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

//."&txtPurId=".$txtPurId
//if($mode == "post")
	//header ("Location: ./Form_Purchase.php?actionmode=post&mainaction=&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
if($mainmode == 'postToJournal')
	header ("Location: ./Form_PurchaseSearch.php?message=".$message);
else if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Purchase.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
	else
		header ("Location: ./Form_Purchase.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_PurchaseSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_PurchaseSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_Purchase.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_Purchase.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_PurchaseDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurId=".$SPurId."&PPurDate=".$PPurDate."&PPurDtId=".$SPurDtId."&message=".$message);		
else if ($mode == "import")		
	header ("Location: ./Form_Purchase.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_PurchaseSearch.php?PMode=1");	
else if ($mode == "" && $mainmode == "updateitemprice" )		
	header ("Location: ./Form_purchase_itemprice.php?closeWin=1");	
else if ($mode == "editqty" && $mainmode == "" )		
	header ("Location: ./Form_PurchaseEditQty.php");	
else if ($mode == "editqty1" && $mainmode == "" )			
	header ("Location: ./Form_PurchaseSerialNo.php");	
else if ($mode == "" && $mainmode == "LoadGrn" ) {
	if ($message == '')
		header ("Location: ./Form_Purchase_LoadGRN.php?PMode=1&PPurId=".$SPurId);	
	else 	
		header ("Location: ./Form_Purchase_LoadGRN.php?PMode=0&PPurId=".$SPurId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "loadporder" )		
	header ("Location: ./Form_Purchase_LoadPorder.php?PMode=1&PPurId=".$SPurId."&message=".$message);					
else if ($mode == "changerates")		
	header ("Location: ./Form_PurchaseRates.php?actionmode=rateschanged&mainaction=".$mainmode."&PPurId=".$SPurId."&message=".$message);
else if ($mode == "changecurrency")	
	header ("Location: ./Form_Purchase.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);
else if($mode == "submitrecord") {
    header ("Location: ./Form_PurchaseDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurId=".$PPurId."&PPurDate=".$PPurDate.
			"&PPurMaturityDate=".$PPurMaturityDate."&PPurSupplier=".$PPurSupplier."&PPurCurr=".$PPurCurr."&PPurProjectCode=".$PPurProjectCode.
			"&PPurCostCentCode=".$PPurCostCentCode."&PPurInvoiceNo=".$PPurInvoiceNo."&PPurDiscount=".$PPurDiscount."&PPurDiscountAmt=".$PPurDiscountAmt.
			"&PPurVatBase1=".$PPurVatBase1."&PPurVatChkbx=".$PPurVatChkbx."&lstWarehouse=".$lstWarehouse."&PPurRemark=".$PPurRemark."&message=".$message."&WarningMsg=".$WarningMsg	);
}

$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, $PVatBase1, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PModuleAdditionalTaxes, $PPurchasesVATMod, $PPurchaseTTC, $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;
	
	if (empty($PVatBase1)) $PVatBase1 = 0;

	$vPurDiscountPer = $PDiscPer;
	
	//Added 2011/09/26
	if ($PPurchaseTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_PurchasesDt SET  ".
				 " PurchaseDt_Price = PurchaseDt_PriceTTC, PurchaseDt_PriceBase1 = PurchaseDt_PriceTTCbase1, PurchaseDt_PriceBase2 = PurchaseDt_PriceTTCbase2 ".
				 " Where Purchase_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	else if ($PPurchaseTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE Temp_PurchasesDt SET  ".
				 " PurchaseDt_Price      = (PurchaseDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " PurchaseDt_PriceBase1 = (PurchaseDt_PriceTTCbase1 / (1 + Item_Vat/100)), ".
				 " PurchaseDt_PriceBase2 = (PurchaseDt_PriceTTCbase2 / (1 + Item_Vat/100)) ".
				 " Where Purchase_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	

						 
	//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_PurchasesDt ".
				 " Where Purchase_ID = ".$PId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
	
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

	//echo $sub_rows[4];
	
		$vPurDtTotal = $sub_rows[1];
		$vItemVat    = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$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);	
		}
					
	}			
	//exit;				
					
	$vPurGrossTotal = $vPurTaxable + $vPurNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vPurDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vPurDiscountPer > 0)
			$vPurDiscountAmt = (($vPurGrossTotal * $vPurDiscountPer) / 100);
	}				
			
	$query    = " SELECT Currency_Code FROM temp_purchases WHERE Purchase_id = $PId ";
	$result   = selectData($connection, $query);
	$vPurCurr = $result[0];	
	
	$query    = " SELECT base1, base2 FROM setup";
	$result   = selectData($connection, $query);
	$base1 = $result[0];
	$base2 = $result[1];


					
	$vPurNetTotal         = $vPurGrossTotal + $vPurVat - $vPurDiscountAmt;
	$vPurTaxableBase1     = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTaxable, $connection);
	$vPurTaxableBase2     = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTaxable, $connection);
	$vPurNoneTaxableBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurNoneTaxable, $connection);
	$vPurNoneTaxableBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurNoneTaxable, $connection);
	$vPurDiscountAmtBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurDiscountAmt, $connection);
	$vPurDiscountAmtBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurDiscountAmt, $connection);
	$vPurGrossTotalBase1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurGrossTotal, $connection);
	$vPurGrossTotalBase2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurGrossTotal, $connection);
	
	//If User Has Access To Modify Vat Base1
	if ($PPurchasesVATMod == 1)
		$vPurVatBase1 = $PVatBase1;
	else	
		$vPurVatBase1 = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurVat, $connection);
	
	$vPurVatBase2 = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurVat, $connection);
		//echo $vPurVatBase1 ."= ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurVat,";exit;
				

	$vPurTax1B1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTax1, $connection);
	$vPurTax1B2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTax1, $connection);		
	$vPurTax2B1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTax2, $connection);
	$vPurTax2B2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTax2, $connection);		
	$vPurTax3B1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTax3, $connection);
	$vPurTax3B2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTax3, $connection);		
	$vPurTax4B1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTax4, $connection);
	$vPurTax4B2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTax4, $connection);		
	$vPurTax5B1  = ConvertCurrencyRate($vPurCurr, $base1, insertMySQLDate($PDate), $PRate, $PRate1, $vPurTax5, $connection);
	$vPurTax5B2  = ConvertCurrencyRate($vPurCurr, $base2, insertMySQLDate($PDate), $PRate, $PRate2, $vPurTax5, $connection);	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_purchases 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;
		// echo $sub_query1;exit;				 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}

function GetPurchaseRates($PPurId,$connection) {

	$query = "Select Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2 From Temp_Purchases where Purchase_ID = '".$PPurId."'";
	//echo $query; exit;
	$result = selectData($connection, $query);
	
	Return $result;

}

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

HERE;
*/

?>