<?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 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_PostToJournal,0) As Module_PostToJournal, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_ExpireDate,0) As Module_ExpireDate ".
			 " 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 From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp ".
          " 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 = 1;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

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

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];
		
						
		
		$querypack = " SELECT 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 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 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, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} // End If No Error Exists 

	
	} // End If No Constraints Found On Delete
	
}

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

	if (empty($txtSaDtPrice))      $txtSaDtPrice = 0;
	if (empty($txtSaDtDiscount))   $txtSaDtDiscount = 0;
	if (empty($txtSaDtQty)) 	   $txtSaDtQty = 0;    
	if (empty($txtSaDtQty2))	   $txtSaDtQty2 = 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."'";
	}
				
	$query = "SELECT Item_Vat, ifNull(Item_Promotion, 0) FROM Items WHERE item_Code = '".$txtItemCode."'";
	$result = selectData($connection, $query);
	$item_vat  = $result[0];
	$ItemPromo = $result[1];
	//$item_vat = $item_vat/100;
	$tax_flag = 0;
	$notax_flag = 1;
	if ($item_vat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}	
			

	$vSaDtTotal  = 0;
	$vSaCltCode  = '';
	$vSaDiscount = 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 ".
			 " 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];
			
			
	$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) $txtSaDtPrice = 0;
			
	if ($SalesTTC == 1) {
		$vSaDtPriceTTC      = $txtSaDtPrice;
		$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
		$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

		
		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
	$vSaDtDiscAmt       = ((($vSaDtPrice*$txtSaDtQty) - ($vSaDtPrice*$txtSaDtQty*$txtSaDtDiscount/100))*$vSaDiscount)/100;
	$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
	$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

		
	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, SalesDt_Remark = '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', ".
			 " SaleDt_DiscountAmount = $vSaDtDiscAmt, SaleDt_DiscountBase1 = $vSaDtDiscAmtBase1, SaleDt_DiscountBase2 = $vSaDtDiscAmtBase2, ".
			 " SaleDt_ExpireDate = $vSaDtExpireDate, SaleDt_BatchNo = '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', SaleDt_Reason = '".ereg_replace("'", "\'", trim($SaleDt_Reason))."' ";
			 
	if ($Module_ProjectDt == 1)
		$query = $query.", Project_Code = $ProjectCodeDt ";
	if ($Module_CostCenterDt == 1)	
		$query = $query.", CostCenter_Code = $CostCentCodeDt ";
		
	$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, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'U', $connection);
		$message  = $message . $CalculateResult;
				
	}else{
		$message  = mysql_error(); 
		frollback();
	}
			
	
} 

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

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Sales Is Posted
	$query = "SELECT ifNull(Sale_Posted,0) As SalesPosted FROM Sales WHERE Sale_id = '".$SSaId."'";
	$result = selectData($connection, $query);
	$SaPosted = $result[0];
	
	if ($SaPosted == 1 ){
		$message  = 'Delete not allowed, Invoice posted.';
		$AllowDelete = 0;
	}
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
	    $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;
		
		$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']."', 'return_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)) {
			// 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 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 != ''){

	$ErrorExists = 0;
	
	//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_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) ".
			 " 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_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']."' ".
			 " FROM Sales ".
			 " WHERE Sale_id = ".$SSaId;
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}

		
	if ($ErrorExists == 0) {
		//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, SaleDt_Reason ) ".
				 " 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']."', SaleDt_Reason  ".
				 " FROM Salesdt ".
				 " WHERE Sale_id = ".$SSaId;
		
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			
		  
	}

}



