<?php

session_start();

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 For the Report
ini_set('max_execution_time', $config['ReportTimeExecution']);

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


//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,
				ifnull(costcentminimum,0) as costcentminimum 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 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_paymentterms,0) As Module_PaymentTerms, ".
             " ifNull(module_creditlimit,0) As Module_CreditLimit, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder, 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_ChangeInvoiceClient,0) As Module_ChangeInvoiceClient, ".
			 " ifNull(Module_ChangeInvoiceItems,0) As Module_ChangeInvoiceItems, ifNull(Module_SerialNo,0) As Module_SerialNo, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_InvoiceCheckLimit,0) As Module_InvoiceCheckLimit,IfNull(module_Checkzerosales,0) module_Checkzerosales, ".
			 " IfNull(module_sellingbyclient,0) module_sellingbyclient, ifnull(module_serialnoout,0) as module_serialnoout  ".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, TipsAccount, CashCur,  ifNull(show_discountAmount,0) As show_discountAmount From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//User Access
$querylog=" select ifNull(Fa_clientpaymentterms,0) As FA_ClientPaymentTerms, ifNull(Clientscreditlimit,0) As FA_ClientCreditLimit, ".
          " ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_ChangeInvoiceClient,0) As FI_ChangeInvoiceClient, ifNull(FI_ChangeInvoiceItems,0) As FI_ChangeInvoiceItems,  ".
		  " ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse ".
		  " 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='SSaId' value='$SSaId'>
