<?php

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

include("config.inc.php");
include("Functions_Sales.php");
include("function.inc.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 Execution 
ini_set('max_execution_time', $config['ReportTimeExecution']);

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
			 " ifNull(Module_rawmaterial,0) As Module_RawMaterial, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(Module_AutoReturnSales,0) As Module_AutoReturnSales, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ifNull(Module_Unit1Method,0) As Module_Unit1Method,  ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifnull(Module_ConfirmDR,0) as Module_ConfirmDR ". 
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$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']."' ".
 			   "";
			   
$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 SalesSetup Table
$querySalesSetup="Select SalesTTC, TipsAccount, CashCur From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}



//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ifNull(ModifyVAT,0) As ModifyVAT ".
		  " 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);
}

/*
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='insertsales' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SRSaId' value='$SRSaId'>
<input type='text' name='SRSaDtId' value='$SRSaDtId'>
<input type='text' name='SRSaVatChkbx' value='$SRSaVatChkbx'>
HERE;
*/
$message='';
//Submit Record Mode

if ($mode == "checkduplicate" ){


//$disc = GetDiscountValue($PItem,$vSaClient,$connection);


$query = " select  GetDiscountValue('".$vSaClient."','".$PItem."'),client_discountonInvoice,Client_PaymentTerms from Clients where ledger_number = '".$vSaClient."'";
$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_array($result);
$disc=$row[0];
$client_discountonInvoice=$row[1];
$Client_PaymentTerms=$row[2];
if($client_discountonInvoice=='') $client_discountonInvoice=0;
if($Client_PaymentTerms=='') $Client_PaymentTerms=0;

$query = " select  1 from temp_deliverydt where item_code='".$PItem."' and delivery_id = '".$SSaId."'";

$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_array($result);
echo $row[0];
echo "[BRK]";
echo $disc;
echo "[BRK]";
echo $client_discountonInvoice;
echo "[BRK]";
echo $Client_PaymentTerms;
exit;
}
else
if ($mode == "getclientname"){
	
		$query = "SELECT Ledger_number,Ledger_name ,client_discountonInvoice, currency_code
					FROM Clients ";
					
		if($choice==0)
			$query = $query." WHERE Upper(Ledger_number) = Upper('".str_replace('\\','\\\\',$clientcode)."') ";
		else
			$query = $query." WHERE Upper(Ledger_name) = Upper('".str_replace('\\','\\\\',$clientname)."') ";
					
		$result = selectData($connection, $query);
		$ClientCode = $result[0];
		$ClientName = $result[1];
		$client_discountonInvoice = $result[2];
		$currency_code = $result[3];
		echo $ClientCode;
		echo"[BRK]";
		echo $ClientName;
		echo"[BRK]";
		echo $client_discountonInvoice;
		echo"[BRK]";
		echo $currency_code;
 
exit;
}
else
if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	
	if (!isset($PRSaCurr)) $PRSaCurr = $base1;

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PRSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PRSaCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PRSaCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PRSaCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PRSaProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PRSaProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PRSaClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PRSaClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	if ($PRSaSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PRSaSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Salesman Code.';
		}
	}
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($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.';
		}
	}
	
	
	//Insert Master Table
	if ($SRSaId == "" && $ErrorExists == 0){
	
		if (empty($PRSaDiscountAmt))
			$PRSaDiscountAmt = 0;
		if (empty($PRSaDiscount))
			$PRSaDiscount = 0;
		if (empty($PRSaDirectReturn))
			$PRSaDirectReturn = 0;	
			
		if (empty($PRSaCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PRSaCostCentCode."'";
			
		if (empty($PRSaProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PRSaProjectCode."'";
			
		fbegin();	
		$PRSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
		// Get Vat Checkbox From Client
		/*$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PRSaClientCode."'";
		$result = selectData($connection, $query);
		$PRSaVatChkbx = $result[0];*/
		if($costcent_applyvat==0) $PRSaVatChkbx=0;
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PRSaCurr."') As CreditCur, ".
					 " CreditAccountReturn, TipsAccount, VatAccount, CreditVATReturn, PromotionAccount, TransportAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$PRSaClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			 
		fbegin();
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
				 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
				 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
				 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, Delivery_DirectReturn, User_Account, Logged_Code,Delivery_ManualNo) ".
				 " VALUES ( ".$PRSaId.", Null, '".insertMySQLDate($PRSaDate)."', '".insertMySQLDate($PRSaMaturityDate)."' , ".
				 "          '".ereg_replace("'", "\'", trim($PRSaRemark))."', '".ereg_replace("'", "\'", trim($PRSaClientCode))."', '".ereg_replace("'", "\'", trim($PRSaDAddress))."', '".ereg_replace("'", "\'", trim($PRSaVehicleNumber))."', ".
				 "          '".ereg_replace("'", "\'", trim($PRSaDriverName))."', '".ereg_replace("'", "\'", trim($PRSaSalesmanCode))."', '".$PRSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 'DR', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
				 "          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PRSaVatChkbx, $PRSaDirectReturn, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' 
				 , '".ereg_replace("'", "\'", trim($PSaManualNo))."' )";
					 
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SRSaId = $PRSaId;
			fcommit();
		}else{
			$PRSaId = "";
			$SRSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SRSaId != "" && $SRSaDtId == "" && $txtItemCode != "" && $ErrorExists == 0){
	
		if (empty($PRSaDiscountAmt))  $PRSaDiscountAmt = 0;
		if (empty($PRSaDiscount))	  $PRSaDiscount = 0;
		if (empty($PRSaDirectReturn)) $PRSaDirectReturn = 0;		
			
		if (empty($txtRSaDtPrice))	   $txtRSaDtPrice = 0;
		if (empty($txtRSaDtDiscount))  $txtRSaDtDiscount = 0;
		if (empty($txtRSaDtQty))	   $txtRSaDtQty = 0;  
		if (empty($txtRSaDtQty2))	   $txtRSaDtQty2 = 0;  
		
		if (empty($txtRSaDtExpireDate))		$vSaDtExpireDate = 'Null';
		else  $vSaDtExpireDate = "'".insertMySQLDate($txtRSaDtExpireDate)."'";  
		
			
		if (empty($PRSaCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PRSaCostCentCode."'";
			
		if (empty($PRSaProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PRSaProjectCode."'";	
			
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	
		
		
	
		$WarningMsg = '';
		
		$vSaDtPriceTTC      = 0;
		$vSaDtPriceTTCBase1 = 0;
		$vSaDtPriceTTCBase2 = 0;					
		$vSaDtPrice         = 0;
		$vSaDtPriceBase1    = 0;
		$vSaDtPriceBase2    = 0;
		$vSaDtCostBase1     = 0;
		$vSaDtCostBase2     = 0;
		$vSaDtDiscAmt       = 0;
		$vSaDtDiscAmtBase1  = 0;
		$vSaDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSaDtTax1 = 0;
		$vSaDtTax2 = 0;
		$vSaDtTax3 = 0;
		$vSaDtTax4 = 0;
		$vSaDtTax5 = 0;
		
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		// Case Not Pack Item
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
		if ($ItemPack != 1) {

			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0) ".
			        " FROM Items WHERE item_Code = '".$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];
			$ItemPromo     = $result[6];
			$ItemNonStock  = $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) {
				/*if ($ItemUnit > 0) {
					$vItemUnitCoef = 1/$ItemUnit;
					$vItemUnit2Qty = $vItemUnitCoef * $txtRSaDtQty;
				}*/
				
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $txtRSaDtQty2;
			}
			
			fbegin();
			$txtRSaDtId = get_nextsequence('deliverydt_id','',$connection);	
			fcommit();

			if ($Module_Delivery == 0) {
				//if item promotion the set price to zero
				if($ItemPromo == 1) $txtRSaDtPrice = 0;
				
				if ($SalesTTC == 1) {
					$vSaDtPriceTTC      = $txtRSaDtPrice;
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;

					//Added 2011/10/28
					if ($PRSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
					else $vSaDtPrice = $txtRSaDtPrice;					
				
					//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
					$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
					$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
							
				} else	{
					$vSaDtPrice      = $txtRSaDtPrice;
					$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
					$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
					
					$vSaDtPriceTTC      = 0;
					$vSaDtPriceTTCBase1 = 0;
					$vSaDtPriceTTCBase2 = 0;
							
				}	
					
				
				// Calculation For Detail Discount Amount
				$vSaDtDiscAmt       = ((($vSaDtPrice*$txtRSaDtQty) - ($vSaDtPrice*$txtRSaDtQty*$txtRSaDtDiscount/100))*$PRSaDiscount)/100;
				$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

				if ($Module_AdditionalTaxes == 1) {
				
					// Calculation of Item Tax Amounts
					$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
							 " FROM Clients ".
							 " WHERE Ledger_number = '".$PRSaClientCode."'";
										 
					$result = selectData($connection, $query);
					$vCltTax1 = $result[0];
					$vCltTax2 = $result[1];
					$vCltTax3 = $result[2];
					$vCltTax4 = $result[3];
					$vCltTax5 = $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 ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
					if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
					if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
					if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
					if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
						
				}
					
				

			} //End ($Module_Delivery == 0) 	
			
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditVATReturn, CreditAccountReturn, ".
					 " PromotionAccount, TipsAccount, CreditReturnNonStock, CreditVATReturnNonStock, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
					 " FROM salessetup ";
			$result = selectData($connection, $query);
					
			$vSaStpDirectStkDbt = $result[0];
			$vSaStpDirectStkCrd = $result[1];
			$vSaStpDirectStkCur = $result[2];	
			$vSaStpDiscAcc      = $result[3];	
			$vSaStpVatAcc       = $result[4];	
			$vSaStpCreditVatAcc = $result[5];	
			$vSaStpCreditAcc    = $result[6];	
			$vSaStpPromoAcc     = $result[7];
			$vSaStpTipsAcc      = $result[8];
			$vSaStpCreditNonStockAcc    = $result[9];
			$vSaStpCreditVatNonStockAcc = $result[10];
			$vSaStpVatNonStockAcc 	  	= $result[11];
			$vSaStpCreditExportAcc	 	= $result[14];
			
			$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".ereg_replace("'", "\'", trim($PRSaClientCode))."' ";	
			$resexp = mysql_query($queryexp,$connection);
			$rwexp = mysql_fetch_row($resexp);
			$clientexp = $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_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'SR' ".
					 " 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];
			$vTranStpDiscAcc         = $result[10];
			$vTranStpPromoAcc        = $result[11]; 
			$vTranStpTipsAcc         = $result[12]; 
			$vTransStpExportAcc 	 = $result[13];
			
			if ($Module_RawMaterial == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				$vSaDtTipsAcc      = $vTranStpTipsAcc;
						
				if ($item_vat > 0 && $PRSaVatChkbx == 1) {
					if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
					}
				}
				if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 		
			} 
			else {
				$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
				$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
				//$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
				$vSaDtTipsAcc      = $vSaStpTipsAcc;
				
				if ($item_vat > 0 && $PRSaVatChkbx == 1) {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
					else
						$vSaDtItemAcc = $vSaStpCreditVatAcc;
				} else {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
					else	
						$vSaDtItemAcc = $vSaStpCreditAcc;
				}

				if ($ItemNonStock == 1)
					$vSaDtVatAcc = $vSaStpVatNonStockAcc;
				else	
					$vSaDtVatAcc = $vSaStpVatAcc;
				if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc; 
			}
			
			$sub_queryVat = " SELECT GetVATAccount('".$PRSaClientCode."','".$vSaDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
			
			$query_cost = " select ifNull(MeanCostCur('".$txtItemCode."', '".insertMySQLDate($PRSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
			              " ifNull(MeanCostCur('".$txtItemCode."', '".insertMySQLDate($PRSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
			$result_cost = selectData($connection, $query_cost);
			
			$vSaDtCostBase1  = $result_cost[0];
			$vSaDtCostBase2  = $result_cost[1];
			if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
			if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
			$vSaDtCostBase2 = ConvertCurrency($PRSaCurr, $base2, insertMySQLDate($PRSaDate), $vSaDtCostBase1, $connection);	
			//echo $query_cost; exit;
			if($deliverydt_clientdiscount=='') $deliverydt_clientdiscount=0;
			if($deliverydt_itemdiscount=='') $deliverydt_itemdiscount=0;
			fbegin();
			$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
					 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
					 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
					 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_costbase1, Deliverydt_costbase2, ".
					 " DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,DeliveryDt_heatNo,deliverydt_clientdiscount,deliverydt_itemdiscount, DeliveryDt_REason ) ".
					 " VALUES ( ".$txtRSaDtId.", ".$PRSaId.", '".$PRSaCurr."', '".insertMySQLDate($PRSaDate)."', 'DR', '".ereg_replace("'", "\'", trim($PRSaClientCode))."',  ".
					 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$txtItemCode."', Null, $txtRSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $txtRSaDtDiscount, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
					 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($txtRSaDtRemark))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
					 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $ItemPromo,  ".
					 "          $vSaDtCostBase1, $vSaDtCostBase2, $vSaDtExpireDate, '".ereg_replace("'", "\'", trim($txtRSaDtBatchNo))."', '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','$deliverydt_heatno',$deliverydt_clientdiscount,$deliverydt_itemdiscount, '$DeliveryDt_REason' ) ";
			 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
			
			if ($result){
				fcommit();
			}else{
				$txtRSaDtId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
				
			
		}	// End Case Not Pack Item
		else {
		
			$promo_display = true;
			$promo_exhausted = 0;
			
			/*$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
						   " 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];
				$vPackDtPromo = $rowspackdt[4];
				$vPackDtPromoQty = $rowspackdt[5];
					
				// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
				if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
					
					if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
						//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
						$sub_query = " Select Sum(ifNull(DeliveryDt_Quantity,0)) ".
									 " From DeliveryDt ".
									 " Inner Join Deliveries on DeliveryDt.Delivery_id = Deliveries.Delivery_id ".
									 " Where DeliveryDt.Item_CodePacked = '".$txtItemCode."' ".
									 " And DeliveryDt.Item_Code = '".$vItemCode."' ".
									 " And ifNull(DeliveryDt.Deliverydt_OldData,0) = 0 ".
									 " And Deliveries.Journal_Type = 'DI' ".
									 " And Deliveries.Delivery_Date >= '".$rowspackdt[6]."' and Deliveries.Delivery_Date <= '".$rowspackdt[7]."' ";

						//echo "<br><br>".$sub_query;exit;
						$sub_result = selectData($connection, $sub_query);

						if ($vPackDtPromoQty <= ($sub_result[0] + $txtRSaDtQty*$vPackDtQty)){
							$promo_exhausted = 1;
						}
					}else{
						$promo_exhausted = 1;
					}
				
				}
				
				if ($promo_exhausted == 1) break;
			}	*/	
			
			fbegin();
			if ($promo_exhausted == 0){
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " 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];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
									
					

					fbegin();
					$vSaDtId = get_nextsequence('deliverydt_id','',$connection);
					fcommit();

					$vSaDtQty = $txtRSaDtQty*$vPackDtQty;
						
						
							
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$item_vat 	   = $result[0];
					$Item_MaxQty   = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd 	   = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemUnit      = $result[5];
					$ItemNonStock  = $result[6];
					
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0 && $PRSaVatChkbx == 1){
						$tax_flag = 1;
						$notax_flag = 0;
					}

					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						/*if ($ItemUnit > 0) {
							$vItemUnitCoef = 1/$ItemUnit;
							$vItemUnit2Qty = $vItemUnitCoef * $vSaDtQty;
						}*/
						
						$vItemUnitCoef = $ItemUnit;
						if ($Module_Unit1Method == 1)
							$vItemUnit2Qty = $vSaDtQty*$vItemUnitCoef;
						else	
							$vItemUnit2Qty = $vSaDtQty/$vItemUnitCoef;
					}	
							
					$vSaDtPriceTTC      = 0;
					$vSaDtPriceTTCBase1 = 0;
					$vSaDtPriceTTCBase2 = 0;					
					$vSaDtPrice   	    = 0;
					$vSaDtPriceBase1 	= 0;
					$vSaDtPriceBase2    = 0;
					$vSaDtCostBase1  	= 0;
					$vSaDtCostBase2  	= 0;
					$vSaDtDiscAmt       = 0;
					$vSaDtDiscAmtBase1  = 0;
					$vSaDtDiscAmtBase2  = 0;
							
					$vCltTax1 = 0;
					$vCltTax2 = 0;
					$vCltTax3 = 0;
					$vCltTax4 = 0;
					$vCltTax5 = 0;
					$vSaDtTax1 = 0;
					$vSaDtTax2 = 0;
					$vSaDtTax3 = 0;
					$vSaDtTax4 = 0;
					$vSaDtTax5 = 0;

					if ($Module_Delivery == 0) {	
						if ($SalesTTC == 1) {
							$vSaDtPriceTTC      = (($txtRSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
							$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

                            //Added 2011/10/28
							if ($PRSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
							else $vSaDtPrice = $vSaDtPriceTTC;								
									
							//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
									
						} else	{
							$vSaDtPrice      = (($txtRSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
									
							$vSaDtPriceTTC      = 0;
							$vSaDtPriceTTCBase1 = 0;
							$vSaDtPriceTTCBase2 = 0;
									
						}
								
							
						// Calculation For Detail Discount Amount
						$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$txtRSaDtDiscount/100))*$PRSaDiscount)/100;
						$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

						if ($Module_AdditionalTaxes == 1) {
							
							// Calculation of Item Tax Amounts
							$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
									 " FROM Clients ".
									 " WHERE Ledger_number = '".$PRSaClientCode."'";
													 
							$result = selectData($connection, $query);
							$vCltTax1 = $result[0];
							$vCltTax2 = $result[1];
							$vCltTax3 = $result[2];
							$vCltTax4 = $result[3];
							$vCltTax5 = $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 ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
							if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
							if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
							if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
							if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
									
						}		
							
							
						
					} //End if ($Module_Delivery == 0) 
						
						
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditVATReturn, CreditAccountReturn, ".
							 " PromotionAccount, TipsAccount, CreditReturnNonStock, CreditVATReturnNonStock, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
							 " FROM salessetup ";
					$result = selectData($connection, $query);
							
					$vSaStpDirectStkDbt = $result[0];
					$vSaStpDirectStkCrd = $result[1];
					$vSaStpDirectStkCur = $result[2];	
					$vSaStpDiscAcc      = $result[3];	
					$vSaStpVatAcc       = $result[4];	
					$vSaStpCreditVatAcc = $result[5];	
					$vSaStpCreditAcc    = $result[6];	
					$vSaStpPromoAcc     = $result[7];
					$vSaStpTipsAcc      = $result[8];
					$vSaStpCreditNonStockAcc    = $result[9];
					$vSaStpCreditVatNonStockAcc = $result[10];
					$vSaStpVatNonStockAcc 	  	= $result[11];
					$vSaStpCreditExportAcc	 	= $result[14];			
					
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".ereg_replace("'", "\'", trim($PRSaClientCode))."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $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_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'SR' ".
							 " 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];
					$vTranStpDiscAcc         = $result[10];
					$vTranStpPromoAcc        = $result[11]; 
					$vTranStpTipsAcc         = $result[12]; 
								
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
						$vSaDtPromoAcc     = $vTranStpPromoAcc;
						$vSaDtTipsAcc      = $vTranStpTipsAcc;
									
						if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
						}	
						if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						//$vSaDtVatAcc       = $vSaStpVatAcc;
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
						$vSaDtPromoAcc     = $vSaStpPromoAcc;
						$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
						if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}

						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAcc;
						else	
							$vSaDtVatAcc = $vSaStpVatAcc;
						if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc; 	
					}
						
					$sub_queryVat = " SELECT GetVATAccount('".$PRSaClientCode."','".$vSaDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
			 
					$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PRSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
								  " ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PRSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
					$result_cost = selectData($connection, $query_cost);
						
					$vSaDtCostBase1  = $result_cost[0];
					$vSaDtCostBase2  = $result_cost[1];
					if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
					if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
					$vSaDtCostBase2 = ConvertCurrency($PRSaCurr, $base2, insertMySQLDate($PRSaDate), $vSaDtCostBase1, $connection);			
					$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
							 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
							 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
							 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_costbase1, Deliverydt_costbase2, ".
							 " Item_QtyPacked, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_heatno, DeliveryDt_REason ) ".
							 " VALUES ( ".$vSaDtId.", ".$PRSaId.", '".$PRSaCurr."', '".insertMySQLDate($PRSaDate)."', 'DR', '".ereg_replace("'", "\'", trim($PRSaClientCode))."',  ".
							 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$vItemCode."', '".$vItemCodePacked."', $vSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $txtRSaDtDiscount, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
							 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($txtRSaDtRemark))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
							 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $vPackDtPromo,  ".
							 "          $vSaDtCostBase1, $vSaDtCostBase2, $vPackDtQty, $vSaDtExpireDate, '".ereg_replace("'", "\'", trim($txtRSaDtBatchNo))."', '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','".$deliverydt_heatno."', '".$DeliveryDt_REason."' ) ";
					 
					$result=mysql_query($query,$connection);
									
					//echo $query;
					
				} // End Loop Of Packdt
				
					
				if ($result){
					fcommit();
				}else{
					$txtRSaDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}	
			} else{
				$txtRSaDtId = "";
				$ErrorExists = 1;
				$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty / Period Exhausted";
				frollback();
			}
			
		} // End CasePack Item
		
		if ($ErrorExists == 0 && $Module_Delivery == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SRSaId, $PRSaDate, $PRSaVatChkbx, $PRSaDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
		
	} // End Case Insert In Detail Tables
	

} 
//Edit Detail Tables
else if (($mode == "editdt" || $mode == "editdt-ajax") && $SRSaId != "" && $SRSaDtId != ""){
		
	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if ($ErrorExists == 0) {
		if (empty($PRSaDirectReturn))  $PRSaDirectReturn = 0;		
		if (empty($txtRSaDtPrice))	   $txtRSaDtPrice = 0;
		if (empty($txtRSaDtDiscount))  $txtRSaDtDiscount = 0;
		if (empty($txtRSaDtQty))	   $txtRSaDtQty = 0;  
		if (empty($txtRSaDtQty2))	   $txtRSaDtQty2 = 0;     	
		
		if (empty($txtRSaDtExpireDate))		$vSaDtExpireDate = 'Null';
		else  $vSaDtExpireDate = "'".insertMySQLDate($txtRSaDtExpireDate)."'";  
		
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}
				
		$query = "SELECT Item_Vat, ifNull(Item_Promotion, 0), ifNull(Item_WithSerialNo,0) FROM Items WHERE item_Code = '".$txtItemCode."'";
		$result = selectData($connection, $query);
		$item_vat  = $result[0];
		$ItemPromo = $result[1];
		$ItemSerialNo = $result[2];
		//$item_vat = $item_vat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
			

		$vRSaCltCode  = '';
		$vRSaDiscount = 0;

		
		$vRSaDtPriceTTC      = 0;
		$vRSaDtPriceTTCBase1 = 0;
		$vRSaDtPriceTTCBase2 = 0;					
		$vRSaDtPrice      	= 0;
		$vRSaDtPriceBase1 	= 0;
		$vRSaDtPriceBase2 	= 0;
		$vRSaDtDiscAmt       = 0;
		$vRSaDtDiscAmtBase1  = 0;
		$vRSaDtDiscAmtBase2  = 0;

		if ($Module_Delivery == 0) {
			$query = " Select Currency_code, ifNull(Delivery_Taxable,0), ifNull(Delivery_NoneTaxable,0), ifNull(Delivery_DiscountPer,0), Client_code ".
					 " From Temp_Deliveries As Deliveries ".
					 " Where Delivery_ID = '".$SRSaId."' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
					 
			
			$result=mysql_query($query,$connection) or die(mysql_error());
			$rows=mysql_fetch_array($result);
			
			$vRSaCurr        = $rows[0];
			//$vRSaTaxable     = $rows[1];
			//$vRSaNoneTaxable = $rows[2];
			$vRSaDiscount    = $rows[3];
			$vRSaCltCode     = $rows[4];
			
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRSaCurr."' 
						and Curdt_date <= '".insertMySQLDate($PRSaDate)."')";
			$result = selectData($connection, $query);
			$rate_dt = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' 
						and Curdt_date <= '".insertMySQLDate($PRSaDate)."')";
			$result = selectData($connection, $query);
			$rate_dt1 = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' 
					and Curdt_date <= '".insertMySQLDate($PRSaDate)."')";
			$result = selectData($connection, $query);
			$rate_dt2 = $result[0];
			
			
			
			//if item promotion then set price to zero
			//if($ItemPromo == 1) $txtRSaDtPrice = 0;
			
			if ($SalesTTC == 1) {
				$vRSaDtPriceTTC      = $txtRSaDtPrice;
				$vRSaDtPriceTTCBase1 = ($vRSaDtPriceTTC*$rate_dt)/$rate_dt1;
				$vRSaDtPriceTTCBase2 = ($vRSaDtPriceTTC*$rate_dt)/$rate_dt2;	

				if ($PRSaVatChkbx == 1)	$vRSaDtPrice = ($vRSaDtPriceTTC / (1 + $item_vat/100));
				else $vRSaDtPrice = $txtRSaDtPrice;	
				
				//$vRSaDtPrice      = ($vRSaDtPriceTTC / (1 + $item_vat/100));
				$vRSaDtPriceBase1 = ($vRSaDtPrice*$rate_dt)/$rate_dt1;
				$vRSaDtPriceBase2 = ($vRSaDtPrice*$rate_dt)/$rate_dt2;
							
			} else	{
				$vRSaDtPrice      = $txtRSaDtPrice;
				$vRSaDtPriceBase1 = ($vRSaDtPrice*$rate_dt)/$rate_dt1;
				$vRSaDtPriceBase2 = ($vRSaDtPrice*$rate_dt)/$rate_dt2;
					
				$vRSaDtPriceTTC      = 0;
				$vRSaDtPriceTTCBase1 = 0;
				$vRSaDtPriceTTCBase2 = 0;
							
			}	
					
			
			// Calculation For Detail Discount Amount
			$vRSaDtDiscAmt       = ((($vRSaDtPrice*$txtRSaDtQty) - ($vRSaDtPrice*$txtRSaDtQty*$txtRSaDtDiscount/100))*$vRSaDiscount)/100;
			$vRSaDtDiscAmtBase1  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt1;
			$vRSaDtDiscAmtBase2  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt2;		

		} //End if ($Module_Delivery == 0) 
		
		
		if ($deliverydt_clientdiscount=='')
				$deliverydt_clientdiscount = 0; 
				
		if ($deliverydt_itemdiscount=='')
				$deliverydt_itemdiscount = 0;      	  

		
		fbegin();
		
		if ($Module_Delivery == 0) {
			$query = " UPDATE temp_deliverydt SET  ".
					 " DeliveryDt_Quantity = $txtRSaDtQty, Item_Unit2Qty = $txtRSaDtQty2, DeliveryDt_Price = $vRSaDtPrice, DeliveryDt_PriceBase1 = $vRSaDtPriceBase1, ".
					 " DeliveryDt_PriceBase2 = $vRSaDtPriceBase2, DeliveryDt_DiscountPer = $txtRSaDtDiscount, DeliveryDt_PriceTTC = $vRSaDtPriceTTC, ".
					 " Deliverydt_priceTTCBase1 = $vRSaDtPriceTTCBase1, Deliverydt_priceTTCBase2 = $vRSaDtPriceTTCBase2, DeliveryDt_Remark = '".ereg_replace("'", "\'", trim($txtRSaDtRemark))."', ".
					 " Deliverydt_DiscountAmount = $vRSaDtDiscAmt, Deliverydt_DiscountBase1 = $vRSaDtDiscAmtBase1, Deliverydt_DiscountBase2 = $vRSaDtDiscAmtBase2, ".
					 " DeliveryDt_ExpireDate = $vSaDtExpireDate, DeliveryDt_BatchNo = '".ereg_replace("'", "\'", trim($txtRSaDtBatchNo))."'
					 , deliverydt_heatno = '$deliverydt_heatno' 
					 , deliverydt_clientdiscount='$deliverydt_clientdiscount'
					 , deliverydt_itemdiscount='$deliverydt_itemdiscount'
					 , DeliveryDt_REason='$DeliveryDt_REason'
					 ";
					 
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCent_Code = $CostCentCodeDt ";
				
			//Allow Edit Warehouse If Direct Return
			if ($PRSaDirectReturn == 1 && ($Module_SerialNo == 0 || $ItemSerialNo == 0))
				$query = $query.", Warehouse_Code = '".$lstWarehouse."' ";
			
			$query = $query." Where DeliveryDt_ID = ".$SRSaDtId;
			
		} else {
			$query = " UPDATE temp_deliverydt SET  ".
					 " DeliveryDt_Quantity = $txtRSaDtQty, Item_Unit2Qty = $txtRSaDtQty2, ".
					 " DeliveryDt_Remark = '".ereg_replace("'", "\'", trim($txtRSaDtRemark))."', ".
					 " DeliveryDt_ExpireDate = $vSaDtExpireDate, DeliveryDt_BatchNo = '".ereg_replace("'", "\'", trim($txtRSaDtBatchNo))."', deliverydt_heatno = '$deliverydt_heatno', DeliveryDt_REason='$DeliveryDt_REason'  ";
					 
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCent_Code = $CostCentCodeDt ";
				
			$query = $query." Where DeliveryDt_ID = ".$SRSaDtId;
			
		}	
						 
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			fcommit();
				
			if ($Module_Delivery == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SRSaId, $PRSaDate, $PRSaVatChkbx, $vRSaDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'U', $connection);
				$message  = $message . $CalculateResult;
			}
				
		}else{
			$message  = mysql_error(); 
			frollback();
		}
			
	}
} 
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 1;
	$ErrorExists = 0;
	$message  = '';
	
	
	if ($AllowDelete == 1) {
		//Check Each DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.DeliveryDt_ID = '".$SRSaDtId."' ".
				 " And DeliveryDt.Journal_Type = 'DR' ".
				 " And SalesDt.Journal_Type = 'SR' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SalesExists = $result[0];
		
		
		if (empty($SalesExists)) $SalesExists = 0;
		
		if ($SalesExists > 0 ){
			$message  = 'Delete not allowed, item returned.';
			$AllowDelete = 0;
		}
	
	}
	
	if ($AllowDelete == 1) {
		//Check Each DeliveryDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_DeliveryDt As DeliveryDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = DeliveryDt.DeliveryDt_Id ".
				 " Where DeliveryDt.DeliveryDt_ID = '".$SRSaDtId."' ".
				 " And DeliveryDt.Journal_Type = 'DR' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'DR' ";
 
		$result = selectData($connection, $query);
		$SerNoUsedExists = $result[0];
		
		if ($SerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$AllowDelete = 0;
		}
	
	}
	
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

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

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];
		
		
		$querypack = " SELECT DeliveryDt.Item_CodePacked, DeliveryDt.Item_code ".
					 " FROM Temp_DeliveryDt As DeliveryDt ".
					 " Where DeliveryDt.DeliveryDt_ID = '".$SRSaDtId."'";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error($connection));
		$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  = '".$SRSaDtId."'".
					 " AND Journal_Type = 'DR' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error($connection); 
				
			
			// Delete From TempDeliveryDt For Selected Record
			$query = " DELETE FROM Temp_DeliveryDt ".
					 " WHERE DeliveryDt_id = '".$SRSaDtId."'";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error($connection);
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
			
			
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select DeliveryDt_ID, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code  ".
					   " From Temp_DeliveryDt As DeliveryDt  ".
					   " Where DeliveryDt.Delivery_ID = '".$SRSaId."' ".
					   " And DeliveryDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
					   //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error($connection));
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vRSaDtId =	$rowsdt[0];
				
				// Delete From TempPucrhasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						" WHERE PurchaseDt_id  = '".$vRSaDtId."' ".
						" AND Journal_Type = 'DR' ";
						//" And Logged_Code = '".$_SESSION['useraccount']."' ";
						
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error($connection); 		
						
				// Delete From TempDeliveryDt For Selected Record
				$query = " DELETE FROM Temp_DeliveryDt ".
						 " WHERE DeliveryDt_id = '".$vRSaDtId."' ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error($connection); 
					$ErrorExists = 1;
					frollback();
				}	
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
			
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 && $Module_Delivery == 0){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SRSaId, $txtDate, $SRSaVatChkbx, $txtRSaDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} 
	
	} // End If No Constraints Found On Delete
	
	
}

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

	$AllowDelete = 1;
	$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(Delivery_Date,'%d/%m/%Y') FROM Deliveries WHERE Delivery_id = ".$SRSaId;
		$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 Sales Is Posted
	$query = "SELECT ifNull(Delivery_Posted,0) As DeliveryPosted FROM Deliveries WHERE Delivery_id = '".$SRSaId."'";
	$result = selectData($connection, $query);
	$SaPosted = $result[0];
	
	if ($SaPosted == 1 ){
		$message  = 'Delete not allowed, delivery posted.';
		$AllowDelete = 0;
	}
	
	
	if ($AllowDelete == 1) {
		//Check Each DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.Delivery_ID = '".$SRSaId."' ".
				 " And DeliveryDt.Journal_Type = 'DR' ".
				 " And SalesDt.Journal_Type = 'SR' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SalesExists = $result[0];
		
		if (empty($SalesExists)) $SalesExists = 0;
		
		if ($SalesExists > 0 ){
			$message  = 'Delete not allowed, item(s) returned.';
			$AllowDelete = 0;
		}
	
	}
	
			
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
		$sub_query = " Select Journal_Id From Deliveries Where Delivery_id = '".$SRSaId."'";
		$sub_result = selectData($connection, $sub_query);
		$vSaJournalID = $sub_result[0];
		if(empty($vSaJournalID)) $vSaJournalID = -1;
		
		
		//Update Used Serials Set USed=0 For Related Delivery Serials
		$sub_query = " SELECT RelatedSerial_Id FROM Purchasesserialno ".
					 " WHERE PurchaseDt_id In (Select DeliveryDt_id From DeliveryDt Where Delivery_id = '".$SRSaId."' ) ".
					 " AND Journal_Type = 'DR' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
		
			$sub_query1 = " UPDATE purchasesserialno ".
						  " Set SerialNo_Used = 0 ".
						  "	WHERE Serial_ID = '".$sub_rows[0]."'";
						  
			if (!updateData($connection, $sub_query1, true))		 
				$message  = mysql_error(); 		  
		}	
				
		
		
		
		// Delete From PurchasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE PurchaseDt_id In (Select DeliveryDt_id From DeliveryDt Where Delivery_id = '".$SRSaId."' ) ".
				 " AND Journal_Type = 'DR' ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
			
			if (updateData($connection, $query, true)) {
			$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					if($config['log_file'] == 1){
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SRSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'return_delivery', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		// Delete From DeliveryDt For Selected Record
		$query = " DELETE FROM DeliveryDt ".
				 " WHERE Delivery_id = '".$SRSaId."'";
					 
		
			// Delete From Deliveries For Selected Record
			$query = " DELETE FROM Deliveries ".
					 " WHERE Delivery_id = '".$SRSaId."'";
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
			if ($vSaJournalID != -1) {
				
				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vSaJournalID;
				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	

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

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

	// Delete From TempPurchasesSerialNo For Selected Record
	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE PurchaseDt_id In (Select DeliveryDt_id From Temp_DeliveryDt Where Delivery_id = ".$SRSaId." ) ".
			 " AND Journal_Type = 'DR' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 

		
	// Delete From TempDeliveryDt For Selected Record
	$query = " DELETE FROM Temp_DeliveryDt ".
			 " WHERE Delivery_id = ".$SRSaId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempDeliveries For Selected Record
		$query = " DELETE FROM Temp_Deliveries ".
				 " WHERE Delivery_id = ".$SRSaId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SRSaId != ''){

	$ErrorExists = 0;
	$AllowEdit = 1;
	$message  = '';
	
	if ($AllowEdit == 1 && $Module_Delivery == 1) {
		//Check Each DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.Delivery_ID = '".$SRSaId."' ".
				 " And DeliveryDt.Journal_Type = 'DR' ".
				 " And SalesDt.Journal_Type = 'SR' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$ReturnSalesExists = $result[0];
		
		if (empty($ReturnSalesExists)) $ReturnSalesExists = 0;
		
		if ($ReturnSalesExists > 0 ){
			$message  = 'Edit not allowed, item(s) returned.';
			$AllowEdit = 0;
		}
	
	}
	
			
	
	//If No Constraints Exists On Delete
	if ($AllowEdit == 1) {
	
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
				 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
				 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
				 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
				 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
				 " Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef, Delivery_VatChkbx, Delivery_DirectReturn, Delivery_CashCur, Delivery_CashAccount, Delivery_Cash, Delivery_CashBase1, Delivery_CashBase2, Delivery_CashInBase1, ".
				 " Delivery_CashOutBase1, Delivery_CashInBase2, Delivery_CashOutBase2, Delivery_TipsBase1, Delivery_TipsAccount, User_Account, Logged_Code,Delivery_ManualNo, related_schemaname) ".
				 " SELECT Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
				 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
				 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
				 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
				 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
				 " Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef, Delivery_VatChkbx, Delivery_DirectReturn, Delivery_CashCur, Delivery_CashAccount, Delivery_Cash, Delivery_CashBase1, Delivery_CashBase2, Delivery_CashInBase1, ".
				 " Delivery_CashOutBase1, Delivery_CashInBase2, Delivery_CashOutBase2, Delivery_TipsBase1, Delivery_TipsAccount, User_Account, '".$_SESSION['useraccount']."',Delivery_ManualNo, related_schemaname ".
				 " FROM Deliveries ".
				 " WHERE Delivery_id = '".$SRSaId."'";
				 
		//echo $message.$query; exit;				 	
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			$message  = mysql_error(); 	
		}	


		if ($ErrorExists == 0) {
		
			$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
					 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
					 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
					 " Deliverydt_ItemAccount, Deliverydt_discountacc, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, ".
					 " Deliverydt_promotion, RelatedDt_Id, User_Account, Item_UnitCoef, Item_Unit2Qty, Deliverydt_costbase1, Deliverydt_costbase2, DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, ".
					 " DeliveryDt_TransportAmountBase2, Item_QtyPacked, Related_Ref, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, Logged_Code,deliverydt_heatno,deliverydt_clientdiscount,deliverydt_itemdiscount, DeliveryDt_REason ) ".
					 " SELECT DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
					 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
					 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
					 " Deliverydt_ItemAccount, Deliverydt_discountacc, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, ".
					 " Deliverydt_promotion, RelatedDt_Id, User_Account, Item_UnitCoef, Item_Unit2Qty, Deliverydt_costbase1, Deliverydt_costbase2, DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, ".
					 " DeliveryDt_TransportAmountBase2, Item_QtyPacked, Related_Ref, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, '".$_SESSION['useraccount']."',deliverydt_heatno,deliverydt_clientdiscount,deliverydt_itemdiscount, DeliveryDt_REason ".
					 " FROM Deliverydt ".
					 " WHERE Delivery_id = '".$SRSaId."'";
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 			


			$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
					 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.DeliveryDt_ID, Purchasesserialno.PurchaseDt_id, Purchasesserialno.Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, ".
					 " SerialNo_QuantitySold, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$_SESSION['useraccount']."' ".
					 " FROM Purchasesserialno ".
					 " Inner Join Temp_DeliveryDt on Purchasesserialno.PurchaseDt_id = Temp_DeliveryDt.DeliveryDt_ID ".
					 " WHERE Temp_DeliveryDt.Delivery_id = '".$SRSaId."' ".
					 " AND Temp_DeliveryDt.Journal_Type = 'DR' ".
					 " AND Purchasesserialno.Journal_Type = 'DR' ";
					 
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 
		}
	}	
}

else if( $mainmode == 'confirmreturndelivery' && $SRSaId != '' ){
	$confirm_flag     = 1;
	$retDelivery_confirm   = 0;
	
	$query = " SELECT ifNull(Delivery_Confirmed,0) FROM deliveries WHERE delivery_id = '".$SRSaId."'";
	//echo "<br><br>".$query;exit;
	$result = selectData($connection, $query);
	$retDelivery_confirm   = $result[0];
	
	if ($confirm_flag == 1 && $retDelivery_confirm == 0) {
		$query = "UPDATE deliveries SET Delivery_Confirmed = 1 WHERE delivery_id = '".$SRSaId."'";

		if (updateData($connection, $query, true))
		{	
			$query1 = "update deliverydt set confirmDR = 1 where delivery_id = '".$SRSaId."'";
			$res = mysql_query($query1,$connection);
			$message = Create_DeliveryJv($SRSaId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
			if($message == '')
			$message = "Return Deliveries Confirmed";
				
		}
		else
			$message  = mysql_error();
		
	} 
}
//Load Invoices
else if($mainmode == "loadinvoice"){
	$Scemaname = $_GET['Scemaname'];
	if($Scemaname == '') $Scemaname = "NULL";
	else $Scemaname = "'".$Scemaname."'";
	if ($SRSaId == ""){		 
		fbegin();	
		$vRSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
		
		if ($Module_Delivery == 0) {	
			$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
					 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
					 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
					 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
					 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
					 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
					 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_SorderReferences, Detail_Code, Delivery_TaxableTTC, Delivery_DiscountTTC, Delivery_ReturnRef, Delivery_VatChkbx, User_Account, Logged_Code) ".
					 " SELECT $vRSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), concat('Invoice ',Delivery_Reference,' - ',date_format(Delivery_Date,'%d-%m-%Y')), Deliveries.Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Deliveries.Salesman_Code, ".
					 " Deliveries.Currency_Code, Deliveries.Project_Code, Deliveries.Costcent_code, 0, 0, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
					 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
					 " 0, Delivery_Mode, 'DR', Null, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
					 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
					 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
					 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_SorderReferences, Deliveries.Detail_Code, Delivery_TaxableTTC, Delivery_DiscountTTC, Delivery_Reference, Delivery_VatChkbx, Deliveries.User_Account, ".
					 " '".$_SESSION['useraccount']."' ".
					 " From Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
					 " Where Delivery_ID = '".$SelectedRec."' ".
					 " And Deliveries.Journal_Type = 'DI' ";
		} else {
			$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
					 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, ".
					 " Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
					 " Delivery_CREDITACC, Delivery_BelongsToGroup, Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef,related_schemaname, User_Account, Logged_Code) ".
					 " SELECT $vRSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), concat('Invoice ',Delivery_Reference,' - ',date_format(Delivery_Date,'%d/%m/%Y')), Deliveries.Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Deliveries.Salesman_Code, ".
					 " Deliveries.Currency_Code, Deliveries.Project_Code, Deliveries.Costcent_code, 0, 0, 0, Delivery_Mode, 'DR', Null, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, ".
					 " Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
					 " Delivery_CREDITACC, Delivery_BelongsToGroup, Delivery_SorderReferences, Deliveries.Detail_Code, Delivery_Reference,$Scemaname, Deliveries.User_Account, '".$_SESSION['useraccount']."' ".
					 " From Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
					 " Where Delivery_ID = '".$SelectedRec."' ".
					 " And Deliveries.Journal_Type = 'DI' ";
		}
			//echo $query."<br>";exit;	
		$result=mysql_query($query,$connection);
	
		
		if ($result){
			$SRSaId = $vRSaId;
			fcommit();
		}else{
			$vRSaId = "";
			$SRSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
		
	}
	
	
	if ($SRSaId != '') 
    {   	
		$ErrorExists = 0;
		
		$vRSaId = $SRSaId;
		
		
		$sub_query = " SELECT Currency_Code, Delivery_Date, Client_Code, Project_Code, Costcent_code, ifNull(Delivery_DiscountPer,0), ".
					 " Date_Format(Delivery_Date,'%d/%m/%Y') As DeliveryDate, ifNull(Delivery_VatChkbx,0) As Delivery_VatChkbx ".
					 " FROM Temp_Deliveries ".
					 " WHERE Delivery_ID = '".$vRSaId."' ";
		$sub_result = selectData($connection, $sub_query);
		
		$vRSaDiscountPer = $sub_result[5];				   
		if (empty($vRSaDiscountPer)) $vRSaDiscountPer = 0;
		
		$vRSaCurr       = $sub_result[0];
		$vRSaClientCode = $sub_result[2];
		$vRSaDate       = $sub_result[6];
		$vRSaVatChkbx   = $sub_result[7];
		
		
		$sub_query = " SELECT DeliveryDt.DeliveryDt_id, DeliveryDt.Currency_Code, now(), DeliveryDt.Client_Code, DeliveryDt.Project_Code, DeliveryDt.CostCent_Code, DeliveryDt.Warehouse_Code, DeliveryDt.Item_code, ".
					 " DeliveryDt.Item_CodePacked, DeliveryDt.Item_QtyPacked, ifNull(DeliveryDt_Quantity,0), ifNull(DeliveryDt.DeliveryDt_Price,0), ifNull(DeliveryDt.DeliveryDt_PriceBase1,0), ifNull(DeliveryDt.DeliveryDt_PriceBase2,0), ".
					 " ifNull(DeliveryDt.DeliveryDt_DiscountPer,0), ifNull(DeliveryDt.Item_Vat,0), ifNull(DeliveryDt.DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ".
					 " ifNull(Deliverydt_costbase1,0), ifNull(Deliverydt_costbase2,0), Item_UnitCoef, Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
					 " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ifNull(DeliveryDt_promotion,0), ".
					 " DeliveryDt.User_Account, Deliveries.Delivery_Reference, ifNull(Deliveries.Delivery_DiscountPer,0), DeliveryDt.DeliveryDt_ExpireDate, DeliveryDt.DeliveryDt_BatchNo, DeliveryDt.DeliveryDt_TipsAccount, DeliveryDt_REason ".
					 " FROM DeliveryDt Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ";
		
		if($SRSaDtId != '')			 
			$sub_query = $sub_query." WHERE DeliveryDt.DeliveryDt_Id In (".$SRSaDtId.") And DeliveryDt.Journal_Type = 'DI' ";
		else 
			$sub_query = $sub_query." WHERE DeliveryDt.Delivery_Id = '".$SelectedRec."' And DeliveryDt.Journal_Type = 'DI' ";		
			
		
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
		    extract($sub_row);
			$vRSaDtDiscPer       = 0;
			$vRSaDtDiscAmt       = 0;
			$vRSaDtDiscAmtBase1  = 0;
			$vRSaDtDiscAmtBase2  = 0;
			
			$invoicedt = 'invoicedt'.$sub_row[0];
			
			$sub_query1 = " Select ifNull(Sum(ifNull(DR.DeliveryDt_Quantity,0)),0) As QuantityReturned ".
					      " From DeliveryDt DR ".
					      " Where DR.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And DR.Journal_Type = 'DR' ";
			$sub_result1 = selectData($connection, $sub_query1);
			if ($sub_result1[0] == '') $sub_result1[0] = 0;
	
	
			$sub_query2 = " Select Sum(ifNull(Temp_DeliveryDt.DeliveryDt_Quantity,0)) As QuantityReturnedTemp ".
					      " From Temp_DeliveryDt ".
					      " Where Temp_DeliveryDt.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And Temp_DeliveryDt.Journal_Type = 'DR' ".
						  " And Temp_DeliveryDt.Delivery_ID = '".$vRSaId."' ";
			$sub_result2 = selectData($connection, $sub_query2);
			if ($sub_result2[0] == '') $sub_result2[0] = 0;		  
			     
			
			
			//Get The Remaining Qty
			$vRSaDtQty = ($sub_row[10] - ($sub_result1[0] + $sub_result2[0]));
			
			if ($vRSaDtQty > 0 && ( $$invoicedt == 1 || $SRSaDtId != '') ) {
			
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRSaCurr."' )";
				$result = selectData($connection, $query);
				$rate_dt = $result[0];
					
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
				$result = selectData($connection, $query);
				$rate_dt1 = $result[0];
					
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
				$result = selectData($connection, $query);
				$rate_dt2 = $result[0];
				
				$vRSaDtDiscPer = $sub_row[14];
				
				if ($SelectedRec == '') { //If Selecting Items From Many Invoices
					//If Item Discount Is Zero And The Invoice Has Discount
					if ($vRSaDtDiscPer == 0 && $sub_row[38] > 0)
						$vRSaDtDiscPer = $sub_row[38];
				}
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $sub_row[21];
					if ($Module_Unit1Method == 1)
						$vItemUnit2Qty = $vRSaDtQty*$vItemUnitCoef;
					else	
						$vItemUnit2Qty = $vRSaDtQty/$vItemUnitCoef;
				}
				
				// Calculation For Detail Discount Amount
				$vRSaDtDiscAmt       = ((($sub_row[11]*$vRSaDtQty) - ($sub_row[11]*$vRSaDtQty*$vRSaDtDiscPer/100))*$vRSaDiscountPer)/100;
				$vRSaDtDiscAmtBase1  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vRSaDtDiscAmtBase2  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt2;

				$query_cost = " select ifNull(MeanCostCur('".$sub_row[7]."', '".$sub_row[2]."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".$sub_row[7]."', '".$sub_row[2]."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				$vRSaDtCostBase1  = $result_cost[0];
				$vRSaDtCostBase2  = $result_cost[1];
				if (empty($vRSaDtCostBase1)) $vRSaDtCostBase1 = 0;
				if (empty($vRSaDtCostBase2)) $vRSaDtCostBase2 = 0;
				//echo $query_cost; exit;
				$vSaDtCostBase2 = ConvertCurrency($sub_row[1], $base2, $sub_row[2], $vRSaDtCostBase1, $connection);	
				
				$DeliveryDt_ExpireDate = $sub_row[39];
				if (empty($DeliveryDt_ExpireDate)) $DeliveryDt_ExpireDate = 'Null';
				else $DeliveryDt_ExpireDate = "'".$DeliveryDt_ExpireDate."'";
				
				$ProjectCode = $sub_row[4];
				if (empty($ProjectCode)) $ProjectCode = 'Null';
				else $ProjectCode = "'".$ProjectCode."'";
				
				$CostCentCode = $sub_row[5];
				if (empty($CostCentCode)) $CostCentCode = 'Null';
				else $CostCentCode = "'".$CostCentCode."'";
				
				$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0) ".
						 " FROM Items WHERE item_Code = '".$sub_row[7]."'";
				$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];
				
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditVATReturn, CreditAccountReturn, ".
						 " CreditReturnNonStock, CreditVATReturnNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
						 " FROM salessetup ";
								 
				$result = selectData($connection, $query);
						
				$vSaStpDirectStkDbt = $result[0];
				$vSaStpDirectStkCrd = $result[1];
				$vSaStpDirectStkCur = $result[2];	
				$vSaStpDiscAcc      = $result[3];	
				$vSaStpCreditVatAcc = $result[4];	
				$vSaStpCreditAcc    = $result[5];	
				
				$vSaStpCreditNonStockAcc    = $result[6];
				$vSaStpCreditVatNonStockAcc = $result[7];
				$vSaStpVatAcc 		  	  	= $result[8];
				$vSaStpVatNonStockAcc 	  	= $result[9];
				$vSaStpVatAccCash	  	  	= $result[10];
				$vSaStpVatNonStockAccCash 	= $result[11];
						
					
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'SR' ".
						 " 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];
				$vTranStpDiscAcc         = $result[10];
						
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
							
					if ($ItemVat > 0 && $vRSaVatChkbx == 1) {
						if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
						}
					}	
				} 
				else {
					$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
					$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
					$vSaDtDiscAcc      = $vSaStpDiscAcc;
							
					if ($ItemVat > 0 && $vRSaVatChkbx == 1) {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
					} else {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
						else	
							$vSaDtItemAcc = $vSaStpCreditAcc;
					}

					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
				}
				
				
				$sub_queryVat = " SELECT GetVATAccount('".$vRSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				if ($deliverydt_clientdiscount=='') $deliverydt_clientdiscount = 0;
				if ($deliverydt_itemdiscount=='') $deliverydt_itemdiscount = 0;

				
				fbegin();
				$vRSaDtId = get_nextsequence('deliverydt_id','',$connection);	
				fcommit();
				
					 
				fbegin();
				if ($Module_Delivery == 0) {
					$sub_query3 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, Item_QtyPacked, ". 
								  " DeliveryDt_Quantity, DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, ".
								  " DeliveryDt_PriceTTC, Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, ".
								  " Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, ".
								  " Deliverydt_OldData, Deliverydt_promotion, Journal_Type, Related_Ref, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_clientdiscount,deliverydt_itemdiscount, DeliveryDt_REason ) ".
								  " VALUES ( $vRSaDtId, $vRSaId, '".$sub_row[0]."', '".$sub_row[1]."', '".$sub_row[2]."', '".$sub_row[3]."', $ProjectCode, $CostCentCode, '".$sub_row[6]."', '".$sub_row[7]."', if('".$sub_row[8]."'='', Null, '".$sub_row[8]."'), '".$sub_row[9]."', ". 
								  " $vRSaDtQty, '".$sub_row[11]."', '".$sub_row[12]."', '".$sub_row[13]."', '".$sub_row[14]."', $vRSaDtDiscAmt, $vRSaDtDiscAmtBase1, $vRSaDtDiscAmtBase2, '".$sub_row[15]."', '".$sub_row[16]."', '".$sub_row[17]."', ".
								  " '".$sub_row[18]."', $vRSaDtCostBase1, $vRSaDtCostBase2, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$sub_row[23]."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', ".
								  " '".$sub_row[29]."', '".$sub_row[30]."', '".$sub_row[31]."', '".$sub_row[32]."', '".$sub_row[33]."', '".$sub_row[34]."', 0, 0, '".$sub_row[35]."', 'DR', '".$sub_row[37]."', $DeliveryDt_ExpireDate, '".$sub_row[40]."', '".$sub_row[41]."', ".
								  " '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',$deliverydt_clientdiscount,$deliverydt_itemdiscount, '".$DeliveryDt_REason."' ) ";
				} else {
					$sub_query3 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, Item_QtyPacked, ". 
								  " DeliveryDt_Quantity, Item_Vat, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
								  " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Journal_Type, Related_Ref, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, ".
								  " DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code, DeliveryDt_REason ) ".
								  " VALUES ( $vRSaDtId, $vRSaId, '".$sub_row[0]."', '".$sub_row[1]."', '".$sub_row[2]."', '".$sub_row[3]."', $ProjectCode, $CostCentCode, '".$sub_row[6]."', '".$sub_row[7]."', if('".$sub_row[8]."'='', Null, '".$sub_row[8]."'), '".$sub_row[9]."', ". 
								  " $vRSaDtQty, '".$sub_row[15]."', $vRSaDtCostBase1, $vRSaDtCostBase2, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$sub_row[23]."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', ".
								  " '".$sub_row[29]."', 0, 0, '".$sub_row[35]."', 'DR', '".$sub_row[37]."', $DeliveryDt_ExpireDate, '".$sub_row[40]."', '".$sub_row[41]."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".$DeliveryDt_REason."' ) ";
				}
				
				//echo $sub_query3; exit;	
				$sub_result3=mysql_query($sub_query3,$connection);
			
			
				if ($sub_result3){
					$sub_query4 = " SELECT Serial_ID, purchasesserialno.Item_Code, purchasesserialno.Warehouse_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ifNull(SerialNo_Quantity,0), ifNull(SerialNo_QuantitySold,0)  ".
								  " FROM purchasesserialno ".
								  " WHERE purchasesserialno.PurchaseDt_ID  = '".$sub_row[0]."' ".
								  " AND purchasesserialno.Journal_Type = 'DI' ".
								  " AND Not Exists ( Select 1 from purchasesserialno as purchasesserialno1 ".
								  "                  Where purchasesserialno1.RelatedSerial_Id = purchasesserialno.Serial_ID ".
								  "                  And purchasesserialno1.Journal_Type = 'DR'  ".
								  "                  union  ".
								  "                  Select 1 from temp_purchasesserialno ".
								  "                  Where temp_purchasesserialno.RelatedSerial_Id = purchasesserialno.Serial_ID ".
								  "                  And temp_purchasesserialno.Journal_Type = 'DR' ) ";
								  
					//echo $sub_query4,"<br>"; exit;
					$sub_result4 = mysql_query($sub_query4,$connection) or die(mysql_error());
					while($sub_row4=mysql_fetch_array($sub_result4)){
						fbegin();
						$vSerId = get_nextsequence('Serial_Id','',$connection);	
						fcommit();
							
						$sub_query5 = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
									  " VALUES ( ".$vSerId.", 'DR', $vRSaDtId, $vRSaDtId, '".$sub_row4[1]."', '".$sub_row4[3]."', 0, '".$sub_row4[0]."', '".$sub_row4[6]."', '".$sub_row4[7]."', '".$sub_row4[2]."', '".$_SESSION['useraccount']."' ) ";
						//echo $sub_query5; exit;										 
						$sub_result5 = mysql_query($sub_query5,$connection);	
					}
					
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} // End if($vRSaDtQty > 0)
			
		}  //End Loop of DeliveryDt Query
		
		
		if ($Module_Delivery == 0 && $ErrorExists == 0) {	
		
			$CalculateResult = Calculate_MasterAmounts($vRSaId, $vRSaDate, $vRSaVatChkbx, $vRSaDiscountPer, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		
		} 
	
	} else 
		$message  = mysql_error();

}