//Load Delivery
else if($mainmode == "loaddelivery" ){
	
	//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];
		
		//Elie
		$sub_query = "Select Client_VAT From clients Where ledger_number = '".$vDeliveryClient."'";
		
		$sub_result = selectData($connection, $sub_query);
		$vClientVat = $sub_result[0];
		
		//Elie
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, CreditCur, CreditAccountReturn, TipsAccount, ".
					 " VatAccount, CreditVATReturn, Sale_CLAAccount, Sale_DCTAccount, Sale_AWAccount, Sale_TRPAccount, PromotionAccount, ".
					 " TransportAccount, BonusAccount ".
					 " 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_TransportAmount, Sale_TransportBase1, Sale_TransportBase2, Sale_TransportTTC, Sale_BonusAccount, Sale_BonusAmount, Sale_BonusBase1, Sale_BonusBase2, Sale_BonusTTC, User_Account, Logged_Code) ".
				 " SELECT distinct $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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Delivery_DiscountPer, 0, 0, 0, 0, 0, 0, ".
				 " Delivery_Mode, 'SR', 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]."', Deliveries.Sorder_reference, Delivery_Reference, Delivery_SorderReferences, Delivery_Reference, '".$Acc_Result[15]."', Sales.Sale_TransportAmount, Sales.Sale_TransportBase1, ".
				 " Sales.Sale_TransportBase2, Sales.Sale_TransportTTC, '".$Acc_Result[16]."', Sales.Sale_BonusAmount, Sales.Sale_BonusBase1, Sales.Sale_BonusBase2, Sales.Sale_BonusTTC, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
				 " From Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
				 " left Join Sales on Sales.Sale_RelatedId = Deliveries.Delivery_ReturnRef ".
				 " Where Delivery_ID = '".$SelectedRec."' ".
				 " And Deliveries.Journal_Type = 'DR' ";
			//echo $query."<br>";exit;	 
		$result=mysql_query($query,$connection);
		
		
		if ($result){
			$SSaId = $vSaId;
			fcommit();
		}else{
			$vSaId = "";
			$SSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	
	if ($SSaId != '') {
	
		$ErrorExists = 0;
		
		$vSaId = $SSaId;
		
		$sub_query = " SELECT Currency_Code, Sale_Date, Client_Code, Project_Code, CostCenter_Code, ifNull(Sale_DiscountPer,0), ".
					 " Date_Format(Sale_Date,'%d/%m/%Y') As SaleDate, ifNull(Sale_chkvat,0), ifNull(Sale_DiscountAmount,0) ".
					 " FROM Temp_Sales ".
					 " WHERE Sale_ID = '".$vSaId."' ";
		$sale_result = selectData($connection, $sub_query);
		
		$vSaDiscountPer = $sale_result[5];				   
		if (empty($vSaDiscountPer)) $vSaDiscountPer = 0;
		
		$vSaCurr        = $sale_result[0];
		$vSaClientCode  = $sale_result[2];
		$vSaDate        = $sale_result[6];
		$vSaVatChkbx    = $sale_result[7];
		$vSaDiscountAmt = $sale_result[8];
		
		$sub_query = " SELECT DeliveryDt_id, DeliveryDt.Currency_Code, DeliveryDt.Warehouse_Code, DeliveryDt.Item_code, DeliveryDt.Item_CodePacked, ifNull(DeliveryDt_Quantity,0), ".
					 " DeliveryDt_Remark, ifNull(DeliveryDt_promotion,0), DeliveryDt.RelatedDt_Id, DeliveryDt.Client_Code, DeliveryDt.Project_Code, DeliveryDt.CostCent_Code, ".
					 " Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_ItemAccount, Deliverydt_discountacc, DeliveryDt_PromoAcc, ". 
					 " DeliveryDt.Item_UnitCoef, DeliveryDt.Item_Unit2Qty, DeliveryDt.User_Account, DeliveryDt.DeliveryDt_ExpireDate, DeliveryDt.DeliveryDt_BatchNo, Deliverydt_costbase1, ".
					 " Deliverydt_costbase2, Deliverydt_DirectStkDbt  ".
					 " FROM DeliveryDt ";
		
		if($SSaDtId != '')			 
			$sub_query = $sub_query." WHERE DeliveryDt_Id In (".$SSaDtId.") And DeliveryDt.Journal_Type = 'DR' ";
		else 
			$sub_query = $sub_query." WHERE DeliveryDt.Delivery_Id = '".$SelectedRec."' And DeliveryDt.Journal_Type = 'DR' ";		
			
		
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_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;
			$vSaDtItemVat       = 0;
			$vSaDtItemTax       = 0;
			$vSaDtItemTax1      = 0;
			$vSaDtItemTax2      = 0;
			$vSaDtItemTax3      = 0;
			$vSaDtItemTax4      = 0;
			$vSaDtItemTax5      = 0;
			
			$vSaDtTrsPer        = 0;
			$vSaDtTrsAmt        = 0;
			$vSaDtTrsAmtB1      = 0;
			$vSaDtTrsAmtB2      = 0;
			$vSaDtBonPer        = 0;
			$vSaDtBonAmt        = 0;
			$vSaDtBonAmtB1      = 0;
			$vSaDtBonAmtB2      = 0;
			
			$vSaDtCostBase1 	= 0;
			$vSaDtCostBase2 	= 0;
			
			$vSaDtCostBase1		= $sub_row[23];
			$vSaDtCostBase2		= $sub_row[24];
			$vLedger_Account	= $sub_row[25];//echo $vLedger_Account;exit;
			
			$sub_query1 = " Select Sum(ifNull(SalesDt.SaleDt_Quantity,0)) As QuantityReturned ".
					      " From SalesDt ".
						  " Where SalesDt.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And SalesDt.Sale_Id != '".$vSaId."' ".
						  " And SalesDt.Journal_Type = 'SR' ";
			$sub_result1 = selectData($connection, $sub_query1);
			if ($sub_result1[0] == '') $sub_result1[0] = 0;
	
			$sub_query2 = " Select Sum(ifNull(Temp_SalesDt.SaleDt_Quantity,0)) As QuantityReturnedTemp ".
					      " From Temp_SalesDt ".
					      " Where Temp_SalesDt.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And Temp_SalesDt.Sale_Id = '".$vSaId."' ".
						  " And Temp_SalesDt.Journal_Type = 'SR' ";
			$sub_result2 = selectData($connection, $sub_query2);
			if ($sub_result2[0] == '') $sub_result2[0] = 0;		  
			

			//Get The Remaining Qty
			$vSaDtQty = ($sub_row[5] - ($sub_result1[0] + $sub_result2[0]));
			
			if ($vSaDtQty > 0 ) {
				
				$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];		
				
				

                 //Check If Related SalesDt Exists
                $sub_query1  = "Select Count(*) From SalesDt Where RelatedDt_Id = '".$sub_row[8]."' And Journal_Type = 'SI' ";
				$sub_result1 = selectData($connection, $sub_query1);
				if ($sub_result1[0] == '') $sub_result1[0] = 0;
				$vRelatedSaleCount = $sub_result1[0];
				
				If ($vRelatedSaleCount > 0) {
					// Get Prices From SalesDt Related To The Delivery Related To This Return Delivery
					$sub_query1  = " SELECT Currency_Code, ifNull(SaleDt_Price,0), ifNull(SaleDt_PriceBase1,0), ifNull(SaleDt_PriceBase2,0), ifNull(SaleDt_DiscountPer,0), ".
                                   " ifNull(SaleDt_PriceTTC,0), ifNull(Saledt_priceTTCBase1,0), ifNull(Saledt_priceTTCBase2,0), ifNull(Item_Vat,0), ifNull(Item_Tax,0), ".
                                   " ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ".
								   " ifNull(SaleDt_TransportAmount,0), ifNull(SaleDt_TransportBase1,0), ifNull(SaleDt_TransportBase2,0), ifNull(SaleDt_BonusAmount,0), ".
								   " ifNull(SaleDt_BonusBase1,0), ifNull(SaleDt_BonusBase2,0) ".
								   " FROM SalesDt ".
				                   " WHERE SalesDt.RelatedDt_Id = '".$sub_row[8]."' ".
							       " AND SalesDt.Journal_Type = 'SI' ";
					$sub_result1 = selectData($connection, $sub_query1);

					$vSaDtCurr          = $sub_result1[0];
					$vSaDtPrice         = $sub_result1[1];
					$vSaDtPriceBase1    = $sub_result1[2];
					$vSaDtPriceBase2    = $sub_result1[3];
					$vSaDtDiscPer       = $sub_result1[4];
					$vSaDtPriceTTC      = $sub_result1[5];
					$vSaDtPriceTTCBase1 = $sub_result1[6];
					$vSaDtPriceTTCBase2 = $sub_result1[7];
					$vSaDtItemVat       = $sub_result1[8];
					$vSaDtItemTax       = $sub_result1[9];
					$vSaDtItemTax1      = $sub_result1[10];
					$vSaDtItemTax2      = $sub_result1[11];
					$vSaDtItemTax3      = $sub_result1[12];
					$vSaDtItemTax4      = $sub_result1[13];
					$vSaDtItemTax5      = $sub_result1[14];	
					$vSaDtTrsAmt        = $sub_result1[15];
					$vSaDtTrsAmtB1      = $sub_result1[16];
					$vSaDtTrsAmtB2      = $sub_result1[17];
					$vSaDtBonAmt        = $sub_result1[18];
					$vSaDtBonAmtB1      = $sub_result1[19];
					$vSaDtBonAmtB2      = $sub_result1[20];

					If ($vSaCurr != $vSaDtCurr) {
						$vSaDtPrice    = ConvertCurrency($vSaDtCurr, $vSaCurr, insertMySQLDate($vSaDate), $vSaDtPrice, $connection);
						$vSaDtPriceTTC = ConvertCurrency($vSaDtCurr, $vSaCurr, insertMySQLDate($vSaDate), $vSaDtPriceTTC, $connection);
						$vSaDtTrsAmt   = ConvertCurrency($vSaDtCurr, $vSaCurr, insertMySQLDate($vSaDate), $vSaDtTrsAmt, $connection);
						$vSaDtBonAmt   = ConvertCurrency($vSaDtCurr, $vSaCurr, insertMySQLDate($vSaDate), $vSaDtBonAmt, $connection);
					}
			
				} else {
				
					$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$sub_row[9]."'";
					//echo "<br><br>".$query;exit;
					$result = selectData($connection, $query);
					$c_sp = $result[0];
					
					
					
					$query = " SELECT Currency_Code, Item_SellingPrice1, Item_SellingPrice2, Item_SellingPrice3, Item_SellingPrice4, ".
					         " Item_SellingPrice5, Item_SellingPrice6, ifNull(Item_Vat,0), ifNull(Item_Tax,0), 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 = '".$sub_row[3]."'";
						
					//echo "<br><br>".$query;exit;
					$result = selectData($connection, $query);
					$i_sp = $result[1];
						
					switch ($c_sp){
						case "II":
							$i_sp = $result[2]; break;
						case "III":
							$i_sp = $result[3]; break;
						case "IV":
							$i_sp = $result[4]; break;
						case "V":
							$i_sp = $result[5]; break;
						case "VI":
							$i_sp = $result[6]; break;
					}
					
					// Convert From Item Currency To Invoice Currency
					$i_sp    = ConvertCurrency($result[0], $vSaCurr, insertMySQLDate($vSaDate), $i_sp, $connection);
					
					$vSaDtDiscPer       = 0;
					$vSaDtItemVat       = $result[7];
					$vSaDtItemTax       = $result[8];
					$vSaDtItemTax1      = $result[9];
					$vSaDtItemTax2      = $result[10];
					$vSaDtItemTax3      = $result[11];
					$vSaDtItemTax4      = $result[12];
					$vSaDtItemTax5      = $result[13];	
					
					if ($SalesTTC == 1) {
						$vSaDtPriceTTC      = $i_sp;
						$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;					
					
						$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $vSaDtItemVat/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;
								
					}
					
				}
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $sub_row[18];
					if ($Module_Unit1Method == 1)
						$vItemUnit2Qty = $vSaDtQty*$vItemUnitCoef;
					else	
						$vItemUnit2Qty = $vSaDtQty/$vItemUnitCoef;
				}
				
				// Calculation For Detail Discount Amount
				$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$vSaDtDiscPer/100))*$vSaDiscountPer)/100;
				$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
				
				$SaleDt_ExpireDate = $sub_row[21];
				if (empty($SaleDt_ExpireDate)) $SaleDt_ExpireDate = 'Null';
				else $SaleDt_ExpireDate = "'".$SaleDt_ExpireDate."'";
				
				$ProjectCode = $sub_row[10];
				if (empty($ProjectCode)) $ProjectCode = 'Null';
				else $ProjectCode = "'".$ProjectCode."'";
				
				$CostCentCode = $sub_row[11];
				if (empty($CostCentCode)) $CostCentCode = 'Null';
				else $CostCentCode = "'".$CostCentCode."'";
				
				$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0) ".
						 " FROM Items WHERE item_Code = '".$sub_row[3]."'";
				$result = selectData($connection, $query);
				$ItemVat 	   = $result[0];
				$Item_MaxQty   = $result[1];
				$ItemGroupCode = $result[2];
				$ItemProd      = $result[3];
				$ItemTTCInc    = $result[4];
				$ItemUnit      = $result[5];
				$ItemPromo     = $result[6];
				$ItemNonStock  = $result[7];
				
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditVATReturn, CreditAccountReturn, ".
						 " CreditReturnNonStock, CreditVATReturnNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
						 " FROM salessetup ";
								 
				$result = selectData($connection, $query);
						
				$vSaStpDirectStkDbt = $result[0];
				$vSaStpDirectStkCrd = $result[1];
				$vSaStpDirectStkCur = $result[2];	
				$vSaStpDiscAcc      = $result[3];	
				$vSaStpCreditVatAcc = $result[4];	
				$vSaStpCreditAcc    = $result[5];	
				
				$vSaStpCreditNonStockAcc    = $result[6];
				$vSaStpCreditVatNonStockAcc = $result[7];
				$vSaStpVatAcc 		  	  	= $result[8];
				$vSaStpVatNonStockAcc 	  	= $result[9];
				$vSaStpVatAccCash	  	  	= $result[10];
				$vSaStpVatNonStockAccCash 	= $result[11];
						
					
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, 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[11];
				
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
							
					if ($ItemVat > 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 ($ItemVat > 0 && $vSaVatChkbx == 1) {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
					} else {
						if ($ItemNonStock == 1)
							$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
						else	
							$vSaDtItemAcc = $vSaStpCreditAcc;
					}

					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
				}
				
				
				$sub_queryVat = " SELECT GetVATAccount('".$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();
				
				$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_ItemAccount, Saledt_discountacc, ".
							  " Item_Tax, 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_BonusAmount, SaleDt_BonusBase1, SaleDt_BonusBase2, SaleDt_VatAccount,  salesdt_CostAcc, salesdt_CostBase1, ".
							  " salesdt_CostBase2, salesdt_Account, Logged_Code, SaleDt_Reason ) ".
							  " VALUES ( $vSaDtId, $vSaId, '".$sub_row[0]."', '".$sale_result[0]."', '".$sale_result[1]."', '".$sale_result[2]."', $ProjectCode, $CostCentCode, '".$sub_row[2]."', '".$sub_row[3]."', '".$sub_row[4]."', ".
							  " '".$vSaDtQty."', $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $vSaDtDiscPer, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $vSaDtItemVat, $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, ".
							  " '".ereg_replace("'", "\'", trim($sub_row[6]))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtItemAcc."', '".$vSaDtDiscAcc."', $vSaDtItemTax, $vSaDtItemTax1, $vSaDtItemTax2, $vSaDtItemTax3, ".
							  " $vSaDtItemTax4, $vSaDtItemTax5, ".$sub_row[7].", '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'SR', $FI_BelongsToGrp, $SaleDt_ExpireDate, '".$sub_row[22]."', $vSaDtTrsAmt, $vSaDtTrsAmtB1, $vSaDtTrsAmtB2, ".
							  " $vSaDtBonAmt, $vSaDtBonAmtB1, $vSaDtBonAmtB2, '".$vSaDtVatAcc."', '".$vLedger_costAcc."', '".$vSaDtCostBase1."', '".$vSaDtCostBase2."', '".$vLedger_Account."', '".$_SESSION['useraccount']."', '".$SaleDt_Reason."' ) ";
							 
				//echo $sub_query1; exit;	
				$sub_result1=mysql_query($sub_query1,$connection);
			
			
				if ($sub_result1){
					
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} // End if($vSaDtQty > 0)
		}  //End Loop of DeliveryDt Query
		
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($vSaId, $vSaDate, $vSaVatChkbx, $vSaDiscountPer, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}	

	}

}


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)){
			$message  = mysql_error($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)){
			$message  = mysql_error($connection); 
		} 
	}
}