<input type='text' name='SSaDtId' value='$SSaDtId'>
<input type='text' name='SSaVatChkbx' value='$SSaVatChkbx'>
HERE;
*/
$message='';

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

	$AllowDelete = 0;
	$message  = '';
	
	//Check Each SalesDt If Has RelatedId In DeliveryDt And Has DR
	$query = " Select Count(DeliveryDt1.DeliveryDt_id), Deliveries.Delivery_reference ".
			 " From SalesDt, DeliveryDt, DeliveryDt As DeliveryDt1, Deliveries ".
			 " Where SalesDt.SaleDt_ID = ".$SSaDtId.
			 " And SalesDt.Journal_Type = 'SI' ".
			 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
			 " And DeliveryDt1.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
			 " And DeliveryDt1.Journal_Type = 'DR' ".
			 " And DeliveryDt1.Delivery_id = Deliveries.Delivery_id ".
			 " And DeliveryDt.Journal_Type = 'DI' ".
			 " Group By Deliveries.Delivery_reference ";

	$result = selectData($connection, $query);
	$SaReturnExists = $result[0];
	
	if (empty($SaReturnExists)) $SaReturnExists = 0;
		
	if ($SaReturnExists > 0 ){
		$message  = 'Delete not allowed, return delivery exists reference= '.$result[1];
		$AllowDelete = 1;
	}
	
	
	if ($AllowDelete == 0) {
		//Check Each SalesDt If Has RelatedId and Type SR
		$query = " Select Count(SalesDt.SaleDt_id), Sales.Sale_reference ".
				 " From SalesDt, SalesDt As SalesDt1, Sales ".
				 " Where SalesDt.SaleDt_ID = ".$SSaDtId.
				 " And SalesDt1.Journal_Type = 'DR' ".
				 " And SalesDt1.RelatedDt_Id = SalesDt.SaleDt_id ".
				 " And SalesDt1.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SaReturnExists = $result[0];
		
		if (empty($SaReturnExists)) $SaReturnExists = 0;
			
		if ($SaReturnExists > 0 ){
			$message  = 'Delete not allowed, return sales exists reference= '.$result[1];
			$AllowDelete = 1;
		}
	}
	
	if ($AllowDelete == 0) {
		//Check Each SalesDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_SalesDt As SalesDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = SalesDt.SaleDt_Id ".
				 " Where SalesDt.SaleDt_ID = ".$SSaDtId.
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'SI' ";
 
		$result = selectData($connection, $query);
		$SaSerNoUsedExists = $result[0];
		
		if ($SaSerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$AllowDelete = 1;
		}
	
	}
	
	
	if ($AllowDelete == 0) {
		$querypack = " SELECT SalesDt.Item_CodePacked, SalesDt.Item_code ".
					 " FROM Temp_SalesDt As SalesDt ".
					 " Where SalesDt.SaleDt_ID = ".$SSaDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		
		//Check If Last Item In The Sales
		if ($vItemCodePacked == '') {
			$query = " Select Count(*) ".
					 " From Temp_SalesDt As SalesDt ".
					 " Where SalesDt.SaleDt_ID != ".$SSaDtId.
					 " And SalesDt.Sale_ID = ".$SSaId;
		} else {
			$query = " Select Count(*)  ".
					 " From Temp_SalesDt As SalesDt  ".
					 " Where SalesDt.Sale_ID = ".$SSaId.
					 " And SalesDt.Item_CodePacked =  '".$vItemCodePacked."'  ";

		}	

		$result = selectData($connection, $query);
		$LastItemExists = $result[0];
		
		if (empty($LastItemExists)) $LastItemExists = 0;
			
		if ($LastItemExists == 0 ){
			$message  = 'Delete not allowed, last item in waybill, if so, please press cancel button.';
			$AllowDelete = 1;
		}
	}
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 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];
		
		$vSaTaxable     = 0;
		$vSaNoneTaxable = 0;
		$vSaGrossTotal  = 0;
		$vSaDiscount    = 0;
		$vSaDiscountAmt = 0;
		$vSaVat         = 0;	
		$vSaVatChkbx    = 0;	
		$vSaDtTotal     = 0;
		$vSaDtTotalTTC  = 0;
		$vItemVat 	    = 0;
		$vSaQty		    = 0;
		$ErrorExists    = 0;
		
				
		$sub_query = " Select ifNull(sale_chkvat,0) As Sale_VatChckbx ".
					 " From Temp_Sales As Sales ".
				     " Where Sale_ID = ".$SSaId;
		$sub_result = selectData($connection, $sub_query);
		$vChkSaVat = $sub_result[0];

		
		$querypack = " SELECT SalesDt.Item_CodePacked, SalesDt.Item_code ".
					 " FROM Temp_SalesDt As SalesDt ".
					 " Where SalesDt.SaleDt_ID = ".$SSaDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
			
			// Delete From TempPucrhasesSerialNo For Selected Record
			$query = " DELETE FROM Temp_Purchasesserialno ".
					 " WHERE PurchaseDt_id  = ".$SSaDtId.
					 " AND Journal_Type = 'SI' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
		
			// Delete From TempSalesDt For Selected Record
			$query = " DELETE FROM Temp_SalesDt ".
					 " WHERE SaleDt_id = ".$SSaDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
			
			
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select SaleDt_ID, SalesDt.Item_CodePacked, SalesDt.Item_code  ".
					   " From Temp_SalesDt As SalesDt  ".
					   " Where SalesDt.Sale_ID = ".$SSaId.
					   " And SalesDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
					   //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vSaDtId =	$rowsdt[0];
				
				// Delete From TempPucrhasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						" WHERE PurchaseDt_id  = ".$vSaDtId.
						" AND Journal_Type = 'SI' ";
						//" And Logged_Code = '".$_SESSION['useraccount']."' ";
						
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 		
						
				// Delete From TempSalesDt For Selected Record
				$query = " DELETE FROM Temp_SalesDt ".
						 " WHERE SaleDt_id = ".$vSaDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}	
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
				
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SSaId, $txtDate, $SSaVatChkbx, $txtSaDiscount, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, $SaWHTChk,$SaWHTPer, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} // End If No Error Exists 

	
	} // End If No Constraints Found On Delete
	
	$txtSaId = $SSaId;
}

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

	if (empty($PSaDiscountAmt))		$PSaDiscountAmt = 0;
	if (empty($PSaDiscount))		$PSaDiscount = 0;
	if (empty($txtSaDtPrice))		$txtSaDtPrice = 0;
	if (empty($txtSaDtDiscount))    $txtSaDtDiscount = 0;
	if (empty($txtSaDtDiscountAmt))    $txtSaDtDiscountAmt = 0;
	if (empty($txtSaDtQty))	  	    $txtSaDtQty = 0;   
	if (empty($txtSaDtQty2))        $txtSaDtQty2 = 0;
	if (empty($chkSaDtPromo))	    $chkSaDtPromo = 0;
	
	if (empty($txtSaDtExpireDate))		$vSaDtExpireDate = 'Null';
	else  $vSaDtExpireDate = "'".insertMySQLDate($txtSaDtExpireDate)."'";  
	
	if ($Module_ProjectDt == 1){
		if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
		else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
	} 
	if ($Module_CostCenterDt == 1) {
		if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
		else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
	}
	$InsertAllow =1;
	if($costcentminimum == 1 && $CostCentCodeDt != ''){
			$query = "select ifnull(min(min_price),0) from costcenterPrice where costcenter_code = $CostCentCodeDt and item_code = '$txtItemCode';";
			$result = mysql_query($query,$connection);
			$rw = mysql_fetch_row($result);
			$min_price = $rw[0];
			if($min_price == '') $min_price = 0;
			if($min_price != 0 && $min_price > $txtSaDtPrice){
				$InsertAllow=0;
				$message = "Price should be greater than or equal to $min_price";
			}		
		}	
	$query = "SELECT ifnull(Item_Vat,0), 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;
	}	
			

	$WarningMsg = '';
	$vSaDtTotal = 0;
	$vSaCltCode = '';
	$vItemVat    = 0;
	$vSaQty     = 0;
	
	
		
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vSaDtTax1 = 0;
	$vSaDtTax2 = 0;
	$vSaDtTax3 = 0;
	$vSaDtTax4 = 0;
	$vSaDtTax5 = 0;
		
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;					
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtDiscAmt       = 0;
	$vSaDtDiscAmtBase1  = 0;
	$vSaDtDiscAmtBase2  = 0;

		
	$query = " Select Currency_code, ifNull(Sale_Taxable,0), ifNull(Sale_NoneTaxable,0), ifNull(Sale_DiscountPer,0), Client_code, ifNull(Sale_TransportTTC,0), ifNull(Sale_TransportAmount,0) ".
			 " From Temp_Sales As Sales ".
			 " Where Sale_ID = ".$SSaId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
					 
			
	$result=mysql_query($query,$connection) or die(mysql_error());
	$rows=mysql_fetch_array($result);
			
	$vSaCurr        = $rows[0];
	//$vSaTaxable     = $rows[1];
	//$vSaNoneTaxable = $rows[2];
	$vSaDiscount    = $rows[3];
	$vSaCltCode     = $rows[4];
	if ($SalesTTC == 1)  $vSaTranspAmt = $rows[5]; else $vSaTranspAmt = $rows[6];
			
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vSaCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
			
			
			
	//if item promotion the set price to zero
	if($ItemPromo == 1 || $chkSaDtPromo == 1) $txtSaDtPrice = 0;
			
	if ($SalesTTC == 1) {
		$vSaDtPriceTTC      = $txtSaDtPrice;
		$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
		$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

		//Added 2011/10/28
		if ($PSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
		else $vSaDtPrice = $txtSaDtPrice;							
				
		//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
		$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
		$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
							
	} else	{
		$vSaDtPrice      = $txtSaDtPrice;
		$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
		$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
					
		$vSaDtPriceTTC      = 0;
		$vSaDtPriceTTCBase1 = 0;
		$vSaDtPriceTTCBase2 = 0;
							
	}	
					
			
					
	// Calculation For Detail Discount Amount
	if($show_discountAmount ==1)	
	$vSaDtDiscAmt= $txtSaDtDiscountAmt;
	else
	$vSaDtDiscAmt       = ((($vSaDtPrice*$txtSaDtQty) - ($vSaDtPrice*$txtSaDtQty*$txtSaDtDiscount/100))*$vSaDiscount)/100;
	$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
	$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

	if($InsertAllow == 1)	{
	fbegin();
	$query = " UPDATE temp_salesdt SET  ".
		     " SaleDt_Quantity = $txtSaDtQty, Item_Unit2Qty = $txtSaDtQty2, SaleDt_Price = $vSaDtPrice, SaleDt_PriceBase1 = $vSaDtPriceBase1, ".
			 " SaleDt_PriceBase2 = $vSaDtPriceBase2, SaleDt_DiscountPer = $txtSaDtDiscount, SaleDt_PriceTTC = $vSaDtPriceTTC, Saledt_priceTTCBase1 = $vSaDtPriceTTCBase1, ".
			 " Saledt_priceTTCBase2 = $vSaDtPriceTTCBase2, Item_VAT = $item_vat, SalesDt_Remark = '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', ".
			 " SaleDt_ExpireDate = $vSaDtExpireDate, SaleDt_BatchNo = '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', SaleDt_Promotion = $chkSaDtPromo ";
	if($show_discountAmount ==1) 
		$query .= ", SaleDt_DiscountAmount =$vSaDtDiscAmt , SaleDt_DiscountBase1=$vSaDtDiscAmtBase1 ,SaleDt_DiscountBase2= $vSaDtDiscAmtBase2 ";		 
	if ($Module_ProjectDt == 1)
		$query = $query.", Project_Code = $ProjectCodeDt ";
	if ($Module_CostCenterDt == 1)	
		$query = $query.", CostCenter_Code = $CostCentCodeDt ";
		
	//Edit Item Code/Warehouse 
	if ($Module_SerialNo == 0 || $ItemSerialNo == 0)
		$query = $query.", Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."' ";
		
	$query = $query." Where SaleDt_ID = ".$SSaDtId;		 
					 
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ( $result ){ 
		fcommit();
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SSaId, $PSaDate, $PSaVatChkbx, $vSaDiscount, 0, $vSaTranspAmt, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$SaWHTChk,$SaWHTPer, 'U', $connection);
		$message  = $message . $CalculateResult;
				
	}else{
		$message  = mysql_error(); 
		frollback();
	}
			
	}
} 

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

	$AllowDelete = 0;
	$message  = '';
	
	//Check If Sales Is Posted
	$query = "SELECT ifNull(Sale_Posted,0) As SalesPosted, ifNull(Sale_Mode,0) FROM Sales WHERE Sale_id = ".$SSaId;
	$result = selectData($connection, $query);
	$SaPosted  = $result[0];
	$vSaleMode = $result[1];
	
	if ($SaPosted == 1 ){
		$message  = 'Delete not allowed, Invoice posted.';
		$AllowDelete = 1;
	}
	
	if ($AllowDelete == 0) {
		//Check Each SalesDt If Has RelatedId and Type SR
		$query = " Select Count(SalesDt.SaleDt_id), Sales.Sale_reference ".
				 " From SalesDt, SalesDt As SalesDt1, Sales ".
				 " Where SalesDt.Sale_ID = ".$SSaId.
				 " And SalesDt1.Journal_Type = 'SR' ".
				 " And SalesDt1.RelatedDt_Id = SalesDt.SaleDt_id ".
				 " And SalesDt1.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SaReturnExists = $result[0];
			
		if ($SaReturnExists > 0 ){
			$message  = 'Delete not allowed, return invoice exists reference= '.$result[1];
			$AllowDelete = 1;
		}
	}	
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
	
	    $sub_query = " Select Journal_Id From Sales Where Sale_id = ".$SSaId;
		$sub_result = selectData($connection, $sub_query);
		$vSaJournalID = $sub_result[0];
		if(empty($vSaJournalID)) $vSaJournalID = -1;
		
		
	    // Delete From PurchasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE PurchaseDt_id In (Select SaleDt_id From SalesDt Where Sale_id = ".$SSaId." ) ".
				 " AND Journal_Type = 'SI' ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					if($config['log_file'] == 1){
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'sales', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}		
		// Delete From SalesDt For Selected Record
		$query = " DELETE FROM SalesDt ".
				 " WHERE Sale_id = ".$SSaId;
					 
		if (updateData($connection, $query, true)) {
			//If Cash Payment Then Allocate Invoice In Acclink
			if ($vSaleMode == 1) {
				$message = CashPaymentInvoice($SSaId, 'D', $Module_Delivery, $_SESSION['useraccount'], $_SESSION['dbLabel'], $_SESSION['dbName'], $connection);
			}
			
			
			
			// Delete From Sales For Selected Record
			$query = " DELETE FROM Sales ".
					 " WHERE Sale_id = ".$SSaId;
				
			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") && $SSaId != ''){

	// Delete From TempPurchasesSerialNo For Selected Record
	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE PurchaseDt_id In (Select SaleDt_id From Temp_SalesDt Where Sale_id = ".$SSaId." ) ".
			 " AND Journal_Type = 'SI' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
			
	// Delete From TempSalesDt For Selected Record
	$query = " DELETE FROM Temp_SalesDt ".
			 " WHERE Sale_id = ".$SSaId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempSales For Selected Record
		$query = " DELETE FROM Temp_Sales ".
				 " WHERE Sale_id = ".$SSaId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

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

	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_sales (Sale_ID, Sale_Reference, Sorder_reference, Sale_Date, JournalDt_ValueDate, Sale_Remark, Client_code, Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, Salesman_Code, ".
	         " Currency_Code, Project_Code, Costcenter_code, Sale_Posted, Sale_Edit, Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, ".
			 " Sale_DiscountAmount, Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, ".
			 " Sale_Mode, Journal_Type, Journal_Id, Sales_BelongsToGroup, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
			 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, ".
			 " Sale_Acctax4, Sale_Acctax5, Sale_TotalTax, Sale_TotalTaxBase1, Sale_TotalTaxBase2, Sale_CreditCur, Sale_CreditAccount, Sale_Vataccount, Sale_creditaccountvat, ".
			 " Sale_CreditCLA, Sale_CreditDCT, Sale_CreditAW, Sale_CreditTRP, Sale_PromotionAcc, Sale_chkvat, Sale_TaxableTTC, Sale_DiscountTTC, Sale_RelatedId, Sale_SorderReferences, ".
			 " Sale_DeliveryReferences, Sale_TransportAccount, Sale_TransportAmount, Sale_TransportBase1, Sale_TransportBase2, Sale_TransportTTC, Sale_BonusAccount, Sale_BonusAmount, ".
			 " Sale_BonusBase1, Sale_BonusBase2, Sale_BonusTTC, Sale_ManualNo, Sale_vehicleweight, Sale_vehicleLoadweight, Sale_vehicleRealweight, Sale_CashCur, Sale_CashAccount, Sale_Cash, ".
			 " Sale_CashBase1, Sale_CashBase2, Sale_CashInBase1, Sale_CashOutBase1, Sale_CashInBase2, Sale_CashOutBase2, Sale_TipsBase1, Sale_TipsAccount, Sale_PrintReceipt, User_Account, Logged_Code, ".
			 " Sale_WHTchecked, Sale_WHTAmount, Sale_WHTAmountBase1, Sale_WHTAmountBase2 ) ".
			 " SELECT Sale_ID, Sale_Reference, Sorder_reference, Sale_Date, JournalDt_ValueDate, Sale_Remark, Client_code, Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, Salesman_Code, ".
	         " Currency_Code, Project_Code, Costcenter_code, Sale_Posted, Sale_Edit, Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, ".
			 " Sale_DiscountAmount, Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, ".
			 " Sale_Mode, Journal_Type, Journal_Id, Sales_BelongsToGroup, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
			 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, ".
			 " Sale_Acctax4, Sale_Acctax5, Sale_TotalTax, Sale_TotalTaxBase1, Sale_TotalTaxBase2, Sale_CreditCur, Sale_CreditAccount, Sale_Vataccount, Sale_creditaccountvat, ".
			 " Sale_CreditCLA, Sale_CreditDCT, Sale_CreditAW, Sale_CreditTRP, Sale_PromotionAcc, Sale_chkvat, Sale_TaxableTTC, Sale_DiscountTTC, Sale_RelatedId, Sale_SorderReferences, ".
			 " Sale_DeliveryReferences, Sale_TransportAccount, Sale_TransportAmount, Sale_TransportBase1, Sale_TransportBase2, Sale_TransportTTC, Sale_BonusAccount, Sale_BonusAmount, ".
			 " Sale_BonusBase1, Sale_BonusBase2, Sale_BonusTTC, Sale_ManualNo, Sale_vehicleweight, Sale_vehicleLoadweight, Sale_vehicleRealweight, Sale_CashCur, Sale_CashAccount, Sale_Cash, ".
			 " Sale_CashBase1, Sale_CashBase2, Sale_CashInBase1, Sale_CashOutBase1, Sale_CashInBase2, Sale_CashOutBase2, Sale_TipsBase1, Sale_TipsAccount, Sale_PrintReceipt, User_Account, ".
			 " '".$_SESSION['useraccount']."', Sale_WHTchecked, Sale_WHTAmount, Sale_WHTAmountBase1, Sale_WHTAmountBase2 ".
			 " FROM Sales ".
			 " WHERE Sale_id = ".$SSaId;
	
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 	

	//echo $message.$query; exit;				 
	$query = " INSERT INTO temp_salesdt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_CodePacked, SaleDt_Quantity, ". 
             " SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, Item_Vat, SaleDt_PriceTTC, Saledt_priceTTCBase1, ".
             " Saledt_priceTTCBase2, SalesDt_Remark, Saledt_DirectStkDbt, Saledt_DirectStkCrd, Saledt_DirectStkCur, Saledt_ItemAccount, Saledt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, ".
			 " Item_Tax4, Item_Tax5, Saledt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, SaleDt_TransportAmount, SaleDt_TransportBase1, SaleDt_TransportBase2, SaleDt_BonusAmount, SaleDt_BonusBase1, ".
			 " SaleDt_BonusBase2, SaleDt_DiscountAcc, SaleDt_ExpireDate, SaleDt_BatchNo, SaleDt_VatAccount, salesdt_CostAcc, salesdt_CostBase1, salesdt_CostBase2, salesdt_Account, Logged_Code ) ".
			 " SELECT SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_CodePacked, SaleDt_Quantity, ". 
             " SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, Item_Vat, SaleDt_PriceTTC, Saledt_priceTTCBase1, ".
             " Saledt_priceTTCBase2, SalesDt_Remark, Saledt_DirectStkDbt, Saledt_DirectStkCrd, Saledt_DirectStkCur, Saledt_ItemAccount, Saledt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, ".
			 " Item_Tax4, Item_Tax5, Saledt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, SaleDt_TransportAmount, SaleDt_TransportBase1, SaleDt_TransportBase2, SaleDt_BonusAmount, SaleDt_BonusBase1, ".
			 " SaleDt_BonusBase2, SaleDt_DiscountAcc, SaleDt_ExpireDate, SaleDt_BatchNo, SaleDt_VatAccount, salesdt_CostAcc, salesdt_CostBase1, salesdt_CostBase2, salesdt_Account, '".$_SESSION['useraccount']."'  ".
			 " FROM Salesdt ".
			 " WHERE Sale_id = ".$SSaId;
	
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 			


	$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, SaleDt_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.SaleDt_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_SalesDt on Purchasesserialno.PurchaseDt_id = Temp_SalesDt.SaleDt_ID ".
			 " WHERE Temp_SalesDt.Sale_id = ".$SSaId.
			 " AND Purchasesserialno.Journal_Type = 'SI' ";
			 
	
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 

}



//Load Delivery
else if($mainmode == "loaddelivery" ){
	

	$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
			 " from warehouse inner join ".$_SESSION['dbLabel'].".loginstk on warehouse.warehouse_code = loginstk.warehouse_code ".
			 " where user_account='".$_SESSION['useraccount']."' ".
			 " and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
			 " order by warehouse.warehouse_code";
	$whresult = mysql_query($querywh,$connection) or die(mysql_error());
	$whexist  = mysql_num_rows($whresult);
	
	//Insert Master Table
	if ($SSaId == ""){
		
		$sub_query = "Select Client_Code From Deliveries Where Delivery_id = '".$SelectedRec."'";
		$sub_result = selectData($connection, $sub_query);
		$vDeliveryClient = $sub_result[0];
		
		$sub_query = "Select Client_VAT From clients Where ledger_number = '".$vDeliveryClient."'";
		
		$sub_result = selectData($connection, $sub_query);
		$vClientVat = $sub_result[0];
			 
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, CreditCur, CreditAccount, TipsAccount, ".
					 " VatAccount, CreditAccountVAT, Sale_CLAAccount, Sale_DCTAccount, Sale_AWAccount, Sale_TRPAccount, PromotionAccount, ".
					 " TransportAccount, BonusAccount, CreditAccountNonStock, CreditAccountVatNonStock ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$vDeliveryClient."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
	
		fbegin();	
		$vSaId = get_nextsequence('sales_id','',$connection);	
		fcommit();
	
		fbegin();	
		$query = " INSERT INTO temp_sales (Sale_ID, Sale_Reference, Sale_Date, JournalDt_ValueDate, Sale_Remark, Client_code, Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcenter_code, Sale_Posted, Sale_Edit, Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, ".
				 " Sale_DiscountAmount, Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, ".
				 " Sale_Mode, Journal_Type, Journal_Id, Sales_BelongsToGroup, Sale_chkvat, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, Sale_TipsAccount, ".
				 " Sale_Vataccount, Sale_creditaccountvat, Sale_CreditCLA, Sale_CreditDCT, Sale_CreditAW, Sale_CreditTRP, Sale_PromotionAcc, Sorder_reference, Sale_RelatedId, Sale_SorderReferences, Sale_DeliveryReferences, ".
				 " Sale_TransportAccount, Sale_BonusAccount,Sale_vehicleweight,Sale_vehicleLoadweight, User_Account, Logged_Code,Sale_WHTchecked) ".
				 " SELECT $vSaId, Null, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), Delivery_Remark, Deliveries.Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Deliveries.Salesman_Code, ".
				 " Deliveries.Currency_Code, Deliveries.Project_Code, Deliveries.Costcent_code, Delivery_Posted, Delivery_Edit, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 " Delivery_Mode, 'SI', Null, Delivery_BelongsToGroup, ".$vClientVat.", '".$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[12]."', '".$Acc_Result[13]."', ".
				 " '".$Acc_Result[14]."', Sorder_reference, Delivery_Reference, Delivery_SorderReferences, Delivery_Reference, '".$Acc_Result[15]."', '".$Acc_Result[16]."',Delivery_vehicleweight,Delivery_vehicleLoadweight, ".
				 " Deliveries.User_Account, '".$_SESSION['useraccount']."', ifnull(WHTchecked,0) ".
				 " FROM Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
				 " WHERE Delivery_id = ".$SelectedRec;
			// echo $query."<br>";exit;	
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SSaId = $vSaId;
			fcommit();
		}else{
			$vSaId = "";
			$SSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	
	$vItemVat   = 0;
	$vSaDtTotal = 0;
	$vSaTaxable = 0;
	$vSaNoneTaxable = 0;
	$vSaGrossTotal  = 0;
	$vSaDiscountAmt = 0;
	$vSaDiscountPer = 0;
	$vSaTransAmt 	= 0;
	
		
	$vSaDate     = '';
	$vSaVatChkbx = 0;
	
	
	if ($SSaId != '') {
	
		$vSaId = $SSaId;
		
		$sub_query11 = " SELECT Temp_Sales.Currency_Code, Sale_Date, Client_Code, Temp_Sales.Project_Code, Temp_Sales.CostCenter_Code, ifNull(Sale_DiscountPer,0), ".
					   " Date_Format(Sale_Date,'%d/%m/%Y') As SaleDate, ifNull(Sale_chkvat,0), ifNull(Sale_DiscountAmount,0), ifNull(Sale_TransportAmount,0), ifNull(Sale_Mode,0), ifnull(Sale_WHTchecked,0), WHTPercentage ".
					   " FROM Temp_Sales ".
					   "  Inner Join Clients on Client_Code = Clients.Ledger_Number ".
					   " WHERE Sale_ID = '".$vSaId."' ";// echo $sub_query11;exit;
		$sub_result11 = selectData($connection, $sub_query11);
		
		$vSaDiscountPer = $sub_result11[5];				   
		if (empty($vSaDiscountPer)) $vSaDiscountPer = 0;
		
		$vSaDate        = $sub_result11[6];
		$vSaVatChkbx    = $sub_result11[7];
		$vSaDiscountAmt = $sub_result11[8];
		$vSaTransAmt 	= $sub_result11[9];
		$vSaClientCode 	= $sub_result11[2];
		$vSaPayMode 	= $sub_result11[10];
		$vSaWHTCheck 	= $sub_result11[11];
		$vSaWHTPer 		= $sub_result11[12];
		
		$sub_query = " SELECT DeliveryDt_id, DeliveryDt.Currency_Code, DeliveryDt.Warehouse_Code, DeliveryDt.Item_code, DeliveryDt.Item_CodePacked, ifNull(DeliveryDt_Quantity,0), ".
					 " ifNull(SorderDt.SorderDt_Price,0), ifNull(SorderDt.SorderDt_PriceBase1,0), ifNull(SorderDt.SroderDt_PriceBase2,0), ifNull(SorderDt.SorderDt_Discount,0), ".
					 " ifNull(DeliveryDt.Item_Vat,0), ifNull(SorderDt.SorderDt_PriceTTC,0), DeliveryDt_Remark, ifNull(DeliveryDt_promotion,0), DeliveryDt.Client_Code, DeliveryDt.User_Account, ".
					 " DeliveryDt.Project_Code, DeliveryDt.CostCent_Code, DeliveryDt.DeliveryDt_ExpireDate, DeliveryDt.DeliveryDt_BatchNo,  ".
					 " ifNull(((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt.SorderDt_Price,0)) - (ifNull(SorderDt_Quantity,0)*ifNull(SorderDt.SorderDt_Price,0)*(1 - ifNull(SorderDt.SorderDt_Discount,0)/100) - ifNull(SorderDt_DiscountAmount,0)))*100/(ifNull(SorderDt_Quantity,0)*ifNull(SorderDt.SorderDt_Price,0)), 0), ".
					 " ifNull(((ifNull(SorderDt_TransportAmount,0)/(ifNull(SorderDt_Quantity,0)*ifNull(SorderDt.SorderDt_Price,0)*(1 - ifNull(SorderDt.SorderDt_Discount,0)/100) - ifNull(SorderDt_DiscountAmount,0)))*100), 0),  ".
					 " ifNull(SorderDt_DiscountAmount,0) as SorderDt_DiscountAmount, Deliverydt_costbase1, Deliverydt_costbase2, Deliverydt_DirectStkDbt ".
					 " FROM DeliveryDt Left Join Sorderdt on Sorderdt.SorderDt_Id = DeliveryDt.RelatedDt_ID ";
					 
		if ($whexist > 0 && $FI_FrmRestrictWarehouse == 1)
			$sub_query = $sub_query." Inner join ( select distinct loginstk.warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
									" 				where loginstk.user_account='".$_SESSION['useraccount']."' ".
									" 				and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
									"			 ) Q1 on DeliveryDt.warehouse_code = Q1.warehouse_code ";			 
		
		if($SSaDtId != '')			 
			$sub_query = $sub_query." WHERE DeliveryDt_Id In (".$SSaDtId.")";
		else 
			$sub_query = $sub_query." WHERE DeliveryDt.Delivery_Id = '".$SelectedRec."'";		
			
		
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
		
			$vSaDtPrice         = 0;
			$vSaDtPriceBase1    = 0;
			$vSaDtPriceBase2    = 0;
			$vSaDtDiscPer       = 0;
			$vSaDtPriceTTC      = 0;
			$vSaDtPriceTTCBase1 = 0;
			$vSaDtPriceTTCBase2 = 0;
			$vSaDtDiscAmt       = 0;
			$vSaDtDiscAmtBase1  = 0;
			$vSaDtDiscAmtBase2  = 0;
			$vSaDtItemTax1      = 0;
			$vSaDtItemTax2      = 0;
			$vSaDtItemTax3      = 0;
			$vSaDtItemTax4      = 0;
			$vSaDtItemTax5      = 0;
			
			$vSaDtTrsPer        = 0;
			$vSaDtTrsAmt        = 0;
			$vSaDtTrsAmtB1      = 0;
			$vSaDtTrsAmtB2      = 0;
			
			$vSaDtCostBase1 	= 0;
			$vSaDtCostBase2 	= 0;
			
			$vSaDtCostBase1		= $row[23];
			$vSaDtCostBase2		= $row[24];
			$vLedger_Account	= $row[25];
			
			$sub_query4 = " Select Sum(ifNull(SalesDt.SaleDt_Quantity,0)) As QuantitySold ".
					      " From SalesDt ".
						  " Where SalesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And SalesDt.Sale_Id != '".$vSaId."' ";
			$sub_result4 = selectData($connection, $sub_query4);
			if ($sub_result4[0] == '') $sub_result4[0] = 0;
	
			$sub_query5 = " Select Sum(ifNull(Temp_SalesDt.SaleDt_Quantity,0)) As QuantitySoldTemp ".
					      " From Temp_SalesDt ".
					      " Where Temp_SalesDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And Temp_SalesDt.Sale_Id = '".$vSaId."' ";
			$sub_result5 = selectData($connection, $sub_query5);
			if ($sub_result5[0] == '') $sub_result5[0] = 0;		  
			     
			
			$sub_query6 = " Select Sum(ifNull(DR.DeliveryDt_Quantity,0)) As QuantityReturned ".
					      " From DeliveryDt DR ".
					      " Where DR.RelatedDt_ID =  '".$row[0]."' ".
						  " And DR.Journal_Type = 'DR' ";
			$sub_result6 = selectData($connection, $sub_query6);
			if ($sub_result6[0] == '') $sub_result6[0] = 0;		  
			

			//Get The Remaining Qty
			$vSaDtQty = ($row[5] - ($sub_result4[0] + $sub_result5[0] + $sub_result6[0]));
			
			if ($vSaDtQty > 0 ) {
				
			
				$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0) ".
						 " FROM Items WHERE item_Code = '".$row[3]."'";
				$result = selectData($connection, $query);
				$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;
				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;
				}
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$row[1]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$row[1]."' )";
				$result = selectData($connection, $query);
				$rate_dt = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
				$result = selectData($connection, $query);
				$rate_dt1 = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
				$result = selectData($connection, $query);
				$rate_dt2 = $result[0];		
				
				//If Price Is Not Zero And Item Not Promo
				if (($row[6] > 0	&& $row[13] == 0) || ($row[13] == 1) || ($row[4] != '')) {
					$vSaDtPrice         = $row[6];
					//$vSaDtPriceBase1    = $row[7];
					//$vSaDtPriceBase2    = $row[8];
					$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
					$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
					
					$vSaDtDiscPer       = $row[20];
					$vSaDtPriceTTC      = $row[11];
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
				}
				else {
					
					$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$row[14]."'";
					//echo "<br><br>".$query;
					$result = selectData($connection, $query);
					$c_sp = $result[0];
					
					
					if($module_sellingbyclient == 1)
					$query = "SELECT ifnull(sellingprice,Item_SellingPrice1), Item_SellingPrice2, Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6 
							FROM items 
							left join sellingpricebyclient sp on sp.item_code = items.Item_Code and client_code = '$vDeliveryClient'
							WHERE items.Item_Code = '".$row[3]."'";	
					else
					$query = "SELECT Item_SellingPrice1, Item_SellingPrice2, Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6 FROM items WHERE Item_Code = '".$row[3]."'";
						
					//echo "<br><br>".$query;
					$result = selectData($connection, $query);
					$i_sp = $result[0];
						
					switch ($c_sp){
						case "II":
							$i_sp = $result[1]; break;
						case "III":
							$i_sp = $result[2]; break;
						case "IV":
							$i_sp = $result[3]; break;
						case "V":
							$i_sp = $result[4]; break;
						case "VI":
							$i_sp = $result[5]; break;
					}
					
					if ($SalesTTC == 1) {
						$vSaDtPriceTTC      = $i_sp;
						$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;					
					
						$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
						$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
						$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
								
					} else	{
						$vSaDtPrice      = $i_sp;
						$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
						$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
						
						$vSaDtPriceTTC      = 0;
						$vSaDtPriceTTCBase1 = 0;
						$vSaDtPriceTTCBase2 = 0;
								
					}
					
					$vSaDtDiscPer = 0;
					
					
				}
				
				// Calculation For Detail Discount Amount
				if($show_discountAmount == 1) 
				$vSaDtDiscAmt       = $row[22];
				else 
				$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$vSaDtDiscPer/100))*$vSaDiscountPer)/100;
				$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
				
				// Calculation For Detail Transport
				$vSaDtTrsPer        = $row[21];
				$vSaDtTrsAmt   		= ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$vSaDtDiscPer/100))*$vSaDtTrsPer)/100;
				$vSaDtTrsAmtB1      = ($vSaDtTrsAmt*$rate_dt)/$rate_dt1;
				$vSaDtTrsAmtB2      = ($vSaDtTrsAmt*$rate_dt)/$rate_dt1;
				$vSaTransAmt		= $vSaTransAmt + $vSaDtTrsAmt;
				//echo $vSaDtTrsPer; exit;

				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 = '".$row[14]."'";
										 
					$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 = '".$row[3]."'";
										 
					$result = selectData($connection, $query);

					
					if ($vCltTax1 != 0)	$vSaDtItemTax1 = $result[0];
					if ($vCltTax2 != 0)	$vSaDtItemTax2 = $result[1];
					if ($vCltTax3 != 0)	$vSaDtItemTax3 = $result[2];
					if ($vCltTax4 != 0)	$vSaDtItemTax4 = $result[3];
					if ($vCltTax5 != 0)	$vSaDtItemTax5 = $result[4];
						
				}		
					
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, ".
						 " CreditAccountNonStock, CreditAccountVatNonStock, 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];
						
				$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$vDeliveryClient."' ";	
				$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_export, ledger_costAcc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " 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];
				$vLedger_costAcc		= $result[12];
				
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
							
					if ($item_vat > 0 && $vSaVatChkbx == 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 ($item_vat > 0 && $vSaVatChkbx == 1) {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
					} else {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
						else	
							$vSaDtItemAcc = $vSaStpCreditAcc;
					}

					/*if ($vSaPayMode == 1) {
						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAccCash;
						else	
							$vSaDtVatAcc = $vSaStpVatAccCash;
					} else {*/
						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAcc;
						else	
							$vSaDtVatAcc = $vSaStpVatAcc;
					//}
	
				}
				
				if($clientexp == 1) $vSaDtItemAcc = $result[11]; 
				
				$sub_queryVat = " SELECT GetVATAccount('".$vSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
						
				fbegin();
				$vSaDtId = get_nextsequence('saledt_id','',$connection);	
				fcommit();
				
					 
				fbegin();
				
				$SaleDt_ExpireDate = $row[18];
				if (empty($SaleDt_ExpireDate)) $SaleDt_ExpireDate = 'Null';
				else $SaleDt_ExpireDate = "'".$SaleDt_ExpireDate."'";
				
				$ProjectCode = $row[16];
				if (empty($ProjectCode)) $ProjectCode = 'Null';
				else $ProjectCode = "'".$ProjectCode."'";
				
				$CostCentCode = $row[17];
				if (empty($CostCentCode)) $CostCentCode = 'Null';
				else $CostCentCode = "'".$CostCentCode."'";
				
				$sub_query1 = " INSERT INTO temp_salesdt (SaleDt_id, Sale_id, RelatedDt_Id, Currency_Code, Sale_Date, Client_Code, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_CodePacked, SaleDt_Quantity, ". 
							  " SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, Item_Vat, SaleDt_PriceTTC, ".
							  " Saledt_priceTTCBase1, Saledt_priceTTCBase2, SalesDt_Remark, Saledt_DirectStkDbt, Saledt_DirectStkCrd, Saledt_DirectStkCur, Saledt_discountacc, Saledt_ItemAccount, ".
							  " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Saledt_promotion, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Saledt_BelongsToGroup, SaleDt_ExpireDate, SaleDt_BatchNo, ".
							  " SaleDt_TransportAmount, SaleDt_TransportBase1, SaleDt_TransportBase2, SaleDt_VatAccount, salesdt_CostAcc, salesdt_CostBase1, salesdt_CostBase2, salesdt_Account, Logged_Code ) ".
							  " VALUES ( $vSaDtId, $vSaId, '".$row[0]."', '".$row[1]."', '".$sub_result11[1]."', '".$sub_result11[2]."', $ProjectCode, $CostCentCode, '".$row[2]."', '".$row[3]."', '".$row[4]."', '".$vSaDtQty."', ".
							  " $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $vSaDtDiscPer, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, '".$item_vat."', $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($row[12]))."', '".$vSaDtDirectStkDbt."', ".
							  " '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', $vSaDtItemTax1, $vSaDtItemTax2, $vSaDtItemTax3, $vSaDtItemTax4, $vSaDtItemTax5, ".$row[13].", ".
							  " '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'SI', $FI_BelongsToGrp, $SaleDt_ExpireDate, '".$row[19]."', $vSaDtTrsAmt, $vSaDtTrsAmtB1, $vSaDtTrsAmtB2, '".$vSaDtVatAcc."', ".
							  " '".$vLedger_costAcc."', '".$vSaDtCostBase1."', '".$vSaDtCostBase2."', '".$vLedger_Account."', '".$_SESSION['useraccount']."' ) ";
							 
				//echo $sub_query1; exit;	
				$sub_result1=mysql_query($sub_query1,$connection);
				
			
				if ($sub_result1){
					fcommit();
					
					$sub_query3 = " SELECT Serial_ID, purchasesserialno.Item_Code, purchasesserialno.Warehouse_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ifNull(SerialNo_Quantity,0), (ifNull(SerialNo_QuantitySold,0) + 1)  ".
								  " FROM purchasesserialno ".
								  " WHERE purchasesserialno.PurchaseDt_ID  = '".$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 = 'SI'  ".
								  "                  union  ".
								  "                  select 1 from temp_purchasesserialno ".
								  "                  where temp_purchasesserialno.RelatedSerial_Id = purchasesserialno.Serial_ID ".
								  "                  And temp_purchasesserialno.Journal_Type = 'SI' ) ";
								  
					//echo $sub_query3; exit;
					$sub_result3 = mysql_query($sub_query3,$connection) or die(mysql_error());
					while($sub_row3=mysql_fetch_array($sub_result3)){
						fbegin();
						$vSerId = get_nextsequence('Serial_Id','',$connection);	
						fcommit();
							
						$sub_query7 = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, SaleDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
									  " VALUES ( ".$vSerId.", 'SI', $vSaDtId, $vSaDtId, '".$sub_row3[1]."', '".$sub_row3[3]."', 0, '".$sub_row3[0]."', '".$sub_row3[6]."', '".$sub_row3[7]."', '".$sub_row3[2]."', '".$_SESSION['useraccount']."' ) ";
						//echo $sub_query7; exit;										 
						$sub_result7 = mysql_query($sub_query7,$connection);	
					}
					
					
				}else{
					$message  = mysql_error(); 
					frollback();
				}
			} // End if($vSaDtQty > 0)
		}  //End Loop of DeliveryDt Query
		
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($vSaId, $vSaDate, $vSaVatChkbx, $vSaDiscountPer, $vSaDiscountAmt, $vSaTransAmt, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$vSaWHTCheck,$vSaWHTPer, 'I', $connection);
		$message  = $message . $CalculateResult;
		
			
		if($SSaDtId != '') {	
			// Getting Delivery and Sorder references For Related Items
			$vSorderAllRef = '';
			$vDeliveryAllRef = '';
			
			$sub_query = " SELECT Distinct Deliveries.Delivery_Reference, Sorder.Sorder_Reference ".
						 " FROM DeliveryDt Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
						 " Inner Join SorderDt on DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID ".
						 " Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						 " Inner Join Temp_SalesDt As SalesDt on SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_ID ".
						 " WHERE SalesDt.Sale_Id  = ".$vSaId;

			$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_row=mysql_fetch_array($sub_result)){
				
				$pos = strrpos($vDeliveryAllRef, $sub_row[0]);
				if ($pos === false) { 
					$vDeliveryAllRef = $vDeliveryAllRef.','.$sub_row[0];
				}

				
				$vSorderAllRef = $vSorderAllRef.','.$sub_row[1];
				
			}
			
			$sub_query1 = " UPDATE temp_sales SET ".
						  " Sale_DeliveryReferences = Substr('".$vDeliveryAllRef."',2,length('".$vDeliveryAllRef."')), ".
						  " Sale_SorderReferences   = Substr('".$vSorderAllRef."',2,length('".$vSorderAllRef."')) ".
						  " WHERE Sale_ID = ".$vSaId;
			//echo $sub_query1; exit;		 
			$sub_result1=mysql_query($sub_query1,$connection);
		}
		
	}

}

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

	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	$CashAccount = $txtLedgerNo;
	
	$vSaPrtReceipt = $txtSaPrtReceipt;
	$vSaCashInB1   = $txtSaCashInB1;
	$vSaCashOutB1  = $txtSaCashOutB1;
	$vSaCashInB2   = $txtSaCashInB2;
	$vSaCashOutB2  = $txtSaCashOutB2;
	$vSaTipsB1     = $txtSaTipsB1;
	
	if (empty($vSaPrtReceipt)) $vSaPrtReceipt = 0;
	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(Sale_Total,0) + IfNull(Sale_VAT,0) + IfNull(Sale_TransportAmount,0) + IfNull(Sale_BonusAmount,0) - IfNull(Sale_DiscountAmount,0) + ".
				 "         (ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0))) As Sale_NetTotal,  ".
				 " ( ifNull(Sale_TotalBase1,0) + IfNull(Sale_VatBase1,0) + IfNull(Sale_TransportBase1,0) + IfNull(Sale_BonusBase1,0) - IfNull(Sale_DiscountBase1,0) + ".
				 "  (ifNull(sale_Tax1Base1,0) + ifNull(sale_Tax2Base1,0) + ifNull(sale_Tax3Base1,0) + ifNull(sale_Tax4Base1,0) + ifNull(sale_Tax5Base1,0))) As Sale_NetTotalB1,  ".
				 " ( ifNull(Sale_TotalBase2,0) + IfNull(Sale_VatBase2,0) + IfNull(Sale_TransportBase2,0) + IfNull(Sale_BonusBase2,0) - IfNull(Sale_DiscountBase2,0) + ".
				 "  (ifNull(sale_Tax1Base2,0) + ifNull(sale_Tax2Base2,0) + ifNull(sale_Tax3Base2,0) + ifNull(sale_Tax4Base2,0) + ifNull(sale_Tax5Base2,0))) As Sale_NetTotalB2  ".
				 " From Temp_Sales As Sales ".
			     " Where Sales.Sale_Id = '".$SSaId."'";
			   
		//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_sales SET Sale_Mode = 1, Sale_PrintReceipt = $vSaPrtReceipt, ".
				 " Sale_CashInBase1 = $vSaCashInB1, Sale_CashOutBase1 = $vSaCashOutB1, Sale_CashInBase2 = $vSaCashInB2,  ".
				 " Sale_CashOutBase2 = $vSaCashOutB2, Sale_TipsBase1 = $vSaTipsB1, Sale_TipsAccount = '".$TipsAccount."', ".
				 " Sale_CashCur = '".$CashCur."', Sale_CashAccount = '".$CashAccount."', ".
				 " Sale_Cash = $vSaNetTotal, Sale_CashBase1 = $vSaNetTotalB1, Sale_CashBase2 = $vSaNetTotalB2 ".
				 " WHERE Sale_ID = ".$SSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
		} 
		
		//Change VAT Item Accounts
		/*if ($ErrorExists == 0 && $Module_RawMaterial != 1) {
			$query = " SELECT VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS FROM salessetup ";
			$result = selectData($connection, $query);
						
			$vSaStpVatAcc 		  	  = $result[0];
			$vSaStpVatNonStockAcc 	  = $result[1];
			$vSaStpVatAccCash	  	  = $result[2];
			$vSaStpVatNonStockAccCash = $result[3];
			
			$sub_query = " Select SalesDt.SaleDt_Id, SalesDt.Client_Code, SalesDt.Item_Code, ifNull(Item_NonStock,0) ".
						 " From temp_salesdt as SalesDt Inner Join Items on SalesDt.Item_Code = Items.Item_Code ".
						 " Where Sale_ID = ".$SSaId;
			$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_row=mysql_fetch_array($sub_result)){
				$vSaClientCode = $sub_row[1];
				$ItemNonStock  = $sub_row[3];
				
				if ($ItemNonStock == 1)
					$vSaDtVatAcc = $vSaStpVatNonStockAccCash;
				else	
					$vSaDtVatAcc = $vSaStpVatAccCash;
					
				$sub_queryVat = " SELECT GetVATAccount('".$vSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
			
				$query = " UPDATE temp_salesdt SET SaleDt_VatAccount = '".$vSaDtVatAcc."' WHERE SaleDt_ID = ".$sub_row[0];
				$result=mysql_query($query,$connection);
			}		
		
		}*/
	}
}

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

	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	if ($ErrorExists == 0) {
		 
		$query = " UPDATE temp_sales SET Sale_Mode = 0, Sale_PrintReceipt = 0, ".
				 " Sale_CashInBase1 = 0, Sale_CashOutBase1 = 0, Sale_CashInBase2 = 0, Sale_CashOutBase2 = 0,  ".
				 " Sale_TipsBase1 = 0, Sale_Cash = 0, Sale_CashBase1 = 0, Sale_CashBase2 = 0 ".
				 " WHERE Sale_ID = ".$SSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
		} 
		
		//Change VAT Item Accounts
		/*if ($ErrorExists == 0 && $Module_RawMaterial != 1) {
			$query = " SELECT VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS FROM salessetup ";
			$result = selectData($connection, $query);
						
			$vSaStpVatAcc 		  	  = $result[0];
			$vSaStpVatNonStockAcc 	  = $result[1];
			$vSaStpVatAccCash	  	  = $result[2];
			$vSaStpVatNonStockAccCash = $result[3];
			
			$sub_query = " Select SalesDt.SaleDt_Id, SalesDt.Client_Code, SalesDt.Item_Code, ifNull(Item_NonStock,0) ".
						 " From temp_salesdt as SalesDt Inner Join Items on SalesDt.Item_Code = Items.Item_Code ".
						 " Where Sale_ID = ".$SSaId;
			$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_row=mysql_fetch_array($sub_result)){
				$vSaClientCode = $sub_row[1];
				$ItemNonStock  = $sub_row[3];
				
				if ($ItemNonStock == 1)
					$vSaDtVatAcc = $vSaStpVatNonStockAcc;
				else	
					$vSaDtVatAcc = $vSaStpVatAcc;
					
				$sub_queryVat = " SELECT GetVATAccount('".$vSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
			
				$query = " UPDATE temp_salesdt SET SaleDt_VatAccount = '".$vSaDtVatAcc."' WHERE SaleDt_ID = ".$sub_row[0];
				$result=mysql_query($query,$connection);
			}		
		
		}*/
	}
}

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

	if (empty($txtSaDiscountAmt))	$txtSaDiscountAmt = 0;
	if (empty($txtSaDiscount))		$txtSaDiscount = 0; 
	if (empty($txtSaTransportAmt))	$txtSaTransportAmt = 0;	
	if (empty($txtSaBonusAmt))		$txtSaBonusAmt = 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_sales WHERE Sale_ID = $SSaId ";
	$sub_result = selectData($connection, $sub_query);
	$txtSaTransportAmt = ConvertCurrency($sub_result[0], $txtCurr, insertMySQLDate($txtDate), $txtSaTransportAmt, $connection);	
	$txtSaBonusAmt = ConvertCurrency($sub_result[0], $txtCurr, insertMySQLDate($txtDate), $txtSaBonusAmt, $connection);	
	
	$query = " UPDATE temp_sales SET Currency_Code = '".$txtCurr."' WHERE Sale_ID = $SSaId ";
	$result=mysql_query($query,$connection);
	
	//echo $query; exit;

		
	//Update Detail Amount Columns
	$sub_query = " Select SaleDt_Id, Currency_Code, ifNull(SaleDt_Price,0), ifNull(SaleDt_PriceBase1,0), ifNull(SaleDt_PriceBase2,0), ".
				 " ifNull(SaleDt_PriceTTC,0), ifNull(SaleDt_PriceTTCBase1,0), ifNull(SaleDt_PriceTTCBase2,0), ifNull(SaleDt_DiscountAmount,0), ".
				 " ifNull(SaleDt_DiscountBase1,0), ifNull(SaleDt_DiscountBase2,0), ifNull(SaleDt_TransportAmount,0), ifNull(SaleDt_BonusAmount,0) ".
				 " From temp_salesdt ".
				 " Where Sale_ID = ".$SSaId;
	$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];
		$vSaDtBonAmt   	    = $sub_row[12];
			
				
		$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);
		$vSaDtBonAmt   = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSaDtBonAmt, $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);
		$vSaDtBonAmtB1      = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $vSaDtBonAmt, $connection);
		$vSaDtBonAmtB2      = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $vSaDtBonAmt, $connection);
		
		$sub_query1 = " UPDATE temp_salesdt SET  ".
					  " Currency_Code = '".$txtCurr."', ".
					  " SaleDt_Price = $vSaDtPrice, SaleDt_PriceBase1 = $vSaDtPriceBase1, SaleDt_PriceBase2 = $vSaDtPriceBase2, ".
					  " SaleDt_PriceTTC = $vSaDtPriceTTC, SaleDt_PriceTTCBase1 = $vSaDtPriceTTCBase1, SaleDt_PriceTTCBase2 = $vSaDtPriceTTCBase2, ".
					  " SaleDt_DiscountAmount = $vSaDtDiscAmt, SaleDt_DiscountBase1 = $vSaDtDiscAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscAmtBase2, ".
					  " SaleDt_TransportAmount = $vSaDtTrsAmt, SaleDt_TransportBase1 = $vSaDtTrsAmtB1, SaleDt_TransportBase2 = $vSaDtTrsAmtB2, ".
					  " SaleDt_BonusAmount = $vSaDtBonAmt, SaleDt_BonusBase1 = $vSaDtBonAmtB1, SaleDt_BonusBase2 = $vSaDtBonAmtB2 ".
					  " Where SaleDt_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($SSaId, $txtDate, $SSaVatChkbx, $txtSaDiscount, $txtSaDiscountAmt, $txtSaTransportAmt, $txtSaBonusAmt, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$SaWHTChkbx,$SaWHTPer, 'I', $connection);
	$message  = $message . $CalculateResult;

	
		
}