else if($mode == "CashPayment" && $SRSaId != ''){  

	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	$CashAccount = $txtLedgerNo;
	
	$vSaCashInB1   = $txtSaCashInB1;
	$vSaCashOutB1  = $txtSaCashOutB1;
	$vSaCashInB2   = $txtSaCashInB2;
	$vSaCashOutB2  = $txtSaCashOutB2;
	$vSaTipsB1     = $txtSaTipsB1;
	
	if (empty($vSaCashInB1))  $vSaCashInB1 = 0;
	if (empty($vSaCashOutB1)) $vSaCashOutB1 = 0;
	if (empty($vSaCashInB2))  $vSaCashInB2 = 0;
	if (empty($vSaCashOutB2)) $vSaCashOutB2 = 0;
	if (empty($vSaTipsB1))    $vSaTipsB1 = 0;
	
	
	if ($CashAccount != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$CashAccount."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0){
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Cash Account.';
		}	
	}

	
	
	if ($ErrorExists == 0) {
		$query = " Select (ifNull(Delivery_Total,0) + IfNull(Delivery_VAT,0) + IfNull(Delivery_TransportAmount,0) + IfNull(Delivery_BonusAmount,0) - IfNull(Delivery_DiscountAmount,0) + ".
				 "         (ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0))) As Delivery_NetTotal,  ".
				 " ( ifNull(Delivery_TotalBase1,0) + IfNull(Delivery_VatBase1,0) + IfNull(Delivery_TransportAmountBase1,0) + IfNull(Delivery_BonusBase1,0) - IfNull(Delivery_DiscountBase1,0) + ".
				 "  (ifNull(Delivery_Tax1Base1,0) + ifNull(Delivery_Tax2Base1,0) + ifNull(Delivery_Tax3Base1,0) + ifNull(Delivery_Tax4Base1,0) + ifNull(Delivery_Tax5Base1,0))) As Delivery_NetTotalB1,  ".
				 " ( ifNull(Delivery_TotalBase2,0) + IfNull(Delivery_VatBase2,0) + IfNull(Delivery_TransportAmountBase2,0) + IfNull(Delivery_BonusBase2,0) - IfNull(Delivery_DiscountBase2,0) + ".
				 "  (ifNull(Delivery_Tax1Base2,0) + ifNull(Delivery_Tax2Base2,0) + ifNull(Delivery_Tax3Base2,0) + ifNull(Delivery_Tax4Base2,0) + ifNull(Delivery_Tax5Base2,0))) As Delivery_NetTotalB2  ".
				 " From Temp_Deliveries As Deliveries ".
			     " Where Deliveries.Delivery_Id = '".$SRSaId."'";
			   
		//echo $query;
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);

		$vSaNetTotal    = $rows[0];
		$vSaNetTotalB1  = $rows[1];
		$vSaNetTotalB2  = $rows[2];
		
		if (empty($vSaNetTotal))   $vSaNetTotal = 0;
		if (empty($vSaNetTotalB1)) $vSaNetTotalB1 = 0;
		if (empty($vSaNetTotalB2)) $vSaNetTotalB2 = 0;
			 
		$query = " UPDATE temp_deliveries SET Delivery_Mode = 1, ".
				 " Delivery_CashInBase1 = $vSaCashInB1, Delivery_CashOutBase1 = $vSaCashOutB1, Delivery_CashInBase2 = $vSaCashInB2,  ".
				 " Delivery_CashOutBase2 = $vSaCashOutB2, Delivery_TipsBase1 = $vSaTipsB1, Delivery_TipsAccount = '".$TipsAccount."', ".
				 " Delivery_CashCur = '".$CashCur."', Delivery_CashAccount = '".$CashAccount."', ".
				 " Delivery_Cash = $vSaNetTotal, Delivery_CashBase1 = $vSaNetTotalB1, Delivery_CashBase2 = $vSaNetTotalB2 ".
				 " ,Delivery_ManualNo = '".ereg_replace("'", "\'", trim($PSaManualNo))."' ".
				 " WHERE Delivery_ID = ".$SRSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$message  = mysql_error($connection); 
		} 
	}
}