//Changing Return 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];
	
	

	$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) ".
				 " 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];	
			
				
		$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    = 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);
		
		$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 ".
					  " 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, '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($SSaVatChkbx))		$SSaVatChkbx = 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))."'";		
		
		
		
	$vSaRef = '';
	$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;
	
		
	
	$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;
	

	$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 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;
	}
	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;
	}
	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;
	}
	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;
	}
	
	//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('ReturnSales',$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];
						
					
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = '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= $SSaVatChkbx;	
				
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					echo $vTranStpRmVatAcc;

					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;
					}

				 
	
				}
				
				
				$querydt = " UPDATE temp_salesdt SET saledt_ItemAccount = $vSaDtItemAcc ".
					   " WHERE Saledt_id = $sub_row[0] ";
	 			//echo $querydt;
				//exit;
				$resultdt=mysql_query($querydt,$connection);
			
			
			
			
			
					
		}  //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(); 
					  
			
			$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 ".
						 " SaleDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " WHERE SaleDt_id = '".$sub_rows7[0]."' ";
						 
				$result=mysql_query($query,$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 ".
					  " 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*$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(); 
				

		}

			
		
		//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, 'P', $connection);
		$message  = $message . $CalculateResult;
							
					
		$query = " UPDATE temp_sales SET ".
				 " 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 ".
				 " WHERE Sale_id = $SSaId ";
				//" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
		
		if ($result){
						
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, 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('SR', ".$SSaId.", '".$_SESSION['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
				//echo $query; exit;
				
				if ($result != 0){ 
					fcommit();
							
					$query   = " SELECT Sale_Reference, Costcenter_code, Project_Code FROM Sales WHERE Sale_id = $SSaId ";
					$result  = selectData($connection, $query);
					$vSaRef  = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
							
					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('Sreturn_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($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'return_sales', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}					
				} else{
					$ErrorExists = 1;
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempSales Function'; 
					frollback();
				}
			}	
				
		} else{
			$message  = mysql_error(); 
			frollback();
		}
			
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllowed == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
			
		else if ($SaveAllowed == 3) 
			$message  = 'Save not allowed. Net Total And Cash Differs.'; 
		else if ($ErrorExists == 1)	
			$message = 'Save not allowed. Please check for Client/Salesman/Project/Costcenter Code.';
		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_ReturnSales.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSaId=".$SSaId."&PrSaRef=".$vSaRef);
	else
		header ("Location: ./Form_ReturnSales.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_ReturnSalesSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_ReturnSalesSearchPending.php?message=".$message);
else if ($mode == "cancel" )		
	header ("Location: ./Form_ReturnSales.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_ReturnSales.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_ReturnSalesDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PSaId=".$SSaId."&PSaDate=".$PSaDate."&PSaDtId=".$SSaDtId);		
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_ReturnSalesSearch.php?PMode=1&message=".$message);	
else if ($mode == "" && $mainmode == "loaddelivery" )		
	header ("Location: ./Form_ReturnSales_LoadDelivery.php?PMode=1&PSaId=".$SSaId."&message=".$message);			
else if ($mode == "CashPayment") { 
	if ($message != "")
		header ("Location: ./Form_ReturnSales_PayCash.php?PMode=0&PSaId=".$SSaId."&message=".$message);
	else
		header ("Location: ./Form_ReturnSales_PayCash.php?PMode=1&PSaId=".$SSaId."&message=".$message);
}
else if ($mode == "CreditPayment") { 
	header ("Location: ./Form_ReturnSales.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
}
else if ($mode == "changecurrency")	
	header ("Location: ./Form_ReturnSales.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$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, $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;
		
	$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 ($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;	
	
	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  ".
				  " WHERE Sale_ID = ".$PId;
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


function 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;
*/

?>