//Adding Invoice Discount
else if($mode == "changediscount" && $SSaId != ''){ 
	if (empty($txtSaDiscountAmt))	$txtSaDiscountAmt = 0;
	if (empty($txtSaDiscount))		$txtSaDiscount = 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_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
				  " From Temp_SalesDt ".
				  " Where Sale_ID = ".$SSaId;
	$sub_result3 = selectData($connection, $sub_query3);
	$vSaTotal   = $sub_result3[0];	
		
	if ($SalesTTC == 1) {
		$vSaDisAmt	= ($txtSaDiscountAmt  / (1 + $Setup_VatPercentage/100));
	} else {
		$vSaDisAmt	= $txtSaDiscountAmt;
	}	
			
	$sub_query4 = " Select SaleDt_ID,  ".
				  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
				  " From Temp_SalesDt As SalesDt  ".
				  " Where SalesDt.Sale_ID = ".$SSaId;
					   
	//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];
				
		$vSaDtDiscAmt	   = 0;
		$vSaDtDiscAmt 	   = ($vSaDtTotal/$vSaTotal)*$vSaDisAmt;
		$vSaDtDiscAmtBase1 = ($vSaDtDiscAmt*$vRate)/$vRateB1;
		$vSaDtDiscAmtBase2 = ($vSaDtDiscAmt*$vRate)/$vRateB2;
			
		$queryupd =  " UPDATE temp_salesdt SET SaleDt_DiscountAmount = $vSaDtDiscAmt, SaleDt_DiscountBase1 = $vSaDtDiscAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscAmtBase2  ".
					 " Where SaleDt_ID = ".$vSaDtId;
		//echo $queryupd; exit;
		if (!updateData($connection, $queryupd, true))
			$error  = mysql_error(); 
				
	
	}
			
			
	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($SSaId, $txtDate, $SSaVatChkbx, $txtSaDiscount, $txtSaDiscountAmt, 0, 0, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$SaWHTChkbx,$SaWHTPer, 'I', $connection);
	$message  = $message . $CalculateResult;

}

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

	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];
	
	
	
	if (empty($txtSaDiscountAmt))
		$txtSaDiscountAmt = 0;
	if (empty($txtSaDiscount))
		$txtSaDiscount = 0;
	if (empty($txtSaTransportAmt))
		$txtSaTransportAmt = 0;	
	if (empty($txtSaBonusAmt))
		$txtSaBonusAmt = 0;		
	if (empty($PSaVatChkbx))
		$PSaVatChkbx = 0;	
	if (empty($SaWHTChkbx))
		$SaWHTChkbx = 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))."'";		
	
	
		
		
		//echo $grnno."dfsf";
	$vSaRef = '';
	$vSaTaxable = 0;
	$vSaTaxableTTC  = 0;
	$vSaNoneTaxable = 0;
	$vSaGrossTotal = 0;
	$vSaDiscountAmt = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaDiscountPer = 0;
	$vSaVat = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
	$vSaTotalTax = 0;
	$vSaTotal = 0;
	$vSaDisAmt = 0;
	$vSaTrsAmt = 0;
	$vSaBonAmt = 0;
	
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaBonusAmt   	   = 0;
	$vSaBonusAmtB1	   = 0;
	$vSaBonusAmtB2	   = 0;
	
	$vSaDtTrsAmt    = 0;
	$vSaDtTrsAmtB1  = 0;
	$vSaDtTrsAmtB2  = 0;
	$vSaDtBonAmt    = 0;
	$vSaDtBonAmtB1  = 0;
	$vSaDtBonAmtB2  = 0;
	
		
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;
	$vSaDtDiscAmt       = 0;
	$vSaDtDiscAmtBase1  = 0;
	$vSaDtDiscAmtBase2  = 0;
	$vSaDtItemTax1      = 0;
	$vSaDtItemTax2      = 0;
	$vSaDtItemTax3      = 0;
	$vSaDtItemTax4      = 0;
	$vSaDtItemTax5      = 0;
	
	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	$ExceedCreditLimit = 0;
	

	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_salesdt ".
				 " Where Sale_ID = '".$SSaId."' ".
				 " 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(SaleDt_Quantity,0)) As SaleDtQuantity ".
								  " From temp_salesdt ".
								  " Where Sale_ID = '".$SSaId."' ".
								  " 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 Price Before Insert
	if($module_Checkzerosales==1){
		$sub_query = " Select 1  ".
					 " From Temp_SalesDt As SalesDt  ".
					 " Where SalesDt.Sale_ID = ".$SSaId." And SaleDt_Price = 0";
						  
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] != 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Price 0.';
		}
	}
	
	//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.';
		}
	}
	if ($txtClientDtCode != '') {
		$sub_query = " Select Count(Detail_Code) From ClientsDetail ".
					 " Where Detail_Code = '".$txtClientDtCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Detail Client Code.';
		}
	}
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select SalesDt.SaleDt_ID, SalesDt.Item_code, ifNull(SaleDt_Quantity,0) as SaleDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_SalesDt As SalesDt Left Join Items on SalesDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on SalesDt.SaleDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'SI' ".
					 " 	And Temp_Purchasesserialno.SaleDt_ID Is Not Null ".
					 " 	Where SalesDt.Sale_ID = ".$SSaId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By SalesDt.SaleDt_ID ".
					 " 	Having ifNull(SaleDt_Quantity,0) != CountSerialNo ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0 && $module_serialnoout == 0 ) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Serials.';
		}		 
	}
	
	if ($ErrorExists == 0) {
		$sub_query = " Select ifNull(Sale_Mode,0), ifNull(Sale_CashInBase1,0), ifNull(Sale_CashInBase2,0) From Temp_Sales Where Sale_ID = ".$SSaId;
		$sub_result = selectData($connection, $sub_query);
		$vSaleMode 	   = $sub_result[0];
		$vSaleCashInB1 = $sub_result[1];
		$vSaleCashInB2 = $sub_result[2];
		
		if ($vSaleMode == 1 && $vSaleCashInB1 == 0 && $vSaleCashInB2 == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Payment mode is cash, please fill in Cash Amounts.';
		}
	
	}
	
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

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

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;
	
	$SaveAllowed = checkcashdiff('Sales',$SSaId,$txtCurr,$base1,$base2,$connection);
	
	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
	
	
		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select SaleDt_id, Currency_Code, ifNull(SaleDt_Price,0), ifNull(SaleDt_PriceBase1,0), ifNull(SaleDt_PriceBase2,0), ".
					 " ifNull(SaleDt_PriceTTC,0), ifNull(SaleDt_PriceTTCBase1,0), ifNull(SaleDt_PriceTTCBase2,0), ifNull(SaleDt_DiscountAmount,0), ".
					 " ifNull(SaleDt_DiscountBase1,0), ifNull(SaleDt_DiscountBase2,0),item_Code ".
					 " From temp_salesdt ".
					 " Where Sale_ID = ".$SSaId;	
		$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_salesdt SET  ".
							  " SaleDt_Price = $vSaDtPrice, SaleDt_PriceBase1 = $vSaDtPriceBase1, SaleDt_PriceBase2 = $vSaDtPriceBase2, ".
							  " SaleDt_PriceTTC = $vSaDtPriceTTC, SaleDt_PriceTTCBase1 = $vSaDtPriceTTCBase1, SaleDt_PriceTTCBase2 = $vSaDtPriceTTCBase2, ".
							  " SaleDt_DiscountAmount = $vSaDtDiscAmt, SaleDt_DiscountBase1 = $vSaDtDiscAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscAmtBase2 ".
							  " Where SaleDt_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];
			
			
			
			// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, ".
						 " CreditAccountNonStock, CreditAccountVatNonStock, 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];
						
				$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$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_export ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " 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];
				
				$vSaVatChkbx= $txtSaVatChk;	
				
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					

					if ($item_vat > 0 && $vSaVatChkbx == 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 ($item_vat > 0 && $vSaVatChkbx == 1) {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
					} else {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
						else	
							$vSaDtItemAcc = $vSaStpCreditAcc;
					}

				 
	
				}
				
				if($clientexp == 1) $vSaDtItemAcc = $result[11]; 
				
				$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				$sub_query1 = " Update temp_deliverydt SET ".
						 " Saledt_DirectStkDbt = '".$vSaDtDirectStkDbt."', Saledt_DirectStkCrd = '".$vSaDtDirectStkCrd."', ".
						 " Saledt_DirectStkCur = '".$vSaDtDirectStkCur."', SaleDt_DiscountAcc = '".$vSaDtDiscAcc."', ".
						 " SaleDt_ItemAccount = '".$vSaDtItemAcc."', SaleDt_VatAccount = '".$vSaDtVatAcc."'  ".
						 " Where DeliveryDt_ID = ".$sub_row[0];
				
	 			if (!updateData($connection, $sub_query1, true)){		 
					$message  = mysql_error(); 
				}	
					
		}  //End Loop of SalesDt Query
		
		
		
		
		
		
		$sub_query2 = " UPDATE temp_salesdt SET ".
					  " Currency_Code = '".$txtCurr."', Sale_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.", CostCenter_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Sale_id = $SSaId ";
		
		//echo $querydt."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
					  
		if ($Module_ProjectDt == 1) {
			$querydt = " UPDATE temp_salesdt SET Project_Code = $ProjectCode ".
					   " WHERE Sale_id = $SSaId ".
					   " AND (Project_Code is null or Project_Code = '') ";
			$resultdt=mysql_query($querydt,$connection);
		}
		if ($Module_CostCenterDt == 1) {
			$querydt = " UPDATE temp_salesdt SET CostCenter_Code = $CostCentCode ".
					   " WHERE Sale_id = $SSaId ".
					   " AND (CostCenter_Code is null or CostCenter_Code = '') ";
			$resultdt=mysql_query($querydt,$connection);
		}
		
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_SalesDt ".
					  " Where Sale_ID = ".$SSaId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vSaTotal   = $sub_result3[0];	
		
		
		
		if ($SalesTTC == 1) {
			$vSaDisAmt	= ($txtSaDiscountAmt  / (1 + $Setup_VatPercentage/100));
			$vSaTrsAmt  = ($txtSaTransportAmt / (1 + $Setup_VatPercentage/100));
			$vSaBonAmt  = ($txtSaBonusAmt     / (1 + $Setup_VatPercentage/100));
		} else {
			$vSaDisAmt	= $txtSaDiscountAmt;
			$vSaTrsAmt  = $txtSaTransportAmt;
			$vSaBonAmt  = $txtSaBonusAmt;
		}	
			
		$sub_query4 = " Select SaleDt_ID,  ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
					  " ifNull(SaleDt_Quantity,0), ifNull(SaleDt_Price,0), ifNull(SaleDt_PriceBase1,0), ifNull(SaleDt_PriceBase2,0), ifNull(SaleDt_DiscountPer,0), RelatedDt_Id, SalesDt.Currency_Code, ".
					  " ifnull(SaleDt_DiscountAmount,0) ".
					  " From Temp_SalesDt As SalesDt  ".
					  " Where SalesDt.Sale_ID = ".$SSaId;
						  
					   
		//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];
			$vRelatedDtID = $sub_rows4[7];
			$vSaCurrCode  = $sub_rows4[8];
				
				
			$vSaDtDiscAmt	   = 0;
			if($show_discountAmount == 1)
			$vSaDtDiscAmt 	   = $sub_rows4[9];
			else	
			$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;
				
			$vSaDtBonAmt    = 0;
			$vSaDtBonAmt    = ($vSaDtTotal/$vSaTotal)*$vSaBonAmt;
			$vSaDtBonAmtB1  = ($vSaDtBonAmt*$rate_dt)/$rate_dt1;
			$vSaDtBonAmtB2  = ($vSaDtBonAmt*$rate_dt)/$rate_dt2;	
				
			$queryupd =  " UPDATE temp_salesdt SET SaleDt_DiscountAmount = $vSaDtDiscAmt, SaleDt_DiscountBase1 = $vSaDtDiscAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscAmtBase2,  ".
						 " SaleDt_TransportAmount = $vSaDtTrsAmt, SaleDt_TransportBase1 = $vSaDtTrsAmtB1, SaleDt_TransportBase2 = $vSaDtTrsAmtB2, ".
						 " SaleDt_BonusAmount = $vSaDtBonAmt, SaleDt_BonusBase1 = $vSaDtBonAmtB1, SaleDt_BonusBase2 = $vSaDtBonAmtB2 ".
						 " Where SaleDt_ID = ".$vSaDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
				
				
			$vSaDtSalePrice    = 0;
			$vSaDtSalePriceB1  = 0;
			$vSaDtSalePriceB2  = 0;
				
			if ($vSaDtQty > 0) {
				$vSaDtSalePrice    = $vSaDtPrice   - ($vSaDtPrice*$vSaDtDiscPer/100)   - ($vSaDtDiscAmt/$vSaDtQty)      - ($vSaDtTrsAmt/$vSaDtQty)   - ($vSaDtBonAmt/$vSaDtQty);
				$vSaDtSalePriceB1  = $vSaDtPriceB1 - ($vSaDtPriceB1*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase1/$vSaDtQty) - ($vSaDtTrsAmtB1/$vSaDtQty) - ($vSaDtBonAmtB1/$vSaDtQty);
				$vSaDtSalePriceB2  = $vSaDtPriceB2 - ($vSaDtPriceB2*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase2/$vSaDtQty) - ($vSaDtTrsAmtB2/$vSaDtQty) - ($vSaDtBonAmtB2/$vSaDtQty);
			}
				
			$queryupd =  " UPDATE deliverydt SET ".
						 " Currency_Code = '".$vSaCurrCode."', SaleDt_Price = $vSaDtSalePrice, SaleDt_PriceBase1 = $vSaDtSalePriceB1, SaleDt_PriceBase2 = $vSaDtSalePriceB2 ".
						 " Where DeliveryDt_ID = '".$vRelatedDtID."'";
			
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
				

		}

		//Update Serials ExpireDate and BatchNo From Detail Table
		if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
			$sub_query5 = " Select SaleDt_Id, SaleDt_ExpireDate, SaleDt_BatchNo ".
						  " From Temp_SalesDt As SalesDt  ".
						  " Where SalesDt.Sale_ID = ".$SSaId;
							  
			//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 = 'SI' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
				
			}
		}	
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SSaId, $txtDate, $SSaVatChkbx, $txtSaDiscount, $txtSaDiscountAmt, $txtSaTransportAmt, $txtSaBonusAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$SaWHTChkbx,$SaWHTPer, 'P', $connection);
		$message  = $message . $CalculateResult;
						  
		if ($Module_InvoiceCheckLimit == 1) {
		
			$query = " Select ifNull(Sale_Mode,0) From Temp_Sales Where Sale_ID = ".$SSaId;
			$result = selectData($connection, $query);
			$vCashMode = $result[0];

			// Calculation of Tax Amounts
			$query = " SELECT Client_Tax1, Client_Tax2, Client_Tax3, Client_Tax4, Client_Tax5, Client_CreditLimit, ".
					 " Client_PaymentTerms, Client_CashMode, Clients.Currency_Code ".
					 " FROM Clients ".
					 " WHERE Ledger_number = '".$txtClientCode."'";
			
			$result = selectData($connection, $query);
			$vCltTax1 = $result[0];
			$vCltTax2 = $result[1];
			$vCltTax3 = $result[2];
			$vCltTax4 = $result[3];
			$vCltTax5 = $result[4];
			$vCltCreditLimit = $result[5];
			$vCltPaymentTerm = $result[6];
			$vCltCashMode    = $result[7];
			$vCltCurrCode    = $result[8];
			
			// Checking For Client Credit Limit
			$ExceedCreditLimit = 0;
			$vCltCreditLimit   = ConvertCurrency($vCltCurrCode, $txtCurr, insertMySQLDate($txtDate), $vCltCreditLimit, $connection);

			if ($vCltCashMode == "1" || $vCashMode == 1){
				$ExceedCreditLimit = 0;
			}else{ 
				if ($FA_ClientCreditLimit == 1) {
					$ExceedCreditLimit = 0;
				} else { 
					if ($FA_ClientCreditLimit == 0 && $Module_CreditLimit == 1){ 
						$query_sales  = " Select Journal_ID From Temp_Sales Where Sale_id = $SSaId ";
						$result_sales = selectData($connection, $query_sales);
						$vSaJournalID = $result_sales[0];
						if(empty($vSaJournalID)) $vSaJournalID = -1;
						
						//Get Current Balance
						$querybalance = " SELECT IFNULL(SUM(if(journaldt_dbcd = 'D', ifNull(journaldt_amount1,0), (-1)*ifNull(journaldt_amount1,0))), 0) As Balance FROM journaldt ".
										" where journaldt.journal_id != ".$vSaJournalID." and ledger_number = '".$txtClientCode."' ".
										" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate($txtDate)."','%Y%m%d') ";
										
						//echo "<br><br>".$querybalance; exit;
						$resultbalance = selectData($connection, $querybalance);
						$q1 = $resultbalance[0];
						$q1 = ConvertCurrency($base1, $txtCurr, insertMySQLDate($txtDate), $q1, $connection);
						
						$sub_query = " Select Round((ifNull(Sale_Total,0) + IfNull(Sale_VAT,0) + ifNull(Sale_TransportAmount,0) + ifNull(Sale_BonusAmount,0) - IfNull(Sale_DiscountAmount,0)), ".$DecimalBase.") As Sale_NetTotal ".
									 " From Temp_Sales ".
									 " Where Sale_ID = ".$SSaId;
						$sub_result = selectData($connection, $sub_query);
						$q2 = $sub_result[0];
						
						
						//if ($vCltCreditLimit >= ($q1 + $q2)){
						if (($vCltCreditLimit - ($q1 + $q2)) > -3){
							$ExceedCreditLimit = 0;
						} else{
							$message = "Save not allowed. Exceed credit limit. Balance (Previous: ".number_format($q1, $DecimalBase)."  Current: ".number_format($q2, $DecimalBase)."  Total: ".number_format(($q1 + $q2), $DecimalBase)." )";
							$ExceedCreditLimit = 1;
						}
							
					} else
						$ExceedCreditLimit = 0;
										
				}	
			}
		}					
				

		//Check If Client Is Changed ==> Change VAT Accounts
		$sub_query7 = " Select Client_Code From Temp_Sales Where Sale_ID = '".$SSaId."'";
		$sub_result7 = selectData($connection, $sub_query7);
		$vPreClientCode = $sub_result7[0];
		
		if ($vPreClientCode != trim($txtClientCode)) {
			$Acc_Query = " SELECT VatAccount FROM salessetup ";
			$Acc_Result = selectData($connection, $Acc_Query);
			
			$vSaVatAcc = $Acc_Result[0];
			$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			
			$query = " UPDATE temp_sales SET ".
					 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', Sale_VatAccount = '".$vSaVatAcc."' ".
					 " WHERE Sale_id = '".$SSaId."' ";
			$result=mysql_query($query,$connection);
			
			
				//In Case Edit, If Invoice Client Is Changed, Then Change Delivery and SalesOrder Client
		if ($Module_ChangeInvoiceClient == 1 && $FI_ChangeInvoiceClient == 1) {
			$sub_query = " Select Client_Code From Sales Where Sale_ID = ".$SSaId;
			$sub_result = selectData($connection, $sub_query);
			$vExistClientCode = $sub_result[0];
			//echo $vExistClientCode." ".$txtClientCode;
			//exit;
			if ($vExistClientCode != "" && $vExistClientCode != $txtClientCode) {
				$sub_query = " Select Distinct Delivery_Id From DeliveryDt ".
							 " Where Deliverydt_Id IN (Select RelatedDt_Id From Temp_SalesDt Where Sale_Id = ".$SSaId.") ".
							 " And Journal_Type = 'DI' ";
							 
				$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
				while($sub_row=mysql_fetch_array($sub_result)){
					$sub_query1 = " UPDATE Deliveries SET  ".
								  " Client_Code = '".$txtClientCode."', Salesman_Code = $SalesmanCode ".
								 
								 " Where Delivery_Id = ".$sub_row[0];
						
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 
						
					$sub_query1 = " UPDATE DeliveryDt SET  ".
								  " Client_Code = '".$txtClientCode."' , Deliverydt_VatAccount = '".$vSaVatAcc."' ".
								  " Where Delivery_Id = ".$sub_row[0];
						
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 	
				
				}
				
				
				$sub_query = " Select Distinct Sorder_Id ".
							 " From SorderDt Inner Join DeliveryDt on DeliveryDt.RelatedDt_Id = SorderDt.SorderDt_Id ".
							 " Where DeliveryDt.Deliverydt_Id IN (Select RelatedDt_Id From Temp_SalesDt Where Sale_Id = ".$SSaId.") ".
							 " And DeliveryDt.Journal_Type = 'DI' ";
				$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
				while($sub_row=mysql_fetch_array($sub_result)){
					$sub_query1 = " UPDATE Sorder SET  ".
								  " Client_Code = '".$txtClientCode."' ".
								  " Where Sorder_Id = ".$sub_row[0];
						
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 
						
					$sub_query1 = " UPDATE SorderDt SET  ".
								  " Client_Code = '".$txtClientCode."' ".
								  " Where Sorder_Id = ".$sub_row[0];
						
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 	
				
				}
			}
		
		}
			
			
			
			$sub_query7 = " Select SaleDt_ID, SalesDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0) ".
						  " From Temp_SalesDt as SalesDt ".
						  " Inner Join Items on SalesDt.Item_Code = Items.Item_Code ".
						  " Where Sale_ID = '".$SSaId."'";
						  
			$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_salesdt SET ".
						 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', SaleDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " WHERE SaleDt_id = '".$sub_rows7[0]."' ";
				$result=mysql_query($query,$connection);
			
			}
			
		}
		
		if (empty($txtVehicleWeight))   $txtVehicleWeight = 0;
		if (empty($txtVehicleLoadWeight))   $txtVehicleLoadWeight = 0;
		if (empty($txtVehicleRealWeight))   $txtVehicleRealWeight = 0;
		
		$query = " UPDATE temp_sales SET ".
				 //" Sale_Reference = $vSaRef, ".
				 " Sale_Date = '".insertMySQLDate($txtDate)."', ".
				 " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."', ".
				 " Sale_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 //" Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
				 " Salesman_Code = $SalesmanCode, Sale_ShippedTo = '".ereg_replace("'", "\'", trim($txtIAddress))."', ".
				 " Sale_Marks = '".ereg_replace("'", "\'", trim($txtVehicleNumber))."', Sale_ShippedVia = '".ereg_replace("'", "\'", trim($txtDriverName))."', ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcenter_code = $CostCentCode,  ".
				 " Sale_chkvat = $SSaVatChkbx, Sale_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."' ".
				 ", Sale_vehicleweight = $txtVehicleWeight ".
				 ", Sale_vehicleLoadweight = $txtVehicleLoadWeight ".
				 ", Sale_vehicleRealweight = $txtVehicleRealWeight ".
				 " WHERE Sale_id = $SSaId ";
				//" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
		
		if ($ExceedCreditLimit == 0) {	
			if ($result){
				//fcommit();
						
				if ($mainmode == 'insert') $SMode = 'I';
				if ($mainmode == 'edit') $SMode = 'U';
				//echo $SMode;exit;
				
				$vOldProjCode  	= '';
				$vOldCostCentCode = '';
				// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
				$query   = " SELECT Project_Code, Costcenter_code  FROM Sales WHERE Sale_id = $SSaId ";
				$result  = selectData($connection, $query);
				$vOldProjCode     = $result[0];
				$vOldCostCentCode = $result[1];
				
				$query = "Select Count(*) From Temp_Sales where Sale_ID = '".$SSaId."'";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$ExistInTemp = $result[0];	
				
				$query_checkDelivery  = "select count(*) as SaleExist from sales where sale_id = '$SSaId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($SaleExist > 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_TempSales('SI', ".$SSaId.", '".$_SESSION['useraccount']."') FROM Dual ";//echo $query; exit;
					$result = selectData($connection, $query);
					$result = $result[0];
					//echo $query; exit;
					//echo 'error='.$result; exit;
					if ($result != 0){ 
						fcommit();
						
						$query   = " SELECT Sale_Reference, Costcenter_code, Project_Code, ifNull(Sale_Mode,0) FROM Sales WHERE Sale_id = $SSaId ";
						$result  = selectData($connection, $query);
						$vSaRef  = $result[0];
						$vCostCentCode = $result[1];
						$vProjectCode  = $result[2];
						$vSaleMode     = $result[3];
						
						if ($vSaRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1) ||
							($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1)) {
							
							if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
							else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
							else $vProjCostCent = '';
							
							fbegin();
							$vSaRef = get_nextsequence('sales_reference',$vProjCostCent,$connection);	
							fcommit();
							
							$query = " UPDATE sales SET ".
									 " Sale_Reference = $vSaRef ".
									 " WHERE Sale_id = $SSaId ";
							
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error();
						
						}	

						if ($Module_PostToJournal == 1)	{
							$message = Create_SalesJv($SSaId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
						}
						
						//If Cash Payment Then Allocate Invoice In Acclink
						if ($vSaleMode == 1 && $message == '') {
							$message = CashPaymentInvoice($SSaId, 'I', $Module_Delivery, $_SESSION['useraccount'], $_SESSION['dbLabel'], $_SESSION['dbName'], $connection);
						}
						if($Module_ChangeInvoiceItems == 1 && $FI_ChangeInvoiceItems == 1)	{
							$query = "select RelatedDt_Id,Item_code, Warehouse_Code from salesdt where sale_id=$SSaId;";
							$res = mysql_query($query,$connection);
							while($rw=mysql_fetch_row($res)){
								if($rw[0] != '' && $rw[0] != 0){
									$querydt = "update deliverydt set Item_code = '$rw[1]', Warehouse_Code = '$rw[2]'  where DeliveryDt_id = $rw[0];";
									$resdt = mysql_query($querydt,$connection);
									$query2 = "select ifnull(RelatedDt_Id,0) from deliverydt where DeliveryDt_id = $rw[0];";
									$res2 = mysql_query($query2,$connection);
									$rw2 = mysql_fetch_row($res2);
									if($rw2[0] != 0){
										$querydt2 = "update sorderdt set Item_code = '$rw[1]', Warehouse_Code = '$rw[2]' where sorderdt_id=$rw2[0];";
										$qresdt2 =mysql_query($querydt2,$connection);
									}
								}
							}
						}
						if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'sales', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
					} 
					
					else{
						$ErrorExists = 1;
						//$message  = "Error: ".mysql_error($connection); 
						$message  = 'Error In CopyData_TempSales Function'; 
						frollback();
					}
				
				} 
			} else{
				$message  = mysql_error(); 
				frollback();
			}
		} else{
			//$message = "Save not allowed. Exceed credit limit.";
			frollback();
		}	
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllowed == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else	
		if ($SaveAllowed == 3) 
			$message  = 'Save not allowed. Net Total And Cash Differs.'; 
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';
		
		frollback();
	}	
}