else if($mode == "CreditPayment" && $SRSaId != ''){  

	$SaveAllowed = 1;
	$ErrorExists = 0;
	

	
	
	if ($ErrorExists == 0) {
		 
		$query = " UPDATE temp_deliveries SET Delivery_Mode = 0, ".
				 " Delivery_CashInBase1 = 0, Delivery_CashOutBase1 = 0, Delivery_CashInBase2 = 0, Delivery_CashOutBase2 = 0,  ".
				 " Delivery_TipsBase1 = 0, Delivery_Cash = 0, Delivery_CashBase1 = 0, Delivery_CashBase2 = 0 ".
				 " WHERE Delivery_ID = ".$SRSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$message  = mysql_error($connection); 
		} 
	}
}

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

	if (empty($txtRSaDiscountAmt)) 	$txtRSaDiscountAmt = 0;
	if (empty($txtRSaDiscount))		$txtRSaDiscount = 0;
	if (empty($txtRSaTransportAmt))	$txtRSaTransportAmt = 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);
	$vRate = $Rate_Result[0];
	
	$Rate_Query1  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$Rate_Result1 = selectData($connection, $Rate_Query1);
	$vRateB1 = $Rate_Result1[0];
	
	$Rate_Query2  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$Rate_Result2 = selectData($connection, $Rate_Query2);
	$vRateB2 = $Rate_Result2[0];
	
	
	$sub_query = " Select Currency_Code From temp_deliveries WHERE Delivery_ID = $SRSaId ";
	$sub_result = selectData($connection, $sub_query);
	$txtRSaTransportAmt = ConvertCurrency($sub_result[0], $txtCurr, insertMySQLDate($txtDate), $txtRSaTransportAmt, $connection);	
	
	$query = " UPDATE temp_deliveries SET Currency_Code = '".$txtCurr."' WHERE Delivery_ID = $SRSaId ";
	$result=mysql_query($query,$connection);
	
	//echo $query; exit;
	
		
	//Update Detail Amount Columns
	$sub_query = " Select DeliveryDt_id, Currency_Code, ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ".
				 " ifNull(DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ifNull(Deliverydt_DiscountAmount,0), ".
				 " ifNull(Deliverydt_DiscountBase1,0), ifNull(Deliverydt_DiscountBase2,0), ifNull(DeliveryDt_TransportAmount,0) ".
				 " From temp_deliverydt ".
				 " Where Delivery_ID = ".$SRSaId;	
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_row=mysql_fetch_array($sub_result)){
					
		$vSaDtPrice         = $sub_row[2];
		$vSaDtPriceBase1    = $sub_row[3];
		$vSaDtPriceBase2    = $sub_row[4];
		$vSaDtPriceTTC      = $sub_row[5];
		$vSaDtPriceTTCBase1 = $sub_row[6];
		$vSaDtPriceTTCBase2 = $sub_row[7];
		$vSaDtDiscAmt       = $sub_row[8];
		$vSaDtDiscAmtBase1  = $sub_row[9];
		$vSaDtDiscAmtBase2  = $sub_row[10];	
		$vSaDtTrsAmt    	= $sub_row[11];
			
				
		$vSaDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtPrice, $connection);
		$vSaDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtPriceTTC, $connection);
		$vSaDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtDiscAmt, $connection);
		$vSaDtTrsAmt   = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtTrsAmt, $connection);
						
		$vSaDtPriceBase1    = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vSaDtPrice, $connection);
		$vSaDtPriceBase2    = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vSaDtPrice, $connection);
		$vSaDtPriceTTCBase1 = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vSaDtPriceTTC, $connection);
		$vSaDtPriceTTCBase2 = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vSaDtPriceTTC, $connection);
		$vSaDtDiscAmtBase1  = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vSaDtDiscAmt, $connection);
		$vSaDtDiscAmtBase2  = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vSaDtDiscAmt, $connection);
		$vSaDtTrsAmtB1      = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vSaDtTrsAmt, $connection);
		$vSaDtTrsAmtB2      = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vSaDtTrsAmt, $connection);
		
		$sub_query1 = " UPDATE temp_deliverydt SET  ".
					  " Currency_Code = '".$txtCurr."', ".
					  " DeliveryDt_Price = $vSaDtPrice, DeliveryDt_PriceBase1 = $vSaDtPriceBase1, DeliveryDt_PriceBase2 = $vSaDtPriceBase2, ".
					  " DeliveryDt_PriceTTC = $vSaDtPriceTTC, Deliverydt_priceTTCBase1 = $vSaDtPriceTTCBase1, Deliverydt_priceTTCBase2 = $vSaDtPriceTTCBase2, ".
					  " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2, ".
					  " DeliveryDt_TransportAmount = $vSaDtTrsAmt, DeliveryDt_TransportAmountBase1 = $vSaDtTrsAmtB1, DeliveryDt_TransportAmountBase2 = $vSaDtTrsAmtB2, DeliveryDt_REason='$DeliveryDt_REason' ".
 					  " Where DeliveryDt_ID = ".$sub_row[0];

		//echo $sub_query1; exit;	
		if (!updateData($connection, $sub_query1, true))		 
			$message  = mysql_error(); 
					
	}  //End Loop of SalesDt Query
		

	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($SRSaId, $txtDate, $SRSaVatChkbx, $txtRSaDiscount, $txtRSaDiscountAmt, $txtRSaTransportAmt, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
	$message  = $message . $CalculateResult;

	
		
}


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

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

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' 
			and Curdt_date <= '".insertMySQLDate($txtDate)."')";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' 
			and Curdt_date <= '".insertMySQLDate($txtDate)."')";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' 
			and Curdt_date <= '".insertMySQLDate($txtDate)."')";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	//exit;
	
	if (empty($txtRSaDiscountAmt)) 	$txtRSaDiscountAmt = 0;
	if (empty($txtRSaDiscount))		$txtRSaDiscount = 0;
	if (empty($txtRSaTransportAmt))	$txtRSaTransportAmt = 0;	
			
	if (empty($txtCostCentCode))	$CostCentCode = 'Null';
	else		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))		$ProjectCode = 'Null';
	else		$ProjectCode = "'".$txtProjectCode."'";	
		
	if (empty($txtSalesmanCode))	$SalesmanCode = 'Null';
	else		$SalesmanCode = "'".ereg_replace("'", "\'", trim($txtSalesmanCode))."'";		
		
	if (empty($txtDirectReturn))    $txtDirectReturn = 0;
		
	$vSaRef = '';
	$vSaTotal = 0;
	$vSaDisAmt = 0;
	$vSaTrsAmt = 0;
	
	$vSaDtTrsAmt    = 0;
	$vSaDtTrsAmtB1  = 0;
	$vSaDtTrsAmtB2  = 0;
	
	
	$vSaDtQty     = 0;
	$vSaDtPrice   = 0;
	$vSaDtPriceB1 = 0;
	$vSaDtPriceB2 = 0;
	$vSaDtDiscPer = 0;
	
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;
	$vSaDtDiscAmt       = 0;
	$vSaDtDiscAmtBase1  = 0;
	$vSaDtDiscAmtBase2  = 0;
	
	
	$SaveAllowed = 1;
	$ErrorExists = 0;
	

	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_deliverydt ".
				 " Where Delivery_ID = '".$SRSaId."' ".
				 " 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(DeliveryDt_Quantity,0)) As DeliveryDtQuantity ".
								  " From temp_deliverydt ".
								  " Where Delivery_ID = '".$SRSaId."' ".
								  " 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) $SaveAllowed = 0;
					
					 
				}
				
			}
		}
	}

	
	//Check For Client, Salesman, 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 ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Client Code.';
		}
	}
	if ($txtSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$txtSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Salesman Code.';
		}
	}	
	
	
	$ErrorExists = checkcashdiff('ReturnDelivery',$SRSaId,$txtCurr,$base1,$base2,$connection);					 
	if($ErrorExists==1) $message  = 'Save not allowed. Net Total And Cash Differs.'; 
	 
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_code, ifNull(DeliveryDt_Quantity,0) as DeliveryDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_DeliveryDt As DeliveryDt Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on DeliveryDt.DeliveryDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'DR' ".
					 " 	And Temp_Purchasesserialno.DeliveryDt_ID Is Not Null ".
					 " 	Where DeliveryDt.Delivery_ID = ".$SRSaId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By DeliveryDt.DeliveryDt_ID ".
					 " 	Having ifNull(DeliveryDt_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 DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_code, ifNull(DeliveryDt_Quantity,0) as DeliveryDt_Quantity ".
					 " 	From Temp_DeliveryDt As DeliveryDt ".
					 " 	Where DeliveryDt.Delivery_ID = ".$SRSaId.
					 " 	And ifNull(DeliveryDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
		
	}
	//echo $sub_query;exit;
	
	if ($SaveAllowed == 1 && $ErrorExists == 0  && $ExceedLockPeriod == 0) {
	
		if ($Module_Delivery == 0) {	
			$sub_query = " Select DeliveryDt_id, Currency_Code, ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ".
						 " ifNull(DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ifNull(Deliverydt_DiscountAmount,0), ".
						 " ifNull(Deliverydt_DiscountBase1,0), ifNull(Deliverydt_DiscountBase2,0),Item_Code ".
						 " From temp_deliverydt ".
						 " Where Delivery_ID = '".$SRSaId."'";	
			$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_row=mysql_fetch_array($sub_result)){
					
				$vSaDtPrice         = $sub_row[2];
				$vSaDtPriceBase1    = $sub_row[3];
				$vSaDtPriceBase2    = $sub_row[4];
				$vSaDtPriceTTC      = $sub_row[5];
				$vSaDtPriceTTCBase1 = $sub_row[6];
				$vSaDtPriceTTCBase2 = $sub_row[7];
				$vSaDtDiscAmt       = $sub_row[8];
				$vSaDtDiscAmtBase1  = $sub_row[9];
				$vSaDtDiscAmtBase2  = $sub_row[10];
				$Item_Code  = $sub_row[11];
			 

				 
				if ($sub_row[1] != $txtCurr) {
					$vSaDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtPrice, $connection);
					$vSaDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtPriceTTC, $connection);
					$vSaDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtDiscAmt, $connection);
						
					$vSaDtPriceBase1    = ($vSaDtPrice*$rate_dt)/$rate_dt1;
					$vSaDtPriceBase2    = ($vSaDtPrice*$rate_dt)/$rate_dt2;
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
					$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
					
					$sub_query1 = " UPDATE temp_deliverydt SET  ".
								  " DeliveryDt_Price = $vSaDtPrice, DeliveryDt_PriceBase1 = $vSaDtPriceBase1, DeliveryDt_PriceBase2 = $vSaDtPriceBase2, ".
								  " DeliveryDt_PriceTTC = $vSaDtPriceTTC, Deliverydt_priceTTCBase1 = $vSaDtPriceTTCBase1, Deliverydt_priceTTCBase2 = $vSaDtPriceTTCBase2, ".
								  " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2 ".
								  " Where DeliveryDt_ID = ".$sub_row[0];
					
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 
					
				}
					$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
							" FROM Items WHERE item_Code = '".$Item_Code."'";
							
					$result = selectData($connection, $query);
					$item_vat 		= $result[0];
					$Item_MaxQty 	= $result[1];
					$ItemGroupCode 	= $result[2];
					$ItemProd   	= $result[3];
					$ItemTTCInc 	= $result[4];
					$ItemUnit   	= $result[5];
					$ItemPromo  	= $result[6];
					$ItemNonStock  	= $result[7];
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
				
				// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditVATReturn, CreditAccountReturn, ".
							 " PromotionAccount, TipsAccount, CreditReturnNonStock, CreditVATReturnNonStock, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
							 " FROM salessetup ";
					$result = selectData($connection, $query);
							
					$vSaStpDirectStkDbt = $result[0];
					$vSaStpDirectStkCrd = $result[1];
					$vSaStpDirectStkCur = $result[2];	
					$vSaStpDiscAcc      = $result[3];	
					$vSaStpVatAcc       = $result[4];	
					$vSaStpCreditVatAcc = $result[5];	
					$vSaStpCreditAcc    = $result[6];	
					$vSaStpPromoAcc     = $result[7];
					$vSaStpTipsAcc      = $result[8];
					$vSaStpCreditNonStockAcc    = $result[9];
					$vSaStpCreditVatNonStockAcc = $result[10];
					$vSaStpVatNonStockAcc 	  	= $result[11];
					$vSaStpCreditExportAcc	 	= $result[14];			
					
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".ereg_replace("'", "\'", trim($txtClientCode))."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $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_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'SR' ".
							 " 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];
					$vTranStpDiscAcc         = $result[10];
					$vTranStpPromoAcc        = $result[11]; 
					$vTranStpTipsAcc         = $result[12]; 
					$vTransStpExportAcc 	 = $result[13];
					
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
						$vSaDtPromoAcc     = $vTranStpPromoAcc;
						$vSaDtTipsAcc      = $vTranStpTipsAcc;
									
						if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
						}	
						if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						//$vSaDtVatAcc       = $vSaStpVatAcc;
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
						$vSaDtPromoAcc     = $vSaStpPromoAcc;
						$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
						if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}

						if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc;  

					}	
				$query = " UPDATE temp_deliverydt SET ".
						 " Deliverydt_ItemAccount = '".$vSaDtItemAcc."', Deliverydt_DirectStkDbt = '".$vSaDtDirectStkDbt."', Deliverydt_DirectStkCrd = '".$vSaDtDirectStkCrd."', ".
						 " Deliverydt_DirectStkCur = '".$vSaDtDirectStkCur."', Deliverydt_discountacc =  '".$vSaDtDiscAcc."', DeliveryDt_PromoAcc = '".$vSaDtPromoAcc."', ".
						 " DeliveryDt_TipsAccount = '".$vSaDtTipsAcc."' ".
						 " WHERE DeliveryDt_id = '".$sub_row[0]."' ";
						//echo $query."<br>";
				$result=mysql_query($query,$connection);
			
				
					
			}  //End Loop of DeliveryDt Query
		} //End if ($Module_Delivery == 0) 
		
		
		
		
		
		$sub_query2 = " UPDATE temp_deliverydt SET ".
					  " Currency_Code = '".$txtCurr."', Delivery_Date = '".insertMySQLDate($txtDate)."', ".
					  " Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."' ";
					  
		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 Delivery_id = $SRSaId ";
				   
		//echo $querydt."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
					  
		
		
		$sub_query7 = " Select DeliveryDt_ID, DeliveryDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0) ".
						  " From Temp_DeliveryDt as DeliveryDt ".
						  " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						  " Where Delivery_ID = '".$SRSaId."'";
						  
			$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];
			
				// Get DirectStock Accounts
				$query = " SELECT VatAccount, VATAccountNonStock FROM salessetup ";
				$result = selectData($connection, $query);
						
				$vSaStpVatAcc 		  	  	= $result[0];
				$vSaStpVatNonStockAcc 	  	= $result[1];
						
					
				$query = " SELECT Trans_VATAccount FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$result = selectData($connection, $query);
				$vTranStpVatAcc = $result[0];
				
				if ($Module_RawMaterial == 1) {
					$vSaDtVatAcc = $vTranStpVatAcc;
				} 
				else {
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
									
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaDtVatAcc."') from dual ";
				
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				
				$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " WHERE DeliveryDt_id = '".$sub_rows7[0]."' ";
						
				$result=mysql_query($query,$connection);
			
			}
			
			
		if ($Module_Delivery == 0) {	
		
			//Distribute The Total Discount On Detail Table
			$sub_query3 = " Select Sum((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_DeliveryDt ".
						  " Where Delivery_ID = '".$SRSaId."'";
			$sub_result3 = selectData($connection, $sub_query3);
			$vSaTotal   = $sub_result3[0];	
			$vSaDisAmt	= $txtRSaDiscountAmt;
			$vSaTrsAmt  = $txtRSaTransportAmt;
			
			if ($SalesTTC == 1) {
				$vSaDisAmt	= ($txtRSaDiscountAmt  / (1 + $Setup_VatPercentage/100));
				$vSaTrsAmt  = ($txtRSaTransportAmt / (1 + $Setup_VatPercentage/100));
			} else {
				$vSaDisAmt	= $txtRSaDiscountAmt;
				$vSaTrsAmt  = $txtRSaTransportAmt;
			}
			
			
			$sub_query4 = " Select DeliveryDt_ID,  ".
						  " ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ".
						  " ifNull(DeliveryDt_Quantity,0), ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ifNull(DeliveryDt_DiscountPer,0) ".
						  " From Temp_DeliveryDt As DeliveryDt  ".
						  " Where DeliveryDt.Delivery_ID = '".$SRSaId."'";
					   
			//echo $query; 
			$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
			while($sub_rows4=mysql_fetch_array($sub_result4)){
			
				$vSaDtId      = $sub_rows4[0];
				$vSaDtTotal   = $sub_rows4[1];
				$vSaDtQty     = $sub_rows4[2];
				$vSaDtPrice   = $sub_rows4[3];
				$vSaDtPriceB1 = $sub_rows4[4];
				$vSaDtPriceB2 = $sub_rows4[5];
				$vSaDtDiscPer = $sub_rows4[6];
				
				
				
				$vSaDtDiscAmt	   = 0;
				$vSaDtDiscAmt 	   = ($vSaDtTotal/$vSaTotal)*$vSaDisAmt;
				$vSaDtDiscAmtBase1 = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2 = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
				
				$vSaDtTrsAmt = 0;
				$vSaDtTrsAmt    = ($vSaDtTotal/$vSaTotal)*$vSaTrsAmt;
				$vSaDtTrsAmtB1  = ($vSaDtTrsAmt*$rate_dt)/$rate_dt1;
				$vSaDtTrsAmtB2  = ($vSaDtTrsAmt*$rate_dt)/$rate_dt2;
				
				$vSaDtSalePrice    = 0;
				$vSaDtSalePriceB1  = 0;
				$vSaDtSalePriceB2  = 0;
				
				if ($vSaDtQty > 0) {
					$vSaDtSalePrice    = $vSaDtPrice   - ($vSaDtPrice*$vSaDtDiscPer/100)   - ($vSaDtDiscAmt/$vSaDtQty)      - ($vSaDtTrsAmt/$vSaDtQty);
					$vSaDtSalePriceB1  = $vSaDtPriceB1 - ($vSaDtPriceB1*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase1/$vSaDtQty) - ($vSaDtTrsAmtB1/$vSaDtQty);
					$vSaDtSalePriceB2  = $vSaDtPriceB2 - ($vSaDtPriceB2*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase2/$vSaDtQty) - ($vSaDtTrsAmtB2/$vSaDtQty);
				}
				
				$queryupd =  " UPDATE temp_deliverydt SET ".
							 " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2,  ".
							 " DeliveryDt_TransportAmount = $vSaDtTrsAmt, DeliveryDt_TransportAmountBase1 = $vSaDtTrsAmtB1, DeliveryDt_TransportAmountBase2 = $vSaDtTrsAmtB2, ".
							 " SaleDt_Price = $vSaDtSalePrice, SaleDt_PriceBase1 = $vSaDtSalePriceB1, SaleDt_PriceBase2 = $vSaDtSalePriceB2 ".
							 " Where DeliveryDt_ID = '".$vSaDtId."'";
							 //" And Logged_Code = '".$PLoggedCode."' ";
				//echo $queryupd; exit;
				if (!updateData($connection, $queryupd, true))
					$error  = mysql_error(); 
				

			}
			
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SRSaId, $txtDate, $SRSaVatChkbx, $txtRSaDiscount, $txtRSaDiscountAmt, $txtRSaTransportAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'P', $connection);
			$message  = $message . $CalculateResult;
		
					
		} //End if ($Module_Delivery == 0) 		 
				 
			
		//Update Serials ExpireDate and BatchNo From Detail Table
			if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
				$sub_query5 = " Select DeliveryDt_Id, DeliveryDt_ExpireDate, DeliveryDt_BatchNo ".
							  " From Temp_DeliveryDt As DeliveryDt  ".
							  " Where DeliveryDt.Delivery_ID = ".$SRSaId;
							  
				//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]))		$vSaDtExpireDate = 'Null';
					else  $vSaDtExpireDate = "'".$sub_rows5[1]."'";		
			
					$query = " UPDATE temp_purchasesserialno SET ".
							 " Item_ExpireDate = $vSaDtExpireDate, Item_BatchNo = '".$sub_rows5[2]."' ".
							 " WHERE PurchaseDt_Id  = '".$sub_rows5[0]."' ".
							 " AND Journal_Type = 'DR' ";
					//echo $query."<br>";exit;		   
					if (!updateData($connection, $query, true))		 
						$message  = mysql_error(); 
				
				}
			}	
		
		$query = " UPDATE temp_deliveries SET ".
				 " Delivery_Date = '".insertMySQLDate($txtDate)."' , ".
				 " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."' , ".
				 " Delivery_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
				 " Salesman_Code = $SalesmanCode, Delivery_ShippedTo = '".ereg_replace("'", "\'", trim($txtDAddress))."', ".
				 " Delivery_Marks = '".ereg_replace("'", "\'", trim($txtVehicleNumber))."', Delivery_ShippedVia = '".ereg_replace("'", "\'", trim($txtDriverName))."', ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Delivery_DirectReturn = $txtDirectReturn ,Delivery_ManualNo='$txtManualNo' ".
				" WHERE Delivery_id = $SRSaId ";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
		
		if ($result){
						
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM Deliveries WHERE Delivery_id = $SRSaId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_Deliveries where Delivery_ID = '".$SRSaId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
				$query_checkDelivery  = "select count(*) as DeliveryExist from deliveries where delivery_id = '$SRSaId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($DeliveryExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempDelivery('DR', ".$SRSaId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$result = $result[0];
				
				//echo 'error='.$result; exit;
				if ($result != 0){
					fcommit();
							
					$query   = " SELECT Delivery_Reference, Costcent_code, Project_Code FROM Deliveries WHERE Delivery_id = $SRSaId ";
					$result  = selectData($connection, $query);
					$vSaRef  = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
					
					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vSaRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vSaRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}			
					
					if ($vSaRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							
						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';
							
						fbegin();
						$vSaRef = get_nextsequence('Dreturn_Reference',$vProjCostCent,$connection);	
						fcommit();
								
						$query = " UPDATE deliveries SET ".
								 " Delivery_Reference = $vSaRef ".
								 " WHERE Delivery_id = $SRSaId ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
							
					}	
					
					$PostAcc=0;
					if ($Module_ConfirmDR==1)  {
					   
					 if ($Delivery_Confirmed==1)  $PostAcc=1;
					 else $PostAcc=0;
					   	
					}

					else $PostAcc=1;
					
					if ($Module_PostToJournal == 1 && $PostAcc == 1)	 
						$message = Create_DeliveryJv($SRSaId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
						
					//echo $message; exit; 
					
					//Create Return Sales From Return Delivery Automatically
					if ($Module_Delivery == 1 && $Module_AutoReturnSales == 1)
						$message = Create_AutoReturnSales($SRSaId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
					
				    if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SRSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'return_delivery', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
				} else{
					//$message  = mysql_error(); 
					$ErrorExists = 1;
					$message  = 'Error In CopyData_TempDelivery Function'; 
					frollback();
				}
			
			}
				
		} else{
			$message  = mysql_error(); 
			frollback();
		}
		
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllowed == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';	
		
		frollback();
	}
}


$message		   = ereg_replace(' ','%20',$message);
$WarningMsg		   = ereg_replace(' ','%20',$WarningMsg);
$PRSaRemark 	   = ereg_replace(' ','%20',$PRSaRemark);
$PRSaIAddress	   = ereg_replace(' ','%20',$PRSaIAddress);
$PRSaDAddress 	   = ereg_replace(' ','%20',$PRSaDAddress);
$PRSaDriverName    = ereg_replace(' ','%20',$PRSaDriverName);
$PRSaVehicleNumber = ereg_replace(' ','%20',$PRSaVehicleNumber);

$lstWarehouse      = ereg_replace('#','%23',$lstWarehouse);
$PRSaRemark        = ereg_replace('#','%23',$PRSaRemark);
$PRSaIAddress      = ereg_replace('#','%23',$PRSaIAddress);
$PRSaDAddress      = ereg_replace('#','%23',$PRSaDAddress);
$PRSaVehicleNumber = ereg_replace('#','%23',$PRSaVehicleNumber);
$PRSaDriverName    = ereg_replace('#','%23',$PRSaDriverName);

$lstWarehouse      = ereg_replace('&','%26',$lstWarehouse);
$PRSaRemark        = ereg_replace('&','%26',$PRSaRemark);
$PRSaIAddress      = ereg_replace('&','%26',$PRSaIAddress);
$PRSaDAddress      = ereg_replace('&','%26',$PRSaDAddress);
$PRSaVehicleNumber = ereg_replace('&','%26',$PRSaVehicleNumber);
$PRSaDriverName    = ereg_replace('&','%26',$PRSaDriverName);