$message          = ereg_replace(' ','%20',$message);
$WarningMsg       = ereg_replace(' ','%20',$WarningMsg);
$PSaRemark        = ereg_replace(' ','%20',$PSaRemark);
$PSaIAddress      = ereg_replace(' ','%20',$PSaIAddress);
$PSaDriverName    = ereg_replace(' ','%20',$PSaDriverName);
$PSaVehicleNumber = ereg_replace(' ','%20',$PSaVehicleNumber);

$PSaRemark        = ereg_replace('#','%23',$PSaRemark);
$PSaIAddress      = ereg_replace('#','%23',$PSaIAddress);
$PSaDriverName    = ereg_replace('#','%23',$PSaDriverName);
$PSaVehicleNumber = ereg_replace('#','%23',$PSaVehicleNumber);

$PSaRemark        = ereg_replace('&','%26',$PSaRemark);
$PSaIAddress      = ereg_replace('&','%26',$PSaIAddress);
$PSaDriverName    = ereg_replace('&','%26',$PSaDriverName);
$PSaVehicleNumber = ereg_replace('&','%26',$PSaVehicleNumber);


//echo $mode.$message; exit;

if($mode == "post") {
	if ($ExceedCreditLimit == 0 && $SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Sales.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSaId=".$SSaId."&PrSaRef=".$vSaRef);
	else
		header ("Location: ./Form_Sales.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_SalesSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_SalesSearchPending.php?message=".$message);
else if ($mode == "cancel" )		
	header ("Location: ./Form_Sales.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_Sales.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_SalesDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PSaId=".$SSaId."&PSaDate=".$PSaDate."&PSaDtId=".$SSaDtId);		
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_SalesSearch.php?PMode=1&message=".$message);	
else if ($mode == "CashPayment") { 
	if ($message != "")
		header ("Location: ./Form_Sales_PayCash.php?PMode=0&PSaId=".$SSaId."&message=".$message);
	else
		header ("Location: ./Form_Sales_PayCash.php?PMode=1&PSaId=".$SSaId."&message=".$message);
}	
else if ($mode == "CreditPayment") { 
	header ("Location: ./Form_Sales.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
}
else if ($mode == "changecurrency")	
	header ("Location: ./Form_Sales.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
else if ($mode == "changediscount")	
	header ("Location: ./Form_Sales.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
else if ($mode == "" && $mainmode == "loaddelivery" ) {		
	if ($message != "")
		header ("Location: ./Form_Sales_LoadDelivery.php?PMode=0&PSaId=".$SSaId."&message=".$message);			
	else	
		header ("Location: ./Form_Sales_LoadDelivery.php?PMode=1&PSaId=".$SSaId."&message=".$message);
}	


$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SSaId;
		
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);
	
	Return	$result[0];

}

function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PBonusAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC,$PWHTChk,$PWHTPer, $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;
	$vSaTransportAmtTTC = 0;
	$vSaBonusAmt   	    = 0;
	$vSaBonusAmtB1      = 0;
	$vSaBonusAmtB2      = 0;
	$vSaBonusAmtTTC     = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
	
	$vSaWHT      = 0;
	$vSaWHTBase1 = 0;
	$vSaWHTBase2 = 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;
	
	if($PWHTChk == '') $PWHTChk = 0;
	
	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_SalesDt SET  ".
				 " SaleDt_Price = SaleDt_PriceTTC, ".
				 " SaleDt_PriceBase1 = SaleDt_PriceTTCBase1, ".
				 " SaleDt_PriceBase2 = SaleDt_PriceTTCBase2 ".
				 " Where Sale_ID = ".$PId;

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

		$query = " UPDATE Temp_SalesDt SET  ".
				 " SaleDt_Price      = (SaleDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " SaleDt_PriceBase1 = (SaleDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " SaleDt_PriceBase2 = (SaleDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Sale_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0), ".
				 " SaleDt_Quantity, (ifNull(SaleDt_DiscountAmount,0) - ifNull(SaleDt_TransportAmount,0) - ifNull(SaleDt_BonusAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_SalesDt ".
				 " Where Sale_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;
	
	
	
	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));
			}	
		}
		
		$vSaTransportAmtTTC = $PTransportAmt;					
		$vSaTransportAmt    = ($vSaTransportAmtTTC / (1 + $PSetupVatPercentage/100));
		$vSaBonusAmtTTC 	= $PBonusAmt;					
		$vSaBonusAmt    	= ($vSaBonusAmtTTC / (1 + $PSetupVatPercentage/100));
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
			$vSaDiscountAmtTTC   = 0;
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
			
			$vSaDiscountAmtTTC   = 0;
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
	}		
					
	$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;
	$vSaTransportAmtB1   = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2   = ($vSaTransportAmt*$PRate)/$PRate2;	
	$vSaBonusAmtB1 	     = ($vSaBonusAmt*$PRate)/$PRate1;
	$vSaBonusAmtB2	     = ($vSaBonusAmt*$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;	
	
	
	if($PWHTChk == 1) {
		if($PSalesTTC == 1) 
			$vSaWHT      = ((($vSaTaxableTTC + $vSaNoneTaxable) - $vSaVat)*$PWHTPer/100); 
		else 
			$vSaWHT      = (($vSaTaxable + $vSaNoneTaxable)*$PWHTPer/100); 
		$vSaWHTBase1 = ($vSaWHT*$PRate)/$PRate1;
		$vSaWHTBase2 = ($vSaWHT*$PRate)/$PRate2;
	} else {
		$vSaWHT      = 0;
		$vSaWHTBase1 = 0;
		$vSaWHTBase2 = 0;
		
	}	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_sales SET ".
				  " Sale_Taxable = $vSaTaxable, Sale_TaxableBase1 = $vSaTaxableBase1, Sale_TaxableBase2 = $vSaTaxableBase2, ".
				  " Sale_NoneTaxable = $vSaNoneTaxable, Sale_NoneTaxableBase1 = $vSaNoneTaxableBase1, Sale_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Sale_DiscountAmount = $vSaDiscountAmt, Sale_DiscountBase1 = $vSaDiscountAmtBase1, Sale_DiscountBase2 = $vSaDiscountAmtBase2, ";
				  
	//if ($PTransportAmt > 0)			  
		$sub_query1 = $sub_query1." Sale_TransportAmount = $vSaTransportAmt, Sale_TransportBase1 = $vSaTransportAmtB1, Sale_TransportBase2 = $vSaTransportAmtB2, Sale_TransportTTC = $vSaTransportAmtTTC, ";
	//if ($PBonusAmt > 0)	
		$sub_query1 = $sub_query1." Sale_BonusAmount = $vSaBonusAmt, Sale_BonusBase1 = $vSaBonusAmtB1, Sale_BonusBase2 = $vSaBonusAmtB2, Sale_BonusTTC = $vSaBonusAmtTTC, ";
	
	
	$sub_query1 = $sub_query1.
				  " Sale_DiscountPer = $vSaDiscountPer, Sale_VAT = $vSaVat, Sale_VATBase1 = $vSaVatBase1, Sale_VATBase2 = $vSaVatBase2, ".
				  " Sale_Total = $vSaGrossTotal, Sale_TotalBase1 = $vSaGrossTotalBase1, Sale_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Sale_DiscountTTC = $vSaDiscountAmtTTC, Sale_TaxableTTC = $vSaTaxableTTC,  ".
				  " Sale_Tax1 = $vSaTax1, Sale_Tax1Base1 = $vSaTax1B1,   Sale_Tax1Base2 = $vSaTax1B2,  ".
				  " Sale_Tax2 = $vSaTax2, Sale_Tax2Base1 = $vSaTax2B1,   Sale_Tax2Base2 = $vSaTax2B2,  ".
				  " Sale_Tax3 = $vSaTax3, Sale_Tax3Base1 = $vSaTax3B1,   Sale_Tax3Base2 = $vSaTax3B2,  ".
				  " Sale_Tax4 = $vSaTax4, Sale_Tax4Base1 = $vSaTax4B1,   Sale_Tax4Base2 = $vSaTax4B2,  ".
				  " Sale_Tax5 = $vSaTax5, Sale_Tax5Base1 = $vSaTax5B1,   Sale_Tax5Base2 = $vSaTax5B2,  ".
				  " Sale_WHTchecked = $PWHTChk, Sale_WHTAmount = $vSaWHT, Sale_WHTAmountBase1 = $vSaWHTBase1, Sale_WHTAmountBase2 = $vSaWHTBase2 ".
				  " WHERE Sale_ID = ".$PId;
	//echo $sub_query1."<br>";exit;				 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


function Distribute_TotalDiscount($PSaId, $PRate, $PRate1, $PRate2, $connection, $PLoggedCode) {
	
	$vSaDtId      = 0;
	$vSaDtTotal   = 0;
	$vSaDtQty     = 0;
	$vSaDtPrice   = 0;
	$vSaDtPriceB1 = 0;
	$vSaDtPriceB2 = 0;
	$vSaDtDiscPer = 0;
	$vSaDtTrsAmt  = 0;
	$vSaDtTrsAmtB1     = 0;
	$vSaDtTrsAmtB2     = 0;
	$vSaDtSalePrice    = 0;
	$vSaDtSalePriceB1  = 0;
	$vSaDtSalePriceB2  = 0;
		
				 
	$querytotal = " Select Sale_ID, Sales.Currency_code, (ifNull(Sale_Taxable,0) + ifNull(Sale_NoneTaxable,0)) As Sale_Total, Sale_DiscountAmount ".
				  " From Temp_Sales As Sales  ".
				  " Where Sale_ID = ".$PSaId;
				  //" And Logged_Code = '".$PLoggedCode."' ";
		
	
	$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
	$rowstotal=mysql_fetch_array($resulttotal);
	
	$vSaTotal   = $rowstotal[2];
	$vSaDisAmt  = $rowstotal[3];
	
	$query = " Select SaleDt_ID,  ".
             " ((SaleDt_Quantity*SaleDt_Price)-((SaleDt_Quantity*SaleDt_Price*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
			 " ifNull(SaleDt_Quantity,0), ifNull(SaleDt_Price,0), ifNull(SaleDt_PriceBase1,0), ifNull(SaleDt_PriceBase2,0), ".
			 " ifNull(SaleDt_DiscountPer,0) ".
         	 " From Temp_SalesDt As SalesDt  ".
			 " Where SalesDt.Sale_ID = ".$PSaId;
			 //" And DeliveryDt.Logged_Code = '".$PLoggedCode."' ";
			   
	//echo $query; 
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){
	
		$vSaDtId      = $rows[0];
		$vSaDtTotal   = $rows[1];
		$vSaDtQty     = $rows[2];
		$vSaDtPrice   = $rows[3];
		$vSaDtPriceB1 = $rows[4];
		$vSaDtPriceB2 = $rows[5];
		$vSaDtDiscPer = $rows[6];
		
		$vSaDtDiscountAmt = 0;
		$vSaDtDiscountAmt      = ($vSaDtTotal/$vSaTotal)*$vSaDisAmt;
		$vSaDtDiscountAmtBase1 = ($vSaDtDiscountAmt*$PRate)/$PRate1;
		$vSaDtDiscountAmtBase2 = ($vSaDtDiscountAmt*$PRate)/$PRate2;
		
		
		$queryupd =  " UPDATE temp_salesdt SET SaleDt_DiscountAmount = $vSaDtDiscountAmt, ".
					 " SaleDt_DiscountBase1 = $vSaDtDiscountAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscountAmtBase2  ".
					 " Where SaleDt_ID = ".$vSaDtId;
					 //" And Logged_Code = '".$PLoggedCode."' ";
		
		if (!updateData($connection, $queryupd, true))
			$error  = mysql_error(); 
		

	}
	
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalDiscount: '.$error;
	   
	Return $error;
}

function Create_SalesJv($PSaId, $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_SalesAutoJv(".$PSaId.", 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_SalesAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_SalesJv: '.$error;

	Return $error;
	

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

HERE;
*/

?>