//echo $mode.$message; exit;

if($mode == "post") {
	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_ReturnDelivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrRSaId=".$SRSaId."&PrRSaRef=".$vSaRef);
	else
		header ("Location: ./Form_ReturnDelivery.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtRSaId=".$SRSaId);
}
else if ($mode == "" && ($mainmode == "delete" || $mainmode=='confirmreturndelivery') )	
	header ("Location: ./Form_ReturnDeliverySearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_ReturnDeliverySearchPending.php?message=".$message);
else if ($mode == "cancel" )		
	header ("Location: ./Form_ReturnDelivery.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_ReturnDelivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtRSaId=".$SRSaId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_ReturnDeliveryDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PRSaId=".$SRSaId."&PRSaDate=".$PRSaDate."&PRSaDtId=".$SRSaDtId);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_ReturnDeliverySearch.php?PMode=1&SelectedID=".$SRSaId."&message=".$message);	
else if ($mode == "" && $mainmode == "loadinvoice" )		
	header ("Location: ./Form_ReturnDelivery_LoadInvoice.php?PMode=1&PRSaId=".$SRSaId."&message=".$message);			
else if ($mode == "CashPayment") { 
	if ($message != "")
		header ("Location: ./Form_ReturnDelivery_PayCash.php?PMode=0&PSaId=".$SRSaId."&message=".$message);
	else
		header ("Location: ./Form_ReturnDelivery_PayCash.php?PMode=1&PSaId=".$SRSaId."&message=".$message);
}	
else if ($mode == "CreditPayment") { 
	header ("Location: ./Form_ReturnDelivery.php?actionmode=submitrecord&mainaction=".$mainmode."&txtRSaId=".$SRSaId."&message=".$message);
}
else if ($mode == "changecurrency")	
	header ("Location: ./Form_ReturnDelivery.php?actionmode=submitrecord&mainaction=".$mainmode."&txtRSaId=".$SRSaId."&message=".$message);
else if($mode == "submitrecord") {
    header ("Location: ./Form_ReturnDeliveryDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PRSaId=".$PRSaId.	
			"&PRSaDate=".$PRSaDate."&PRSaMaturityDate=".$PRSaMaturityDate."&PRSaClientCode=".$PRSaClientCode."&PRSaSalesmanCode=".$PRSaSalesmanCode.
			"&PRSaCurr=".$PRSaCurr."&PRSaProjectCode=".$PRSaProjectCode."&PRSaCostCentCode=".$PRSaCostCentCode."&PRSaDiscount=".$PRSaDiscount.
			"&PRSaDiscountAmt=".$PRSaDiscountAmt."&PRSaVatChkbx=".$PRSaVatChkbx."&PRSaDirectReturn=".$PRSaDirectReturn."&lstWarehouse=".$lstWarehouse.
		    "&PRSaDriverName=".$PRSaDriverName."&PRSaVehicleNumber=".$PRSaVehicleNumber."&PRSaRemark=".$PRSaRemark."&PRSaIAddress=".$PRSaIAddress.
     		"&PRSaDAddress=".$PRSaDAddress."&message=".$message."&WarningMsg=".$WarningMsg	);
}


$return_arr = array();

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



function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	$result = selectData($connection, $query);
	//echo $query;
	Return	$result[0];

}

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

	$vSaDtTotal = 0;
	$vItemVat    = 0;
	
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountPer    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
		
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;

	$vSaDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(Delivery_VatChkbx, 0) From Temp_Deliveries Where Delivery_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}
	
	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_DeliveryDt SET  ".
				 " DeliveryDt_Price = DeliveryDt_PriceTTC, ".
				 " DeliveryDt_PriceBase1 = DeliveryDt_PriceTTCBase1, ".
				 " DeliveryDt_PriceBase2 = DeliveryDt_PriceTTCBase2 ".
				 " Where Delivery_ID = ".$PId;

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

		$query = " UPDATE Temp_DeliveryDt SET  ".
				 " DeliveryDt_Price      = (DeliveryDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase1 = (DeliveryDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase2 = (DeliveryDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Delivery_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " DeliveryDt_Quantity, (ifNull(DeliveryDt_DiscountAmount,0) - ifNull(DeliveryDt_TransportAmount,0) - ifNull(DeliveryDt_BonusAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_DeliveryDt ".
				 " Where Delivery_ID = ".$PId;
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
		
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
		}
		
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
	
		
				
	$vSaTransportAmt   = $PTransportAmt;	
	$vSaTransportAmtB1 = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2 = ($vSaTransportAmt*$PRate)/$PRate2;	
				
					
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
					

	$vSaTax1B1  = ($vSaTax1*$PRate)/$PRate1;
	$vSaTax1B2  = ($vSaTax1*$PRate)/$PRate2;		
	$vSaTax2B1  = ($vSaTax2*$PRate)/$PRate1;
	$vSaTax2B2  = ($vSaTax2*$PRate)/$PRate2;		
	$vSaTax3B1  = ($vSaTax3*$PRate)/$PRate1;
	$vSaTax3B2  = ($vSaTax3*$PRate)/$PRate2;		
	$vSaTax4B1  = ($vSaTax4*$PRate)/$PRate1;
	$vSaTax4B2  = ($vSaTax4*$PRate)/$PRate2;		
	$vSaTax5B1  = ($vSaTax5*$PRate)/$PRate1;
	$vSaTax5B2  = ($vSaTax5*$PRate)/$PRate2;	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_DiscountPer = $vSaDiscountPer, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_VatChkbx = $PVatChk, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_TransportAmount = $vSaTransportAmt, Delivery_TransportAmountBase1 = $vSaTransportAmtB1, Delivery_TransportAmountBase2 = $vSaTransportAmtB2, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2  ".
				  " WHERE Delivery_ID = ".$PId;
		
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


function Create_DeliveryJv($PRSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_DeliveryAutoJv(".$PRSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	//echo $query; exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_DeliveryAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_DeliveryJv: '.$error;

	Return $error;
	

}

function Create_AutoReturnSales($PRSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @result :=0 ", $conn);

	$query = " call Create_AutoReturnSales(".$PRSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @result) ";
	//echo $query; exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @result from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2 || $cur1[0] == -1)
	   $error = 'Error In Procedure Create_SalesAutoJv: '.$error;
	else if  ($cur1[0] == 0)  
	   $error = 'Error In Procedure Create_AutoReturnSales: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_AutoReturnSales: '.$error;

	Return $error;
	

}


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

HERE;
*/

?>