<?php

session_start();

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

include("config.inc.php");
include("Functions_Sales.php");
include("function.inc.php");
//include("Functions_Purchase.php");

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

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


if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}
//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");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage,
			 ifnull(costcentminimum,0) as costcentminimum from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";
		   
$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;

//Read From 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_InvoiceCheckLimit,0) As Module_InvoiceCheckLimit, ".
			 " ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ".
			 " ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject,ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj,  ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ifNull(Module_ChangeInvoiceItems,0) As Module_ChangeInvoiceItems, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifnull(module_serialnoout,0) as module_serialnoout, ifnull(Module_CreateAdjustmentforPack,0) as Module_CreateAdjustmentforPack ".
             " 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_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ifNull(ModifyVAT,0) As ModifyVAT, ".
		  " ifNull(FI_AllowEditIfDelivered,0) As FI_AllowEditIfDelivered, ifNull(FI_ChangeInvoiceItems,0) As FI_ChangeInvoiceItems, ".
		  " ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse, ifNull(Login_negativeQty,0) As Login_negativeQty,IfNull(FI_SalebelowCost,0) FI_SalebelowCost ".
		  " 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);
}
$message='';

//Submit Record Mode
$deliverydt_heatno	= $_POST["deliverydt_heatno"];  if ($deliverydt_heatno == ""){	$deliverydt_heatno 	= $_GET["deliverydt_heatno"];} 
$PSaRemark			= $_POST["PSaRemark"]; 			if ($PSaRemark == ""){			$PSaRemark 			= $_GET["PSaRemark"];} 
$grnno  			= $_POST["grnno"]; 				if ($grnno == ""){				$grnno 				= $_GET["grnno"]; } 
$txtdestfrom  		= $_POST["txtdestfrom"]; 		if ($txtdestfrom == ""){		$txtdestfrom 		= $_GET["txtdestfrom"]; } 
$txtdestto  		= $_POST["txtdestto"]; 			if ($txtdestto == ""){			$txtdestto 			= $_GET["txtdestto"]; } 
$txtdestdate  		= $_POST["txtdestdate"]; 		if ($txtdestdate == ""){		$txtdestdate 		= $_GET["txtdestdate"]; } 

//if($PSaRemark != '') $PSaRemark = urldecode($PSaRemark);
//$PSaRemark = urlencode($PSaRemark);

if ($mode == "getItemInfo"){
	$item_code 	= $_GET['item_code'];
	$query = "select Item_NetWeight from items where item_code='$item_code'";
	$res = mysql_query($query, $connection);
	$row = mysql_fetch_row($res);
	$weight = $row[0];
	if ($weight == '') $weight = 0;
	echo "[BRK]";
	echo $weight;
	exit;	
}
if ($mode == "getCostCharge"){
	$item_code 	= $_GET['item_code'];
	$date 		= $_GET['deliverydate'];
	$curr		= $_GET['curr'];
	$whcode		= $_GET['warehouse_code'];
	$message = '';
	
	$query = "select round(MeanCostCurByWH('$item_code', CONCAT('".displayParadoxDate(insertDate($date))." ', RIGHT(NOW(), 8)), 1, '$base1', '$curr', '$whcode'), $DecimalBase) ";
 	$res = mysql_query($query, $connection);
	$row = mysql_fetch_row($res);
	$cost = $row[0];
	if ($cost == '') $cost = 0;
	$message = mysql_error(); 
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	echo $cost;
	exit;
}

if ($mode == "getclientname"){
	
		$query = "SELECT Ledger_number,Ledger_name,client_discountonInvoice 
					FROM Clients ";
					
		if($choice==0)
			$query = $query." WHERE Upper(Ledger_number) = Upper('".str_replace('\\','\\\\',$clientcode)."') ";
		else
			$query = $query." WHERE Upper(Ledger_name) = Upper('".str_replace('\\','\\\\',$clientcode)."') ";
		$query = $query." and client_deactivate = 0";
		$result = selectData($connection, $query);
		$ClientCode = $result[0];
		$ClientName = $result[1];
		
		$client_discountonInvoice = $result[2];
		echo"[BRK]";
		echo $ClientCode;
		echo"[BRK]";
		echo $ClientName;
		echo"[BRK]";
		echo $client_discountonInvoice;
 
exit;
}
else
if ($mode == "importfromexcel"){

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

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSaCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSaCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PSaProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSaProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PSaClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSaClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	if ($PSaSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSaSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Salesman Code.';
		}
	}
	 
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	 
	 
	  $txtCostCentCodeDt = $PSaCostCentCode;
	  $txtProjectCodeDt = $PSaProjectCode;
	
	//Insert Master Table
	if ($SSaId == "" && $ErrorExists == 0){
	
		if (empty($PSaDiscountAmt))
			$PSaDiscountAmt = 0;
		if (empty($PSaDiscount))
			$PSaDiscount = 0;
			
		if (empty($PSaCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSaCostCentCode."'";
			
		if (empty($PSaProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSaProjectCode."'";
			
		fbegin();	
		$PSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
		$result = selectData($connection, $query);
		$PSaVatChkbx = $result[0];
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
					 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount, BonusAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			 
		fbegin();
		
		if (empty($PSaVehicleLoadWeight))   $PSaVehicleLoadWeight = 0;
		if (empty($PSaVehicleWeight))   $PSaVehicleWeight = 0;
		$delivery_date         = $_GET['delivery_date'];
		$delivery_card_msg     = $_GET['delivery_card_msg'];
		$delivery_contact      = $_GET['delivery_contact'];
		$delivery_contactphone = $_GET['delivery_contactphone'];
		if($delivery_date == '') $delivery_date = $PSaDate;
		
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
				 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
				 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
				 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, Delivery_BonusAccount, Delivery_ManualNo,Delivery_vehicleweight,Delivery_vehicleLoadweight, User_Account, Logged_Code, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone,GRNNO) ".
				 " VALUES ( ".$PSaId.", Null, '".insertMySQLDate($PSaDate)."', '".insertMySQLDate($PSaMaturityDate)."' , ".
				 "          '".ereg_replace("'", "\'", trim($PSaRemark))."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', '".ereg_replace("'", "\'", trim($PSaDAddress))."', '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaDriverName))."', '".ereg_replace("'", "\'", trim($PSaSalesmanCode))."', '".$PSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
				 "          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PSaVatChkbx, '".$Acc_Result[12]."'".
				 "          , '".ereg_replace("'", "\'", trim($PSaManualNo))."', $PSaVehicleWeight, $PSaVehicleLoadWeight, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".insertMySQLDate($delivery_date)."', '".$delivery_card_msg."', '".$delivery_contact."',  '".$delivery_contactphone."','".$grnno."')";
					 
		
		$result=mysql_query($query,$connection);
		
	
	
		//echo $query."<br>";exit;	
		
		if ($result){
			$SSaId = $PSaId;
			fcommit();
		}else{
			$PSaId = "";
			$SSaId = "";
			$ErrorExists == 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	
	
	if ($SSaId != "" && $SSaDtId == ""  && $ErrorExists == 0){
	$WarningMsg = '';
		
		$vSaDtPriceTTC      = 0;
		$vSaDtPriceTTCBase1 = 0;
		$vSaDtPriceTTCBase2 = 0;					
		$vSaDtPrice         = 0;
		$vSaDtPriceBase1    = 0;
		$vSaDtPriceBase2    = 0;
		$vSaDtCostBase1     = 0;
		$vSaDtCostBase2     = 0;
		$vSaDtDiscAmt       = 0;
		$vSaDtDiscAmtBase1  = 0;
		$vSaDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSaDtTax1 = 0;
		$vSaDtTax2 = 0;
		$vSaDtTax3 = 0;
		$vSaDtTax4 = 0;
		$vSaDtTax5 = 0;
		
		$QtyExistExceeded   = 0;
		
	if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

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

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



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


	$x=1;
	$arrayemp = array();
	
    while($x<=$excel->sheets[0]['numRows']) { ///rowwwww
            
		$txtItemCode = $excel->sheets[0]['cells'][$x][1];
		$itemdesc = $excel->sheets[0]['cells'][$x][2];
		$lstWarehouse = $excel->sheets[0]['cells'][$x][3];
		$txtSaDtQty = $excel->sheets[0]['cells'][$x][4];
		
			$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
			//echo "<br><br>".$query;
			$result = selectData($connection, $query);
			$c_sp = $result[0];
	
			$query = " SELECT ifNull(Item_Vat,0), ifNull(Item_Unit,0), ifNull(Item_Promotion,0), ifNull(Item_tax1,0), ifNull(Item_tax2,0), ".
					 " ifNull(Item_tax3,0), ifNull(Item_tax4,0), ifNull(Item_tax5,0), Currency_Code, Item_SellingPrice1, Item_SellingPrice2, ".
					 " Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6 ".
					 " FROM Items WHERE item_Code = '".$txtItemCode."'";
					 
			$result = selectData($connection, $query);
			$ItemVat    = $result[0];
			$ItemUnit   = $result[1];
			$ItemPromo  = $result[2];
			$ItemTax1   = $result[3];	
			$ItemTax2   = $result[4];	
			$ItemTax3   = $result[5];	
			$ItemTax4   = $result[6];	
			$ItemTax5   = $result[7];	
			$ItemCurr   = $result[8];	
			
			
			$i_sp   = $result[9];
			
			switch ($c_sp){
				case "II":
					$i_sp = $result[10]; break;
				case "III":
					$i_sp = $result[11]; break;
				case "IV":
					$i_sp = $result[12]; break;
				case "V":
					$i_sp = $result[13]; break;
				case "VI":
					$i_sp = $result[14]; break;
			}
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = 0;
			}
				
			
											
			if ($Module_Delivery == 0) {	
			
				if ($SalesTTC == 1) {
					$txtSaDtPrice      = $i_sp;
					$txtSaDtPrice       = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					$vSaDtPriceTTCBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					$vSaDtPriceTTCBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);

					$txtSaDtPrice      = ($txtSaDtPrice / (1 + $ItemVat/100));
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
							
				} else	{
					$txtSaDtPrice      = $i_sp;
					
					$txtSaDtPrice      = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $txtSaDtPrice, $connection);
					
					$txtSaDtPrice      = 0;
					$vSaDtPriceTTCBase1 = 0;
					$vSaDtPriceTTCBase2 = 0;
							
				}
				
			} 
		
			
			$query_cost = " select ifNull(MeanCostCur('".$row[0]."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
			              " ifNull(MeanCostCur('".$row[0]."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
			$result_cost = selectData($connection, $query_cost);
			
			$vSaDtCostBase1  = $result_cost[0];
			$vSaDtCostBase2  = $result_cost[1];
			if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
			if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
			//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);		
		
		/////////////////////// detail table
			if (empty($PSaDiscountAmt))	   $PSaDiscountAmt = 0;
		if (empty($PSaDiscount))	   $PSaDiscount = 0;
			
		if (empty($txtSaDtPrice))	   $txtSaDtPrice = 0;
		if (empty($txtSaDtDiscount))   $txtSaDtDiscount = 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 (empty($PSaCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSaCostCentCode."'";
			
		if (empty($PSaProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSaProjectCode."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	
		
		
	
		
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		$query = "SELECT ifNull(Delivery_Mode,0) FROM Deliveries WHERE Delivery_id = ".$SSaId;
		$result = selectData($connection, $query);
		$vSaPayMode = $result[0];
		
 
		
		// Case Not Pack Item
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
		if ($ItemPack != 1) {
		

			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
			        " FROM Items WHERE item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'";
			$result = selectData($connection, $query);
			$item_vat 	   = $result[0];
			$Item_MaxQty   = $result[1];
			$ItemGroupCode = $result[2];
			$ItemProd      = $result[3];
			$ItemTTCInc    = $result[4];
			$ItemUnit      = $result[5];
			$ItemPromo     = $result[6];
			$ItemNonStock  = $result[7];
			//$item_vat = $item_vat/100;
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				/*if ($ItemUnit > 0) {
					$vItemUnitCoef = 1/$ItemUnit;
					$vItemUnit2Qty = $vItemUnitCoef * $txtSaDtQty;
				}*/
				
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $txtSaDtQty2;
			}
			
			//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
			if ($ItemNonStock == 0) {
				if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "") {
					$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtSaDtBatchNo."', now(), 0, 'DI', '', '') QtyExists From Dual ";
				} else {
					$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', now(), 0, 'DI', '', '') QtyExists From Dual ";
				}
					 
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];

				$sub_query1 = " Select ifNull(Sum(ifNull(DeliveryDt_Quantity,0)),0) FROM Temp_DeliveryDt ".
							  " Where Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Delivery_ID = $PSaId And DeliveryDt_ID != ifNull('".$txtSaDtId."',0) ";	
				if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "")
					$sub_query1 = $sub_query1." And	DeliveryDt_BatchNo = '".$txtSaDtBatchNo."' ";
							
				$sub_result1 = selectData($connection, $sub_query1);
				if (empty($sub_result1[0])) $sub_result1[0] = 0;

				$vItemQtyExists = $vItemQtyExists + $sub_result1[0];


				if (abs($txtSaDtQty) > $vItemQtyExists && abs($txtSaDtQty) > 0)
					$QtyExistExceeded = 1;
			}
			//fady
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1 )) {
			

				if ($Module_Delivery == 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
					/*$vSaDtDiscAmt       = ((($vSaDtPrice*$txtSaDtQty) - ($vSaDtPrice*$txtSaDtQty*$txtSaDtDiscount/100))*$PSaDiscount)/100;
					$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
*/
					if ($Module_AdditionalTaxes == 1) {
					
						// Calculation of Item Tax Amounts
						$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
								 " FROM Clients ".
								 " WHERE Ledger_number = '".$PSaClientCode."'";
											 
						$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 = '".str_replace('\\','\\\\',$txtItemCode)."'";
											 
						$result = selectData($connection, $query);

						
						if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
						if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
						if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
						if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
						if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
							
					}
						
					

				} //End ($Module_Delivery == 0) 	
				
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
						 " 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];	
				$vSaStpPromoAcc     = $result[6];
				$vSaStpTipsAcc      = $result[7];
				
				$vSaStpCreditNonStockAcc    = $result[8];
				$vSaStpCreditVatNonStockAcc = $result[9];
				$vSaStpVatAcc 		  	  	= $result[10];
				$vSaStpVatNonStockAcc 	  	= $result[11];
				$vSaStpVatAccCash	  	  	= $result[12];
				$vSaStpVatNonStockAccCash 	= $result[13];
						
					
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc ".
						 " 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];
				$vTranStpPromoAcc        = $result[11]; 
				$vTranStpTipsAcc         = $result[12]; 
						
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					$vSaDtPromoAcc     = $vTranStpPromoAcc;
					$vSaDtTipsAcc      = $vTranStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 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;		
					//$vSaDtVatAcc       = $vSaStpVatAcc;
					$vSaDtDiscAcc      = $vSaStpDiscAcc;
					$vSaDtPromoAcc     = $vSaStpPromoAcc;
					$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 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;
					//}
					
									
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				
				
				
				$query_cost = " select ifNull(MeanCostCur('".str_replace('\\','\\\\',$txtItemCode)."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".str_replace('\\','\\\\',$txtItemCode)."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				
				$vSaDtCostBase1  = $result_cost[0];
				$vSaDtCostBase2  = $result_cost[1];
				$vSaDtCost=ConvertCurrency($base1, $PSaCurr, insertMySQLDate($PSaDate), $$vSaDtCostBase1, $connection);
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				//echo $query_cost; exit;
				//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
				fbegin();
				$txtSaDtId = get_nextsequence('deliverydt_id','',$connection);	
				fcommit();
				
				fbegin();
				$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
						 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
						 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
						 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, ".
						 " DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,DeliveryDt_heatNo ) ".
						 " VALUES ( ".$txtSaDtId.", ".$PSaId.", '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', 'DI', '".ereg_replace("'", "\'", trim($PSaClientCode))."',  ".
						 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."', Null, $txtSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, 0, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
						 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, null, '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
						 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $chkSaDtPromo, $vSaDtCost, ".
						 "          $vSaDtCostBase1, $vSaDtCostBase2, Null, Null, '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','$deliverydt_heatno' ) ";
				 
				//echo $query."<br>";exit;		
				$result=mysql_query($query,$connection);
				
				if ($result){
					fcommit();
				}else{
					$txtSaDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error($connection); 
					frollback();
				}
			}	
			else {
				//$ErrorExists = 1;
				$message  = "Qty[".abs($txtSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
				
			}
			
		}	// End Case Not Pack Item
		else {
		
			$promo_display = true;
			$promo_exhausted  = 0;
			$QtyExistExceeded = 0;
			
			$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
						   " FROM PackDt ".
						   " WHERE Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'  ";
								   
			$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
			while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
				$vItemCodePacked = $rowspackdt[0];
				$vItemCode = $rowspackdt[1];
				$vPackDtQty = $rowspackdt[2];
				$vPackDtCostPer = $rowspackdt[3];
				$vPackDtPromo = $rowspackdt[4];
				$vPackDtPromoQty = $rowspackdt[5];
				
				$sub_query = " SELECT ifNull(Item_NonStock,0) FROM Items WHERE Item_Code = '".$vItemCode."'";
				$sub_result = selectData($connection, $sub_query);
				$ItemNonStock    = $sub_result[0];
					
				// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
				if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
					
					if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
						//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
						$sub_query = " Select Sum(ifNull(DeliveryDt_Quantity,0)) ".
									 " From DeliveryDt ".
									 " Inner Join Deliveries on DeliveryDt.Delivery_id = Deliveries.Delivery_id ".
									 " Where DeliveryDt.Item_CodePacked = '".str_replace('\\','\\\\',$txtItemCode)."' ".
									 " And DeliveryDt.Item_Code = '".$vItemCode."' ".
									 " And ifNull(DeliveryDt.Deliverydt_OldData,0) = 0 ".
									 " And Deliveries.Journal_Type = 'DI' ".
									 " And Deliveries.Delivery_Date >= '".$rowspackdt[6]."' and Deliveries.Delivery_Date <= '".$rowspackdt[7]."' ";

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

						if ($vPackDtPromoQty <= ($sub_result[0] + $txtSaDtQty*$vPackDtQty)){
							$promo_exhausted = 1;
						}
					}else{
						$promo_exhausted = 1;
					}
					
					if ($promo_exhausted == 1) break;
				
				}
				
				//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
				if ($ItemNonStock == 0 && $promo_exhausted == 0){
					if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "") {
						$sub_query  = " Select QtyExistsByBatchNo('".$vItemCode."', '".$lstWarehouse."', '".$txtSaDtBatchNo."', now(), 0, 'DI', '', '') QtyExists From Dual ";
					} else {
						$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', now(), 0, 'DI', '', '') QtyExists From Dual ";
					}
					
					$sub_result = selectData($connection, $sub_query);
					$vItemQtyExists = 0;
					$vItemQtyExists = $sub_result[0];

					$sub_query1 = " Select ifNull(Sum(ifNull(DeliveryDt_Quantity,0)),0) FROM Temp_DeliveryDt ".
								  " Where Item_code = '".$vItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Delivery_ID = $PSaId And DeliveryDt_ID != ifNull('".$txtSaDtId."',0) ";	
					if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "")
						$sub_query1 = $sub_query1." And	DeliveryDt_BatchNo = '".$txtSaDtBatchNo."' ";
								
					$sub_result1 = selectData($connection, $sub_query1);
					if (empty($sub_result1[0])) $sub_result1[0] = 0;

					$vItemQtyExists = $vItemQtyExists + $sub_result1[0];
					$vSaDtQty      = $txtSaDtQty*$vPackDtQty;

					if (abs($vSaDtQty) > $vItemQtyExists && abs($vSaDtQty) > 0) {
						$QtyExistExceeded = 1;
						Break;
					}
				}
				
				
			}		
			
			//fady		
			if ($promo_exhausted == 0 && ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1 ))){
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'  ";
								   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
					

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

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

						if ($Module_Delivery == 0) {	
							if ($SalesTTC == 1) {
								$vSaDtPriceTTC      = (($txtSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$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 = $vSaDtPriceTTC;								
										
								//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
							} else	{
								$vSaDtPrice      = (($txtSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
								$vSaDtPriceTTC      = 0;
								$vSaDtPriceTTCBase1 = 0;
								$vSaDtPriceTTCBase2 = 0;
										
							}
									
								
							// Calculation For Detail Discount Amount
							$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$txtSaDtDiscount/100))*$PSaDiscount)/100;
							$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
							$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

							if ($Module_AdditionalTaxes == 1) {
								
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
										 " FROM Clients ".
										 " WHERE Ledger_number = '".$PSaClientCode."'";
														 
								$result = selectData($connection, $query);
								$vCltTax1 = $result[0];
								$vCltTax2 = $result[1];
								$vCltTax3 = $result[2];
								$vCltTax4 = $result[3];
								$vCltTax5 = $result[4];
												
								$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
										 " FROM Items ".
										 " WHERE Item_Code = '".$vItemCode."'";
														 
								$result = selectData($connection, $query);

									
								if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
								if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
								if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
								if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
								if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
										
							}		
								
								
							
						} //End if ($Module_Delivery == 0) 
							
							
						// Get DirectStock Accounts
						$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
								 " 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];	
						$vSaStpPromoAcc     = $result[6];
						$vSaStpTipsAcc      = $result[7];
						
						$vSaStpCreditNonStockAcc    = $result[8];
						$vSaStpCreditVatNonStockAcc = $result[9];
						$vSaStpVatAcc 		  	  	= $result[10];
						$vSaStpVatNonStockAcc 	  	= $result[11];
						$vSaStpVatAccCash	  	  	= $result[12];
						$vSaStpVatNonStockAccCash 	= $result[13];
									
								
						$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
								 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc ".
								 " 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];
						$vTranStpPromoAcc        = $result[11]; 
						$vTranStpTipsAcc         = $result[12];
									
						if ($Module_RawMaterial == 1) {
							$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vSaDtDirectStkCur = $vTranStpDirectStkCur;
							$vSaDtVatAcc       = $vTranStpVatAcc;
							$vSaDtDiscAcc      = $vTranStpDiscAcc;
							$vSaDtPromoAcc     = $vTranStpPromoAcc;
							$vSaDtTipsAcc      = $vTranStpTipsAcc;
										
							if ($item_vat > 0 && $PSaVatChkbx == 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;		
							//$vSaDtVatAcc       = $vSaStpVatAcc;
							$vSaDtDiscAcc      = $vSaStpDiscAcc;
							$vSaDtPromoAcc     = $vSaStpPromoAcc;
							$vSaDtTipsAcc      = $vSaStpTipsAcc;
								
							if ($item_vat > 0 && $PSaVatChkbx == 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;
							//}	
						}
							
						$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				 
						$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
						$result_cost = selectData($connection, $query_cost);
						
						
						$vSaDtCostBase1  = $result_cost[0];
						$vSaDtCostBase2  = $result_cost[1];
						$vSaDtCost=ConvertCurrency($Base1, $PSaCurr, insertMySQLDate($PSaDate), $$vSaDtCostBase1, $connection);
						if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
						if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
						
						
						
						//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
						fbegin();
						$vSaDtId = get_nextsequence('deliverydt_id','',$connection);
						fcommit();
								
						fbegin();		
						$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
								 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, ".
								 " Item_QtyPacked, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_heatno ) ".
								 " VALUES ( ".$vSaDtId.", ".$PSaId.", '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', 'DI', '".ereg_replace("'", "\'", trim($PSaClientCode))."',  ".
								 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".trim(strtoupper($vItemCode))."', '".$vItemCodePacked."', $vSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $txtSaDtDiscount, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
								 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
								 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $vPackDtPromo, $vSaDtCost,  ".
								 "          $vSaDtCostBase1, $vSaDtCostBase2, $vPackDtQty, $vSaDtExpireDate, '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."','$deliverydt_heatno' ) ";
						 
						$result=mysql_query($query,$connection);
										
						//echo $query;
					
				} // End Loop Of Packdt
				
					
				if ($result){
					fcommit();
				}else{
					$txtSaDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
				
			} else{
				$txtSaDtId = "";
				$ErrorExists = 1;
				
				if ($promo_exhausted == 1)
					$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty / Period Exhausted";
				else if ($QtyExistExceeded == 1)
					$message = "Qty[".abs($vSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")";
					
				frollback();
			}
			
		} // End CasePack Item
		
		
		
		
		
		
		/////// end detail table
		$x=$x+1;
		}
		
	
	}
	if ($ErrorExists == 0 && $Module_Delivery == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SSaId, $PSaDate, $PSaVatChkbx, $PSaDiscount, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}	


}
else
if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	
	if ($delivery_export=='')
	   $delivery_export = 0;
	if ($txthscode == '') $txthscode = "NULL";
	else $txthscode = "'".$txthscode."'";
	
	if ($txtnumber_boxes == '') $txtnumber_boxes = 0;					
	if ($txtgrossweight == '') $txtgrossweight = 0;					
	if ($txtnetweight == '') $txtnetweight = 0;					

	if ($delivery_cashType=='')
	   $delivery_cashType = "NULL";
	else $delivery_cashType = "'".$delivery_cashType."'";
		
	if ($txtdestdate == '') $txtdestdate = "NULL";
	else $txtdestdate = "'".insertMySQLDate($PSaMaturityDate)."'";
			
	
	if (!isset($PSaCurr))
	   $PSaCurr = $base1;

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSaCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSaCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	// adding message restriction on transactionsetup //01.10.2020
	if (trim(strtoupper($txtItemCode)) != '') {
		$sub_query = "select count(*) From transactionsetup where group_code = (select group_code from items where upper(item_code) = '".strtoupper($txtItemCode)."' ) and journal_type = 'SI'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Group Setup .';
		}
	}
	
	if ($PSaProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSaProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PSaClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSaClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	if ($PSaSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSaSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Salesman Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".trim(strtoupper($txtItemCode))."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	
	//Insert Master Table
	if ($SSaId == "" && $ErrorExists == 0){
	
		if (empty($PSaDiscountAmt))
			$PSaDiscountAmt = 0;
		if (empty($PSaDiscount))
			$PSaDiscount = 0;
		
		$PSaCostCentCode = "".$PSaCostCentCode;	
		if ($PSaCostCentCode == '')
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSaCostCentCode."'";
		
		$PSaProjectCode = "".$PSaProjectCode;
		if ($PSaProjectCode == '')
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSaProjectCode."'";
			
		fbegin();	
		$PSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
		$result = selectData($connection, $query);
		$PSaVatChkbx = $result[0];
		if($costcent_applyvat==0) $PSaVatChkbx=0;
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
					 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount, BonusAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			 
		fbegin();
		
		if (empty($PSaVehicleLoadWeight))   $PSaVehicleLoadWeight = 0;
		if (empty($PSaVehicleWeight))   $PSaVehicleWeight = 0;
		$delivery_date         = $_GET['delivery_date'];
		$delivery_card_msg     = $_GET['delivery_card_msg'];
		$delivery_contact      = $_GET['delivery_contact'];
		$delivery_contactphone = $_GET['delivery_contactphone'];
		if($delivery_date == '') $delivery_date = $PSaDate;
		
		//echo $delivery_date."<br>".$delivery_card_msg."<br>".$delivery_contact."<br>".$delivery_contactphone; exit;
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
				 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
				 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
				 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, Delivery_BonusAccount, Delivery_ManualNo,Delivery_vehicleweight,Delivery_vehicleLoadweight, ".
				 " User_Account, Logged_Code,Delivery_Export, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone,GRNNO, delivery_cashType, ".
				 " delivery_HScode, Delivery_NoCarton, Delivery_CartonGrossWt, Delivery_CartonNetWeight, deliveries_destinationFrom, deliveries_destinationTo, deliveries_destinationDate) ".
				 " VALUES ( ".$PSaId.", Null, '".insertMySQLDate($PSaDate)."', '".insertMySQLDate($PSaMaturityDate)."' , ".
				 "          '".ereg_replace("'", "\'", trim($PSaRemark))."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', '".ereg_replace("'", "\'", trim($PSaDAddress))."', '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaDriverName))."', '".ereg_replace("'", "\'", trim($PSaSalesmanCode))."', '".$PSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
				 "          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PSaVatChkbx, '".$Acc_Result[12]."'".
				 "          , '".ereg_replace("'", "\'", trim($PSaManualNo))."', $PSaVehicleWeight, $PSaVehicleLoadWeight, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',$delivery_export, '".insertMySQLDate($delivery_date)."', '".$delivery_card_msg."', '".$delivery_contact."', ".
				 " '".$delivery_contactphone."','".$grnno."', ".$delivery_cashType.", ".
				 " $txthscode, $txtnumber_boxes, $txtgrossweight, $txtnetweight, ".GetSQLValueString($txtdestfrom,'text').", ".GetSQLValueString($txtdestto,'text').", ".$txtdestdate.")";
		
		$result=mysql_query($query,$connection);
		
		
		
		if ($result){
			$SSaId = $PSaId;
			fcommit();
		}else{
			$PSaId = "";
			$SSaId = "";
			$ErrorExists == 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SSaId != "" && $SSaDtId == "" && $txtItemCode != "" && $ErrorExists == 0){
	
		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($txtSaDtPacking))		   $txtSaDtPacking = 0;    
		if (empty($txtSaDtnbrUnit))		   $txtSaDtnbrUnit = 0;    		
		
		if($txtSaDtnetweight == '')	 		$txtSaDtnetweight = 0;
		if(!is_numeric($txtSaDtnetweight)) $txtSaDtnetweight = 0;
		if (empty($txtSaDtExpireDate))		$vSaDtExpireDate = 'Null';
		else  $vSaDtExpireDate = "'".insertMySQLDate($txtSaDtExpireDate)."'"; 

		if (empty($txtSaDtExpireDate))		$vSaDtExpireDate = 'Null';
		else  $vSaDtExpireDate = "'".insertMySQLDate($txtSaDtExpireDate)."'"; 
		
		if (empty($destdate))		$destdate = 'Null';
		else  $destdate = "'".insertMySQLDate($destdate)."'"; 
		
				
		if (empty($deliverydt_quantitybox))
				$deliverydt_quantitybox = 0;      	  
			
		if (empty($deliverydt_itemunit))
			$deliverydt_itemunit = 0;      	  
		
		if (empty($deliverydt_itempackage))
			$deliverydt_itempackage = 0;      	  
					
		$PSaCostCentCode = "".$PSaCostCentCode;			
		if ($PSaCostCentCode == '')
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSaCostCentCode."'";
		
		$PSaProjectCode = "".$PSaProjectCode;			
		if ($PSaProjectCode == '')
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSaProjectCode."'";	
		
		$txtProjectCodeDt = "".$txtProjectCodeDt;	
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	
		
		
	
		$WarningMsg = '';
		
		$vSaDtPriceTTC      = 0;
		$vSaDtPriceTTCBase1 = 0;
		$vSaDtPriceTTCBase2 = 0;					
		$vSaDtPrice         = 0;
		$vSaDtPriceBase1    = 0;
		$vSaDtPriceBase2    = 0;
		$vSaDtCostBase1     = 0;
		$vSaDtCostBase2     = 0;
		$vSaDtDiscAmt       = 0;
		$vSaDtDiscAmtBase1  = 0;
		$vSaDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSaDtTax1 = 0;
		$vSaDtTax2 = 0;
		$vSaDtTax3 = 0;
		$vSaDtTax4 = 0;
		$vSaDtTax5 = 0;
		
		$QtyExistExceeded   = 0;
		$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;
				$ErrorExists =1;
				$message = "Price should be greater than or equal to $min_price";
			}		
		}
		
		
		
		// echo "reached HERE!!!";
		// meancost < sellingPrice stop UserAccount JP
		$checkPrice = 1;
		if($FI_SalebelowCost == 0){
			 // echo "<BR>".
			$querycst = "select meancostcur(item_code,now(),1,'$base1','$base1')  from items where item_code='$txtItemCode'";
			$rescst = mysql_query($querycst,$connection);
			$rowcst = mysql_fetch_row($rescst);
			if($rowcst[0] == '') $rowcst[0] = 0;
			$txtItemPrice = $txtSaDtPrice;
			if($txtItemPrice == ''){
				 // echo "<BR>".
				$querySP = "select Item_SellingPrice1Base1  from items where item_code='$txtItemCode' ";
				$resSP = mysql_query($querySP,$connection);
				$rowSP = mysql_fetch_row($resSP);
				if($rowSP[0] != '') $txtItemPrice = $rowSP[0];
				else if($rowSP[0] != '') $txtItemPrice = '';
				
				if($txtItemPrice == '') $checkPrice = 0;
			}
			// echo "<br>txtItemPrice : ".$txtItemPrice;
			// echo "<br>rowcst : ".$rowcst[0];
			// echo "<br>checkPrice : ".$checkPrice;
			if(($txtItemPrice < $rowcst[0] || $txtItemPrice == 0) && $checkPrice == 1){
				$ErrorExists = 1;
				$InsertAllow = 0;
				 // echo "<BR>".
				 $message = "insert not Allowed Price should be above Cost!";
			}	
			
			// $message =  'insert not Allowed Price below Cost !';
		}
		
		// exit;
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		$query = "SELECT ifNull(Delivery_Mode,0) FROM Deliveries WHERE Delivery_id = ".$SSaId;
		$result = selectData($connection, $query);
		$vSaPayMode = $result[0];
		

		if($InsertAllow == 1 ){
		// Case Not Pack Item
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
		if ($ItemPack != 1) {
		

			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
			       	" FROM Items WHERE item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'";
			$result = selectData($connection, $query);
			$item_vat 	   = $result[0];
			$Item_MaxQty   = $result[1];
			$ItemGroupCode = $result[2];
			$ItemProd      = $result[3];
			$ItemTTCInc    = $result[4];
			$ItemUnit      = $result[5];
			$ItemPromo     = $result[6];
			$ItemNonStock  = $result[7];
			
			//$item_vat = $item_vat/100;
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				/*if ($ItemUnit > 0) {
					$vItemUnitCoef = 1/$ItemUnit;
					$vItemUnit2Qty = $vItemUnitCoef * $txtSaDtQty;
				}*/
				
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $txtSaDtQty2;
			}
			//fady jp
			//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
			
			if ($ItemNonStock == 0 && $Module_CreateAdjustmentforPack == 0 ) {
				if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "") {
					$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtSaDtBatchNo."', now(), 0, 'DI', '', '') QtyExists From Dual ";
				} else {
					$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', now(), 0, 'DI', '', '') QtyExists From Dual ";
				}
					
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];

				$sub_query1 = " Select ifNull(Sum(ifNull(DeliveryDt_Quantity,0)),0) FROM Temp_DeliveryDt ".
							  " Where Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Delivery_ID = $PSaId And DeliveryDt_ID != ifNull('".$txtSaDtId."',0) ";	
				if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "")
					$sub_query1 = $sub_query1." And	DeliveryDt_BatchNo = '".$txtSaDtBatchNo."' ";
							
				$sub_result1 = selectData($connection, $sub_query1);
				if (empty($sub_result1[0])) $sub_result1[0] = 0;

				$vItemQtyExists = $vItemQtyExists + $sub_result1[0];


				if (abs($txtSaDtQty) > $vItemQtyExists && abs($txtSaDtQty) > 0)
					$QtyExistExceeded = 1;
			}
			//fady
			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1 )) {
			

				if ($Module_Delivery == 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))*$PSaDiscount)/100;
					$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

					if ($Module_AdditionalTaxes == 1) {
					
						// Calculation of Item Tax Amounts
						$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
								 " FROM Clients ".
								 " WHERE Ledger_number = '".$PSaClientCode."'";
											 
						$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 = '".str_replace('\\','\\\\',$txtItemCode)."'";
											 
						$result = selectData($connection, $query);

						
						if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
						if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
						if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
						if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
						if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
							
					}
						
					

				} //End ($Module_Delivery == 0) 	
				
				// Get DirectStock Accounts
				$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
						 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
						 " FROM salessetup ";
								 
				$result = selectData($connection, $query);
						
				$vSaStpDirectStkDbt = $result[0];
				$vSaStpDirectStkCrd = $result[1];
				$vSaStpDirectStkCur = $result[2];	
				$vSaStpDiscAcc      = $result[3];	
				$vSaStpCreditVatAcc = $result[4];	
				$vSaStpCreditAcc    = $result[5];	
				$vSaStpPromoAcc     = $result[6];
				$vSaStpTipsAcc      = $result[7];
				
				$vSaStpCreditNonStockAcc    = $result[8];
				$vSaStpCreditVatNonStockAcc = $result[9];
				$vSaStpVatAcc 		  	  	= $result[10];
				$vSaStpVatNonStockAcc 	  	= $result[11];
				$vSaStpVatAccCash	  	  	= $result[12];
				$vSaStpVatNonStockAccCash 	= $result[13];
				$vSaStpCreditExportAcc	 	= $result[14];
				
				$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".ereg_replace("'", "\'", trim($PSaClientCode))."' ";	
				$resexp = mysql_query($queryexp,$connection);
				$rwexp = mysql_fetch_row($resexp);
				$clientexp = $rwexp[0];
				
				$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = '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];
				$vTranStpPromoAcc        = $result[11]; 
				$vTranStpTipsAcc         = $result[12]; 
				$vTransStpExportAcc 	 = $result[13];
						
				if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					$vSaDtPromoAcc     = $vTranStpPromoAcc;
					$vSaDtTipsAcc      = $vTranStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 1) {
						if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
						}
					}	
					if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 
				} 
				else {
					$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
					$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
					//$vSaDtVatAcc       = $vSaStpVatAcc;
					$vSaDtDiscAcc      = $vSaStpDiscAcc;
					$vSaDtPromoAcc     = $vSaStpPromoAcc;
					$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 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 = $vSaStpCreditExportAcc; 			
				}
							
				$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				$query_cost = " select ifNull(MeanCostCur('".str_replace('\\','\\\\',$txtItemCode)."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".str_replace('\\','\\\\',$txtItemCode)."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				
				$vSaDtCostBase1  = $result_cost[0];
				$vSaDtCostBase2  = $result_cost[1];
				$vSaDtCost=ConvertCurrency($base1, $PSaCurr, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
				//$message = $vSaDtCost;
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				
				//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
				//echo $query_cost; exit;
				
				if (empty($deliverydt_clientdiscount)) $deliverydt_clientdiscount = 0;
				if (empty($deliverydt_itemdiscount)) $deliverydt_itemdiscount = 0;



						
				fbegin();
				$txtSaDtId = get_nextsequence('deliverydt_id','',$connection);	
				fcommit();
		 if($item_vat == "") $item_vat = 0;
				fbegin();
				$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
						 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
						 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
						 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, ".
						 " DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_heatno,deliverydt_quantitybox,deliverydt_itemunit,deliverydt_itempackage,deliverydt_clientdiscount,deliverydt_itemdiscount,
							deliverydt_packingkg,deliverydt_nbrUnit, deliverydt_netweight, Destination_From, Destination_To, Destination_date	) ".
						 " VALUES ( ".$txtSaDtId.", ".$PSaId.", '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', 'DI', '".ereg_replace("'", "\'", trim($PSaClientCode))."',  ".
						 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."', Null, $txtSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $txtSaDtDiscount, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
						 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
						 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $chkSaDtPromo, '$vSaDtCost',  ".
						 "          $vSaDtCostBase1, $vSaDtCostBase2, $vSaDtExpireDate, '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."'
						 , '".$_SESSION['useraccount']."','$deliverydt_heatno',$deliverydt_quantitybox,$deliverydt_itemunit,'$deliverydt_itempackage',$deliverydt_clientdiscount,$deliverydt_itemdiscount,
						 $txtSaDtPacking, $txtSaDtnbrUnit, $txtSaDtnetweight, ".GetSQLValueString($destfrom,'text').", ".GetSQLValueString($destto,'text').", $destdate) ";
				 
				//echo $query."<br>";exit;		
				//$message = $vSaDtCost;
				$result=mysql_query($query,$connection);
			
				if ($result){
					fcommit();
				}else{
					$txtSaDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error($connection); 
					frollback();
				}
					 
			}	
			else {
				//$ErrorExists = 1;
				$message  = "Qty[".abs($txtSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
			}
			
		}	// End Case Not Pack Item
		else {
		
			$promo_display = true;
			$promo_exhausted  = 0;
			$QtyExistExceeded = 0;
			
			$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
						   " FROM PackDt ".
						   " WHERE Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'  ";
								   
			$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
			while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
				$vItemCodePacked = $rowspackdt[0];
				$vItemCode = $rowspackdt[1];
				$vPackDtQty = $rowspackdt[2];
				$vPackDtCostPer = $rowspackdt[3];
				$vPackDtPromo = $rowspackdt[4];
				$vPackDtPromoQty = $rowspackdt[5];
				
				$sub_query = " SELECT ifNull(Item_NonStock,0) FROM Items WHERE Item_Code = '".$vItemCode."'";
				$sub_result = selectData($connection, $sub_query);
				$ItemNonStock    = $sub_result[0];
					
				// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
				if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
					
					if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
						//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
						$sub_query = " Select Sum(ifNull(DeliveryDt_Quantity,0)) ".
									 " From DeliveryDt ".
									 " Inner Join Deliveries on DeliveryDt.Delivery_id = Deliveries.Delivery_id ".
									 " Where DeliveryDt.Item_CodePacked = '".str_replace('\\','\\\\',$txtItemCode)."' ".
									 " And DeliveryDt.Item_Code = '".$vItemCode."' ".
									 " And ifNull(DeliveryDt.Deliverydt_OldData,0) = 0 ".
									 " And Deliveries.Journal_Type = 'DI' ".
									 " And Deliveries.Delivery_Date >= '".$rowspackdt[6]."' and Deliveries.Delivery_Date <= '".$rowspackdt[7]."' ";

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

						if ($vPackDtPromoQty <= ($sub_result[0] + $txtSaDtQty*$vPackDtQty)){
							$promo_exhausted = 1;
						}
					}else{
						$promo_exhausted = 1;
					}
					
					if ($promo_exhausted == 1) break;
				
				}
				
				//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
				if ($ItemNonStock == 0 && $promo_exhausted == 0){
					if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "") {
						$sub_query  = " Select QtyExistsByBatchNo('".$vItemCode."', '".$lstWarehouse."', '".$txtSaDtBatchNo."', now(), 0, 'DI', '', '') QtyExists From Dual ";
					} else {
						$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', now(), 0, 'DI', '', '') QtyExists From Dual ";
					}
						
					$sub_result = selectData($connection, $sub_query);
					$vItemQtyExists = 0;
					$vItemQtyExists = $sub_result[0];

					$sub_query1 = " Select ifNull(Sum(ifNull(DeliveryDt_Quantity,0)),0) FROM Temp_DeliveryDt ".
								  " Where Item_code = '".$vItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Delivery_ID = $PSaId And DeliveryDt_ID != ifNull('".$txtSaDtId."',0) ";	
					if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "")
						$sub_query1 = $sub_query1." And	DeliveryDt_BatchNo = '".$txtSaDtBatchNo."' ";
								
					$sub_result1 = selectData($connection, $sub_query1);
					if (empty($sub_result1[0])) $sub_result1[0] = 0;

					$vItemQtyExists = $vItemQtyExists + $sub_result1[0];
					$vSaDtQty      = $txtSaDtQty*$vPackDtQty;

					if (abs($vSaDtQty) > $vItemQtyExists && abs($vSaDtQty) > 0) {
						$QtyExistExceeded = 1;
						Break;
					}
				}
				
				
			}		
			
			//fady		
			if ($promo_exhausted == 0 && ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1  ))){
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'  ";
								   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
					

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

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

						if ($Module_Delivery == 0) {	
							if ($SalesTTC == 1) {
								$vSaDtPriceTTC      = (($txtSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$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 = $vSaDtPriceTTC;								
										
								//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
							} else	{
								$vSaDtPrice      = (($txtSaDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
								$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
										
								$vSaDtPriceTTC      = 0;
								$vSaDtPriceTTCBase1 = 0;
								$vSaDtPriceTTCBase2 = 0;
										
							}
									
								
							// Calculation For Detail Discount Amount
							if($show_discountAmount == 1) $vSaDtDiscAmt       = $txtSaDtDiscountAmt;	
							else
							$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$txtSaDtDiscount/100))*$PSaDiscount)/100;
							$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
							$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

							if ($Module_AdditionalTaxes == 1) {
								
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
										 " FROM Clients ".
										 " WHERE Ledger_number = '".$PSaClientCode."'";
														 
								$result = selectData($connection, $query);
								$vCltTax1 = $result[0];
								$vCltTax2 = $result[1];
								$vCltTax3 = $result[2];
								$vCltTax4 = $result[3];
								$vCltTax5 = $result[4];
												
								$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
										 " FROM Items ".
										 " WHERE Item_Code = '".$vItemCode."'";
														 
								$result = selectData($connection, $query);

									
								if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
								if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
								if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
								if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
								if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
										
							}		
								
								
							
						} //End if ($Module_Delivery == 0) 
							
							
						// Get DirectStock Accounts
						$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
								 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
								 " FROM salessetup ";
										 
						$result = selectData($connection, $query);
									
						$vSaStpDirectStkDbt = $result[0];
						$vSaStpDirectStkCrd = $result[1];
						$vSaStpDirectStkCur = $result[2];	
						$vSaStpDiscAcc      = $result[3];	
						$vSaStpCreditVatAcc = $result[4];	
						$vSaStpCreditAcc    = $result[5];	
						$vSaStpPromoAcc     = $result[6];
						$vSaStpTipsAcc      = $result[7];
						
						$vSaStpCreditNonStockAcc    = $result[8];
						$vSaStpCreditVatNonStockAcc = $result[9];
						$vSaStpVatAcc 		  	  	= $result[10];
						$vSaStpVatNonStockAcc 	  	= $result[11];
						$vSaStpVatAccCash	  	  	= $result[12];
						$vSaStpVatNonStockAccCash 	= $result[13];
						$vSaStpCreditExportAcc	 	= $result[14];

						$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".ereg_replace("'", "\'", trim($PSaClientCode))."' ";	
						$resexp = mysql_query($queryexp,$connection);
						$rwexp = mysql_fetch_row($resexp);
						$clientexp = $rwexp[0];
		
						$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
								 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc,trans_export ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = '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];
						$vTranStpPromoAcc        = $result[11]; 
						$vTranStpTipsAcc         = $result[12];
						$vTransStpExportAcc 	 = $result[13];
						
						if ($Module_RawMaterial == 1) {
							$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vSaDtDirectStkCur = $vTranStpDirectStkCur;
							$vSaDtVatAcc       = $vTranStpVatAcc;
							$vSaDtDiscAcc      = $vTranStpDiscAcc;
							$vSaDtPromoAcc     = $vTranStpPromoAcc;
							$vSaDtTipsAcc      = $vTranStpTipsAcc;
										
							if ($item_vat > 0 && $PSaVatChkbx == 1) {
								if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
							}
							else {
								if ($ItemProd == 1) {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
								}	
								else {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
								}
							}
							if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 							
						} 
						else {
							$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
							$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
							//$vSaDtVatAcc       = $vSaStpVatAcc;
							$vSaDtDiscAcc      = $vSaStpDiscAcc;
							$vSaDtPromoAcc     = $vSaStpPromoAcc;
							$vSaDtTipsAcc      = $vSaStpTipsAcc;
								
							if ($item_vat > 0 && $PSaVatChkbx == 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 = $vSaStpCreditExportAcc;
						}

											
						$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				 
						$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$vItemCode."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
						$result_cost = selectData($connection, $query_cost);
						
						
						
						$vSaDtCostBase1  = $result_cost[0];
						$vSaDtCostBase2  = $result_cost[1];
						$vSaDtCost=ConvertCurrency($Base1, $PSaCurr, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
						
						if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
						if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
						
						//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);
						
						fbegin();
						$vSaDtId = get_nextsequence('deliverydt_id','',$connection);
						fcommit();
								
				  
						fbegin();		
						$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
								 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, ".
								 " Item_QtyPacked, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code ,deliverydt_heatno, deliverydt_netweight, ".
								 " Destination_From, Destination_To, Destination_date) ".
								 " VALUES ( ".$vSaDtId.", ".$PSaId.", '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', 'DI', '".ereg_replace("'", "\'", trim($PSaClientCode))."',  ".
								 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".trim(strtoupper($vItemCode))."', '".$vItemCodePacked."', $vSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $txtSaDtDiscount, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, $item_vat, ".
								 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', ".
								 "          '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $vPackDtPromo, $vSaDtCost,  ".
								 "          $vSaDtCostBase1, $vSaDtCostBase2, $vPackDtQty, $vSaDtExpireDate, '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', ".
								 " '$deliverydt_heatno', $txtSaDtnetweight, ".GetSQLValueString($destfrom,'text').", ".GetSQLValueString($destto,'text').", $destdate ) ";
						//echo $query;exit; 
						$result=mysql_query($query,$connection);
										
						
					
				} // End Loop Of Packdt
				
					
				if ($result){
					fcommit();
				}else{
					$txtSaDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
				
			} else{
				$txtSaDtId = "";
				$ErrorExists = 1;
				
				if ($promo_exhausted == 1)
					$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty / Period Exhausted";
				else if ($QtyExistExceeded == 1)
					$message = "Qty[".abs($vSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")";
					
				frollback();
			}
			
		} // End CasePack Item
		
		}
		if ($ErrorExists == 0 && $Module_Delivery == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SSaId, $PSaDate, $PSaVatChkbx, $PSaDiscount, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
		
	} // End Case Insert In Detail Tables
	

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

	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".trim(strtoupper($txtItemCode))."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	
	$txtProjectCodeDt = "".$txtProjectCodeDt;
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	if($costcentminimum == 1 && $txtCostCentCodeDt != ''){
			$query = "select ifnull(min(min_price),0) from costcenterPrice where costcenter_code = $txtCostCentCodeDt 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;
				$ErrorExists =1;
				$message = "Price should be greater than or equal to $min_price";
			}		
		}
	if ($SSaId != "" && $SSaDtId != "" && $ErrorExists == 0) {
		
		if ($txthscode == '') $txthscode = "NULL";
		else $txthscode = "'".$txthscode."'";
	
		if ($txtnumber_boxes == '') 	$txtnumber_boxes = 0;					
		if ($txtgrossweight == '') 		$txtgrossweight = 0;					
		if ($txtnetweight == '') 		$txtnetweight = 0;	
		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($txtSaDtCloseQty))   $txtSaDtCloseQty = 0;     
		if (empty($chkSaDtPromo))	   $chkSaDtPromo = 0;
		
		if (empty($txtSaDtPacking))		$txtSaDtPacking = 0;   
		if (empty($txtSaDtnbrUnit))		$txtSaDtnbrUnit = 0;   

		if (empty($txtSaDtExpireDate))	$vSaDtExpireDate = 'Null';
		else  $vSaDtExpireDate = "'".insertMySQLDate($txtSaDtExpireDate)."'";  
		
		if (empty($destdate))		$destdate = 'Null';
		else  $destdate = "'".insertMySQLDate($destdate)."'"; 
		
		$txtProjectCodeDt = "".$txtProjectCodeDt;
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if($txtSaDtnetweight == '') 	$txtSaDtnetweight = 0;
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}
				
		$query = "SELECT Item_Vat, ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0), ifNull(Item_WithSerialNo,0) FROM Items WHERE item_Code = '".str_replace('\\','\\\\',$txtItemCode)."'";
		$result = selectData($connection, $query);
		$item_vat  	  = $result[0];
		$ItemPromo 	  = $result[1];
		$ItemNonStock = $result[2];
		$ItemSerialNo = $result[3];
		//$item_vat = $item_vat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
			
		$QtyExistExceeded   = 0;
		
		//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
		if ($ItemNonStock == 0) {
			if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "") {
				$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtSaDtBatchNo."', now(), 0, 'DI', '', '') QtyExists From Dual ";
			} else {
				$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', now(), 0, 'DI', '', '') QtyExists From Dual ";
			}
					
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];

			$sub_query1 = " Select ifNull(Sum(ifNull(DeliveryDt_Quantity,0)),0) FROM Temp_DeliveryDt ".
						  " Where Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Delivery_ID = $PSaId And DeliveryDt_ID != ifNull('".$txtSaDtId."',0) ";	
			if ($Module_ExpireDate == 1 && $txtSaDtBatchNo != "")
				$sub_query1 = $sub_query1." And	DeliveryDt_BatchNo = '".$txtSaDtBatchNo."' ";
							
			$sub_result1 = selectData($connection, $sub_query1);
			if (empty($sub_result1[0])) $sub_result1[0] = 0;

			$vItemQtyExists = $vItemQtyExists + $sub_result1[0];


			if (abs($txtSaDtQty) > $vItemQtyExists && abs($txtSaDtQty) > 0)
				$QtyExistExceeded = 1;
		}
		//	
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty== 1 )) {
			
			$WarningMsg  = '';
			$vSaDtTotal  = 0;
			$vSaCltCode  = '';
			$vSaDiscount = 0;
			$vItemVat    = 0;
			$vSaQty      = 0;

			
			$vSaDtPriceTTC      = 0;
			$vSaDtPriceTTCBase1 = 0;
			$vSaDtPriceTTCBase2 = 0;					
			$vSaDtPrice      	= 0;
			$vSaDtPriceBase1 	= 0;
			$vSaDtPriceBase2 	= 0;
			$vSaDtDiscAmt       = 0;
			$vSaDtDiscAmtBase1  = 0;
			$vSaDtDiscAmtBase2  = 0;

			if ($Module_Delivery == 0) {
				$query = " Select Currency_code, ifNull(Delivery_Taxable,0), ifNull(Delivery_NoneTaxable,0), ifNull(Delivery_DiscountPer,0), Client_code ".
						 " From Temp_Deliveries As Deliveries ".
						 " Where Delivery_ID = ".$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 || $chkSaDtPromo == 1) $txtSaDtPrice = 0;
				
				if ($SalesTTC == 1) {
					$vSaDtPriceTTC      = $txtSaDtPrice;
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

					//Added 2011/09/24
					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*$vSaDtDiscPer/100))*$vSaDiscount)/100;
				$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;		
				

			} //End if ($Module_Delivery == 0) 

			
			
			//Edit Item Code/Warehouse Check If Item Is Sold
			$SalesExists = 0;
			if ($Module_Delivery == 1) {
				$sub_query = " Select Count(*) From SalesDt ".
							 " Where SalesDt.RelatedDt_Id = '".$SSaDtId."' ".
							 " And SalesDt.Journal_Type = 'SI' ";
				$sub_result = selectData($connection, $sub_query);
				$SalesExists = $sub_result[0];
			}	
			
	
		if (empty($deliverydt_quantitybox))
				$deliverydt_quantitybox = 0;      	  
			
			if (empty($deliverydt_itemunit))
				$deliverydt_itemunit = 0;      	  
			
			if (empty($deliverydt_itempackage))
				$deliverydt_itempackage = 0;    
				
			if ($deliverydt_clientdiscount=='')
				$deliverydt_clientdiscount = 0; 
				
			if ($deliverydt_itemdiscount=='')
				$deliverydt_itemdiscount = 0;      	  

			fbegin();
			$query = " UPDATE temp_deliverydt SET ".
					 " DeliveryDt_Quantity = $txtSaDtQty, Item_Unit2Qty = $txtSaDtQty2, DeliveryDt_Price = $vSaDtPrice, DeliveryDt_PriceBase1 = $vSaDtPriceBase1, ".
					 " DeliveryDt_PriceBase2 = $vSaDtPriceBase2, DeliveryDt_DiscountPer = $txtSaDtDiscount, DeliveryDt_PriceTTC = $vSaDtPriceTTC, Deliverydt_priceTTCBase1 = $vSaDtPriceTTCBase1, ".
					 " Deliverydt_priceTTCBase2 = $vSaDtPriceTTCBase2, Item_VAT = $item_vat, DeliveryDt_Remark = '".ereg_replace("'", "\'", trim($txtSaDtRemark))."', ".
					 " Deliverydt_DiscountAmount = $vSaDtDiscAmt, Deliverydt_DiscountBase1 = $vSaDtDiscAmtBase1, Deliverydt_DiscountBase2 = $vSaDtDiscAmtBase2, DeliveryDt_ClosingQuantity =  $txtSaDtCloseQty, ".
					 " DeliveryDt_ExpireDate = $vSaDtExpireDate, DeliveryDt_BatchNo = '".ereg_replace("'", "\'", trim($txtSaDtBatchNo))."', Deliverydt_promotion = $chkSaDtPromo , deliverydt_heatno = '".$deliverydt_heatno."' 
					 , deliverydt_quantitybox=$deliverydt_quantitybox, deliverydt_itemunit=$deliverydt_itemunit
					 , deliverydt_itempackage='$deliverydt_itempackage'
					 , currency_code='$vSaCurr'
					 , deliverydt_clientdiscount='$deliverydt_clientdiscount'
					 , deliverydt_itemdiscount='$deliverydt_itemdiscount'
					 , deliverydt_packingkg = $txtSaDtPacking
					 , deliverydt_nbrUnit = $txtSaDtnbrUnit
					 , deliverydt_netweight = $txtSaDtnetweight
					 , Destination_From = ".GetSQLValueString($destfrom,'text')."
					 , Destination_To = ".GetSQLValueString($destto,'text')."
					 , Destination_date = $destdate ";
			//echo $query;
            //exit;			
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCent_Code = $CostCentCodeDt ";
				
			//Edit Item Code/Warehouse If Item Is Not Sold
			if ($SalesExists == 0 && ($Module_SerialNo == 0 || $ItemSerialNo == 0))
				$query = $query.", Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."' ";
			
			$query = $query." Where DeliveryDt_ID = ".$SSaDtId;
		
						 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
			
			if ( $result ){ 
				fcommit();
				
				if ($Module_Delivery == 0) {
					//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();
			}
		}
		else {
			//$ErrorExists = 1;
			$message  = "Qty[".abs($txtSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
		}		
	}
} 
	

else if ($mode == "checkduplicate" ){

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


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

	$result=mysql_query($query, $connection) or die(mysql_error());
	$row=mysql_fetch_array($result);
	echo $row[0];
	echo "[BRK]";
	echo $disc;
	echo "[BRK]";
	echo $client_discountonInvoice;
	echo "[BRK]";
	echo $Client_PaymentTerms;
	exit;
}
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	//Check Each DeliveryDt If Has RelatedId and Type DR
	$query = " Select Count(DeliveryDt.DeliveryDt_id), Deliveries.Delivery_reference ".
			 " From DeliveryDt, DeliveryDt As DeliveryDt1, Deliveries ".
			 " Where DeliveryDt.DeliveryDt_ID = ".$SSaDtId.
			 " And DeliveryDt1.Journal_Type = 'DR' ".
			 " And DeliveryDt1.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
			 " And DeliveryDt1.Delivery_id = Deliveries.Delivery_id ".
			 " 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 DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.DeliveryDt_ID = ".$SSaDtId.
				 " And SalesDt.Journal_Type = 'SI' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SaSalesExists = $result[0];
		
		if (empty($SaSalesExists)) $SaSalesExists = 0;
		
		if ($SaSalesExists > 0 ){
			$message  = 'Delete not allowed, item sold.';
			$AllowDelete = 1;
		}
	
	}
	
	if ($AllowDelete == 0) {
		//Check Each DeliveryDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_DeliveryDt As DeliveryDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = DeliveryDt.DeliveryDt_Id ".
				 " Where DeliveryDt.DeliveryDt_ID = ".$SSaDtId.
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'DI' ";
 
		$result = selectData($connection, $query);
		$SaSerNoUsedExists = $result[0];
		
		if ($SaSerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$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;
		
				
		/*if ($FI_DeliverySalesPrice == 1) $vChkSaVat = $chkSaVat;
		else $vChkSaVat = $txtClientVat;
		
		$sub_query = " Select if(ifNull(Delivery_VAT,0) > 0, 1, 0) ".
					 " From Temp_Deliveries As Deliveries ".
				     " Where Delivery_ID = ".$SSaId;
		$sub_result = selectData($connection, $sub_query);
		$vChkSaVat = $sub_result[0];*/
		
		
		
		$querypack = " SELECT DeliveryDt.Item_CodePacked, DeliveryDt.Item_code ".
					 " FROM Temp_DeliveryDt As DeliveryDt ".
					 " Where DeliveryDt.DeliveryDt_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 = 'DI' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error($connection); 
				
			
			// Delete From TempDeliveryDt For Selected Record
			$query = " DELETE FROM Temp_DeliveryDt ".
					 " WHERE DeliveryDt_id = ".$SSaDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error($connection);
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
			
			
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select DeliveryDt_ID, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code  ".
					   " From Temp_DeliveryDt As DeliveryDt  ".
					   " Where DeliveryDt.Delivery_ID = ".$SSaId.
					   " And DeliveryDt.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 = 'DI' ";
						//" And Logged_Code = '".$_SESSION['useraccount']."' ";
						
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error($connection); 		
						
				// Delete From TempDeliveryDt For Selected Record
				$query = " DELETE FROM Temp_DeliveryDt ".
						 " WHERE DeliveryDt_id = ".$vSaDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error($connection); 
					$ErrorExists = 1;
					frollback();
				}	
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
			
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 && $Module_Delivery == 0){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($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 Constraints Found On Delete
	
	$txtSaId = $SSaId;
}

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

	$AllowDelete = 0;
	$message  = '';
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	
	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(Delivery_Date,'%d/%m/%Y') FROM Deliveries WHERE Delivery_id = ".$SSaId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
		if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
	
	//Check If Sales Is Posted
	$query = "SELECT ifNull(Delivery_Posted,0) As DeliveryPosted, Sorder_Reference, ifNull(Delivery_Mode,0) FROM Deliveries WHERE Delivery_id = ".$SSaId;
	$result = selectData($connection, $query);
	$SaPosted  = $result[0];
	$SorderRef = $result[1];
	$vSaleMode = $result[2];
	
	if ($SaPosted == 1 ){
		$message  = 'Delete not allowed, delivery posted.';
		$AllowDelete = 1;
	}
	
	if ($AllowDelete == 0) {
		//Check Each DeliveryDt If Has RelatedId and Type DR
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Deliveries.Delivery_reference ".
				 " From DeliveryDt, DeliveryDt As DeliveryDt1, Deliveries ".
				 " Where DeliveryDt.Delivery_ID = ".$SSaId.
				 " And DeliveryDt1.Journal_Type = 'DR' ".
				 " And DeliveryDt1.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And DeliveryDt1.Delivery_id = Deliveries.Delivery_id ".
				 " Group By Deliveries.Delivery_reference ";

		$result = selectData($connection, $query);
		$SaReturnExists = $result[0];
			
		if ($SaReturnExists > 0 ){
			$message  = 'Delete not allowed, return delivery exists reference= '.$result[1];
			$AllowDelete = 1;
		}
	}	
	
	if ($AllowDelete == 0) {
		//Check Each DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.Delivery_ID = ".$SSaId.
				 " And SalesDt.Journal_Type = 'SI' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SaSalesExists = $result[0];
		
		if ($SaSalesExists > 0 ){
			$message  = 'Delete not allowed, item(s) sold.';
			$AllowDelete = 1;
		}
	
	}
		
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
	
		$sub_query = " Select Journal_Id From Deliveries Where Delivery_id = ".$SSaId;
		$sub_result = selectData($connection, $sub_query);
		$vSaJournalID = $sub_result[0];
		if(empty($vSaJournalID)) $vSaJournalID = -1;
		
		
		//Update Used Serials Set USed=0 For Related Delivery Serials
		$sub_query = " SELECT RelatedSerial_Id FROM Purchasesserialno ".
					 " WHERE PurchaseDt_id In (Select DeliveryDt_id From DeliveryDt Where Delivery_id = ".$SSaId." ) ".
					 " AND Journal_Type = 'DI' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
		
			$sub_query1 = " UPDATE purchasesserialno ".
						  " Set SerialNo_Used = 0 ".
						  "	WHERE Serial_ID = '".$sub_rows[0]."'";
						  
			if (!updateData($connection, $sub_query1, true))		 
				$message  = mysql_error(); 		  
		}	
				
		
		
		
		// Delete From PurchasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE PurchaseDt_id In (Select DeliveryDt_id From DeliveryDt Where Delivery_id = ".$SSaId." ) ".
				 " AND Journal_Type = 'DI' ";
				 
		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']."', 'deliveries', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		// Delete From DeliveryDt For Selected Record
		$query = " DELETE FROM DeliveryDt ".
				 " WHERE Delivery_id = ".$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 Deliveries For Selected Record
			
			$query = " DELETE FROM Deliveries ".
					 " WHERE Delivery_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(); 	

			}
			
			if ($SorderRef != '') {
			    $query = " Update Sorder Set Sorder_Status = 0 Where Sorder_reference = '".$SorderRef."'";
				
				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 DeliveryDt_id From Temp_DeliveryDt Where Delivery_id = ".$SSaId." ) ".
			 " AND Journal_Type = 'DI' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 

		
	// Delete From TempDeliveryDt For Selected Record
	$query = " DELETE FROM Temp_DeliveryDt ".
			 " WHERE Delivery_id = ".$SSaId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempDeliveries For Selected Record
		$query = " DELETE FROM Temp_Deliveries ".
				 " WHERE Delivery_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 != ''){
	
	$AllowEdit = 1;
	$message  = '';
	
	if ($AllowEdit == 1 && $FI_AllowEditIfDelivered == 0 && $Module_Delivery == 1) {
		//Check Each DeliveryDt If Has RelatedId In SalesDt 
		$query = " Select Count(DeliveryDt.DeliveryDt_id), Sales.Sale_reference ".
				 " From DeliveryDt, SalesDt, Sales ".
				 " Where DeliveryDt.Delivery_ID = ".$SSaId.
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " And SalesDt.Journal_Type = 'SI' ".
				 " And SalesDt.RelatedDt_Id = DeliveryDt.DeliveryDt_id ".
				 " And SalesDt.Sale_id = Sales.Sale_id ".
				 " Group By Sales.Sale_reference ";

		$result = selectData($connection, $query);
		$SalesExists = $result[0];
		
		if ($SalesExists > 0 ){
			$message  = 'Edit not allowed, item(s) sold.';
			$AllowEdit = 0;
		}
	
	}

	if ($AllowEdit == 1) {
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
				 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
				 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
				 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
				 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
				 " Delivery_SorderReferences, Detail_Code, Delivery_VatChkbx, Delivery_TransportTTC, Delivery_BonusAccount, Delivery_BonusAmount, Delivery_BonusBase1, Delivery_BonusBase2, Delivery_BonusTTC, Delivery_ManualNo, Delivery_vehicleweight, ".
				 " Delivery_vehicleLoadweight, Delivery_CashCur, Delivery_CashAccount, Delivery_Cash, Delivery_CashBase1, Delivery_CashBase2, Delivery_CashInBase1, Delivery_CashOutBase1, Delivery_CashInBase2, Delivery_CashOutBase2, Delivery_TipsBase1, ".
				 " Delivery_TipsAccount, User_Account, Logged_Code,delivery_export,trans_id, totalWeight, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone,GRNNO, delivery_cashType, ".
				 " delivery_HScode, Delivery_NoCarton, Delivery_CartonGrossWt, Delivery_CartonNetWeight, manifest_auto, deliveries_destinationFrom, deliveries_destinationTo, deliveries_destinationDate ) ".
				 " SELECT Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
				 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
				 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
				 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
				 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
				 " Delivery_SorderReferences, Detail_Code, Delivery_VatChkbx, Delivery_TransportTTC, Delivery_BonusAccount, Delivery_BonusAmount, Delivery_BonusBase1, Delivery_BonusBase2, Delivery_BonusTTC, Delivery_ManualNo, Delivery_vehicleweight, ".
				 " Delivery_vehicleLoadweight, Delivery_CashCur, Delivery_CashAccount, Delivery_Cash, Delivery_CashBase1, Delivery_CashBase2, Delivery_CashInBase1, Delivery_CashOutBase1, Delivery_CashInBase2, Delivery_CashOutBase2, Delivery_TipsBase1, ".
				 " Delivery_TipsAccount, User_Account, '".$_SESSION['useraccount']."',delivery_export,trans_id, totalWeight, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone,GRNNO, delivery_cashType, ".
				 " delivery_HScode, Delivery_NoCarton, Delivery_CartonGrossWt, Delivery_CartonNetWeight, manifest_auto, deliveries_destinationFrom, deliveries_destinationTo, deliveries_destinationDate ".
				 " FROM Deliveries ".
				 " WHERE Delivery_id = ".$SSaId;
	//	echo $query; exit;
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 	
	//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
				 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
				 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
				 " Deliverydt_ItemAccount, Deliverydt_discountacc, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, ".
				 " Deliverydt_promotion, RelatedDt_Id, User_Account, Item_UnitCoef, Item_Unit2Qty, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, ".
				 " DeliveryDt_TransportAmountBase2, Item_QtyPacked, DeliveryDt_BonusAmount, DeliveryDt_BonusBase1, DeliveryDt_BonusBase2, DeliveryDt_ClosingQuantity, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, ".
				 " DeliveryDt_VatAccount, Logged_Code,deliverydt_heatno,deliverydt_quantitybox,deliverydt_itemunit,deliverydt_itempackage,deliverydt_clientdiscount,deliverydt_itemdiscount   ".
				 " ,deliverydt_packingkg, deliverydt_nbrUnit, deliverydt_netweight, Destination_From, Destination_To, Destination_date ) ".
				 " SELECT DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
				 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
				 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
				 " Deliverydt_ItemAccount, Deliverydt_discountacc, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, ".
				 " Deliverydt_promotion, RelatedDt_Id, User_Account, Item_UnitCoef, Item_Unit2Qty, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, ".
				 " DeliveryDt_TransportAmountBase2, Item_QtyPacked, DeliveryDt_BonusAmount, DeliveryDt_BonusBase1, DeliveryDt_BonusBase2, DeliveryDt_ClosingQuantity, DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt_TipsAccount, ".
				 " DeliveryDt_VatAccount, '".$_SESSION['useraccount']."',deliverydt_heatno,deliverydt_quantitybox,deliverydt_itemunit,deliverydt_itempackage,deliverydt_clientdiscount,deliverydt_itemdiscount  ".
				 " ,deliverydt_packingkg, deliverydt_nbrUnit, deliverydt_netweight, Destination_From, Destination_To, Destination_date ".
				 " FROM Deliverydt ".
				 " WHERE Delivery_id = ".$SSaId;
		//echo $query; exit;
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 			


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

//Search Confirmed Sorder
else if($mainmode == "confirmedsorder" && $SSaId != ''){


	$qtymessage = '';
	
	$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);	
			 
	$sub_query = "Select Client_code, ifNull(Sorder_VATChckbx,0), Currency_Code From Sorder Where Sorder_ID = '".$SSaId."'";
	$sub_result = selectData($connection, $sub_query);
	$vSorderClient = $sub_result[0];
	$vSorderVatChk = $sub_result[1];
	$vSorderCurr   = $sub_result[2];
	
	$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$vSorderCurr."') As CreditCur, ".
				 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount ".
				 " FROM salessetup ";
	$Acc_Result = selectData($connection, $Acc_Query);
	
	$vSaVatAcc = $Acc_Result[8];
	$sub_queryVat = " SELECT GetVATAccount('".$vSorderClient."','".$vSaVatAcc."') from dual ";
	$sub_resultVat = selectData($connection, $sub_queryVat);
	if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];


	fbegin();	
	$vSaId = get_nextsequence('delivery_id','',$connection);	
	fcommit();
	
	if ($Module_Delivery == 0) {	
	
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
				 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
				 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
				 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
				 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_SorderReferences, Detail_Code, Delivery_TaxableTTC, Delivery_DiscountTTC, Delivery_VatChkbx, Delivery_vehicleweight, ".
				 " Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TransportTTC, User_Account, Logged_Code, Delivery_Export, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone) ".
				 " SELECT $vSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), Sorder_Remark, Sorder.Client_code, Sorder_DeliveryPlace, Sorder_vehicalno,Sorder_drivername, Sorder.Salesman_Code, ".
				 " Sorder.Currency_Code, Sorder.Project_Code, Sorder.Costcent_code, Sorder_Posted, 0, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, ".
				 " if($SalesTTC=1,ifNull(Sorder_DiscountAmount,0)/(1+$Setup_VatPercentage/100),Sorder_DiscountAmount), if($SalesTTC=1,ifNull(Sorder_DiscountBase1,0)/(1+$Setup_VatPercentage/100),Sorder_DiscountBase1), ".
				 " if($SalesTTC=1,ifNull(Sorder_DiscountBase2,0)/(1+$Setup_VatPercentage/100),Sorder_DiscountBase2), Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, (ifNull(Sorder_Taxable,0) + ifNull(Sorder_NoneTaxable,0)), ".
				 " (ifNull(Sorder_TaxableBase1,0) + ifNull(Sorder_NoneTaxableBase1,0)), (ifNull(Sorder_TaxableBase2,0) + ifNull(Sorder_NoneTaxableBase2,0)), ".
				 " 0, Sorder_Paymentmode, 'DI', Null, Sorder_BelongsToGrp, Sorder_tax1, Sorder_tax2, Sorder_tax3, Sorder_tax4, Sorder_tax5, Sorder_tax1base1, Sorder_tax2base1, ".
				 " Sorder_tax3base1, Sorder_tax4base1, Sorder_tax5base1, Sorder_tax1base2, Sorder_tax2base2, Sorder_tax3base2, Sorder_tax4base2, Sorder_tax5base2, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', ".
				 " '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', ".
				 " '".$Acc_Result[5]."', '".$Acc_Result[6]."', 0, 0, 0, Sorder_reference, Sorder.Detail_Code, if($SalesTTC=1,ifNull(Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),0), if($SalesTTC=1,Sorder_DiscountAmount,0), ifNull(Sorder_VATChckbx,0), ".
				 " Sorder_vehicleweight, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',Sorder_Export, Sorder_ClientSorderDate, Sorder_ShippingWay, Sorder_ShipName, Sorder_ClientPhone".
				 " FROM Sorder Inner Join Clients on Sorder.Client_Code = Clients.Ledger_Number ".
				 " WHERE Sorder_id = ".$SSaId;
		//echo "test 1"; exit;
		//echo $query; exit;
	} else {
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
				 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, ".
				 " Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
				 " Delivery_CREDITACC, Delivery_BelongsToGroup, Delivery_SorderReferences, Detail_Code,Delivery_vehicleweight, User_Account, Logged_Code, Delivery_Export, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone) ".
				 " SELECT $vSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), Sorder_Remark, Sorder.Client_code, Sorder_DeliveryPlace, Sorder_vehicalno,Sorder_drivername, Sorder.Salesman_Code, ".
				 " Sorder.Currency_Code, Sorder.Project_Code, Sorder.Costcent_code, Sorder_Posted, 0, 0, Sorder_Paymentmode, 'DI', Null, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', ".
				 " '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', ".
				 " '".$Acc_Result[5]."', '".$Acc_Result[6]."', Sorder_BelongsToGrp, Sorder_reference, Sorder.Detail_Code,Sorder_vehicleweight, Sorder.User_Account, '".$_SESSION['useraccount']."' ,Sorder_Export, Sorder_ClientSorderDate, Sorder_ShippingWay, Sorder_ShipName, Sorder_ClientPhone".
				 " FROM Sorder Inner Join Clients on Sorder.Client_Code = Clients.Ledger_Number ".
				 " WHERE Sorder_id = ".$SSaId;
				 
				 //echo "test 2"; exit;
	}
	
	//echo $query; exit;	
	if (updateData($connection, $query, true))
    {   	
		$vSaDtCostBase1  = 0;
		$vSaDtCostBase2  = 0;
		$vSaTotalWeight  = 0;
		
		$PGeneratedId = $vSaId;
		$sub_query = " SELECT SorderDt_id, Sorderdt.Currency_Code, now(), Sorderdt.Client_Code, Sorderdt.Project_Code, Sorderdt.CostCent_Code, Sorderdt.Warehouse_Code, Sorderdt.Item_code, ".
					 " Sorderdt.Item_CodePacked, ifNull(SorderDt_Quantity,0), ".
					 " ifNull(SorderDt_Price,0), ifNull(SorderDt_PriceBase1,0), ifNull(SroderDt_PriceBase2,0), ifNull(SorderDt_Discount,0), ifNull(SorderDt_DiscountAmount,0), ".
					 " ifNull(SorderDt_DiscountBase1,0), ifNull(SorderDt_DiscountBase2,0), ifNull(Sorderdt.Item_Vat,0), ifNull(SorderDt_PriceTTC,0), SorderDt_Remark, SorderDt_DirectStkDbt, ".
					 " SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, ifNull(Sorderdt.Item_Tax1,0), ifNull(Sorderdt.Item_Tax2,0), ifNull(Sorderdt.Item_Tax3,0), ifNull(Sorderdt.Item_Tax4,0), ".
					 " ifNull(Sorderdt.Item_Tax5,0), ifNull(Sorderdt_posted,0), ifNull(Sorderdt_OldData,0), ifNull(Sorderdt_promotion,0), Sorderdt.Item_UnitCoef, Sorderdt.Item_Unit2Qty, Sorderdt.User_Account, ".
					 " ifNull(item_withserialno,0) As ItemWithSerialNo, ifNull(Item_QtyPacked,0) As Item_QtyPacked, ifNull(SorderDt_TransportAmount,0), ifNull(SorderDt_TransportBase1,0), ifNull(SorderDt_TransportBase2,0), sorderdt_quantitybox, sorderdt_itemunit, sorderdt_itempackage ".
					 " FROM Sorderdt Inner Join Items on Sorderdt.Item_Code = Items.Item_Code ";
					 
		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 SorderDt.warehouse_code = Q1.warehouse_code ";
									
		$sub_query = $sub_query." WHERE Sorder_id = ".$SSaId;
		
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
			$clientcode = $row[3];
			$deliverydt_quantitybox=$row[40];
			$deliverydt_itemunit=$row[41];
			$deliverydt_itempackage=$row[42];
		
		if (empty($deliverydt_quantitybox))
				$deliverydt_quantitybox = 0;      	  
			
			if (empty($deliverydt_itemunit))
				$deliverydt_itemunit = 0;      	  
			
			if (empty($deliverydt_itempackage))
				$deliverydt_itempackage = 0;    
				
			$sub_query4 = " Select Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
					      " From DeliveryDt ".
						  " Where DeliveryDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And DeliveryDt.Journal_Type = 'DI' ".
						  " And DeliveryDt.Delivery_Id != '".$vSaId."' ";
			$sub_result4 = selectData($connection, $sub_query4);
			if ($sub_result4[0] == '') $sub_result4[0] = 0;

			$sub_query5 = " Select Sum(ifNull(Temp_DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDeliveredTemp ".
					      " From Temp_DeliveryDt ".
					      " Where Temp_DeliveryDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And Temp_DeliveryDt.Journal_Type = 'DI' ";
			$sub_result5 = selectData($connection, $sub_query5);
			if ($sub_result5[0] == '') $sub_result5[0] = 0;		  
			
			//Get Remaining Qty For Each Items
			$vRemainQty = ($row[9] - ($sub_result4[0] + $sub_result5[0]));
			
			//if Item With SerialNo True Set Qty To Zero
			//if ($Module_DeliveryWithSorder == 0) {
			//Stopped 20120612 due to dajcom request
			if ($row[35] == 0) $vSaDtQty = ($row[9] - ($sub_result4[0] + $sub_result5[0]));
			else $vSaDtQty = 0;
			/*if ($Module_SerialNo == 1) {
				$vSaDtQty = 0;	
			} else {
				$vSaDtQty = ($row[9] - ($sub_result4[0] + $sub_result5[0]));
			}*/	
			
			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0), ifNull(item_weight,0) ".
					" FROM Items WHERE item_Code = '".$row[7]."'";
			$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];
			$itemweight 	= $result[8];
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				
				if ($Module_Unit1Method == 1)
					$vItemUnit2Qty = $vSaDtQty*$vItemUnitCoef;
				else	
					$vItemUnit2Qty = $vSaDtQty/$vItemUnitCoef;
			}
				
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
					 " 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];	
			$vSaStpPromoAcc     = $result[6];
			$vSaStpTipsAcc      = $result[7];
				
			$vSaStpCreditNonStockAcc    = $result[8];
			$vSaStpCreditVatNonStockAcc = $result[9];
			$vSaStpVatAcc 		  	  	= $result[10];
			$vSaStpVatNonStockAcc 	  	= $result[11];
			$vSaStpVatAccCash	  	  	= $result[12];
			$vSaStpVatNonStockAccCash 	= $result[13];
					
			$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$clientcode."' ";	
			$resexp = mysql_query($queryexp,$connection);
			$rwexp = mysql_fetch_row($resexp);
			$clientexp = $rwexp[0];
	
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc,trans_export ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = '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];
			$vTranStpPromoAcc        = $result[11]; 
			$vTranStpTipsAcc         = $result[12];
					
			if ($Module_RawMaterial == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				$vSaDtTipsAcc      = $vTranStpTipsAcc;
						
				if ($item_vat > 0 && $vSorderVatChk == 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;		
				//$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
				$vSaDtTipsAcc      = $vSaStpTipsAcc;
						
				if ($item_vat > 0 && $vSorderVatChk == 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[13]; 
			
			$sub_queryVat = " SELECT GetVATAccount('".$row[3]."','".$vSaDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
					
			$QtyExistExceeded = 0;
			$QtyRemainedNeg = 0;
			
			if ($vRemainQty <= 0 && ($Module_NegativeQuantity==0 && $Login_negativeQty==0))
				$QtyRemainedNeg = 1;
			
			if ($ItemNonStock == 0 && $vRemainQty > 0 && ($Module_NegativeQuantity==0 && $Login_negativeQty==0)) {
			
				$sub_query7  = " Select QtyExistsWSorder('".$row[7]."', '".$row[6]."', now(), 0, 'DI', '', '') QtyExists From Dual "; //echo $sub_query7;
				$sub_result7 = selectData($connection, $sub_query7);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result7[0];
			
				//stopped by nadine
				/* if (abs($vRemainQty) > $vItemQtyExists && abs($vRemainQty) > 0)
					$QtyExistExceeded = 1; */
				
				if ($vItemQtyExists>0){
					if ($vRemainQty > $vItemQtyExists) $vSaDtQty = $vItemQtyExists;
				} else $QtyExistExceeded = 1;
				
			}
			
			if (($QtyRemainedNeg == 0 && $QtyExistExceeded == 0) || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
				fbegin();
				$vSaDtId = get_nextsequence('deliverydt_id','',$connection);	
				fcommit();
			
				$query_cost = " select ifNull(MeanCostCur('".$row[7]."', '".$row[2]."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".$row[7]."', '".$row[2]."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				$vSaDtCostBase1  = $result_cost[0];
				$vSaDtCostBase2  = $result_cost[1];
				$vSaDtCost=ConvertCurrency($Base1, $PSaCurr, $row[2], $vSaDtCostBase1, $connection);
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				//echo $query_cost; exit;
				//$vSaDtCostBase2 = ConvertCurrency($row[1], $base2, insertMySQLDate(displayToday()), $vSaDtCostBase1, $connection);		
		
				$ProjectCode = $row[4];
				$ProjectCode = "".$ProjectCode;
				if ($ProjectCode == '') $ProjectCode = 'Null';
				else $ProjectCode = "'".$ProjectCode."'";
				
				$CostCentCode = $row[5];
				$CostCentCode = "".$CostCentCode;
				if ($CostCentCode == '') $CostCentCode = 'Null';
				else $CostCentCode = "'".$CostCentCode."'";
				
				if ($Module_Delivery == 0) {	
				
					$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];
					
					$vSaDtPriceTTC      = $row[18];
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	
					
					$vSaTotalWeight = $vSaTotalWeight + $vSaDtQty*$itemweight;
					
					$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
								  " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								  " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								  " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Deliverydt_cost, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Item_QtyPacked, ".
								  " DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, DeliveryDt_TransportAmountBase2, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_quantitybox, deliverydt_itemunit, deliverydt_itempackage ) ".
								  " VALUES ( $vSaDtId, $vSaId, '".$row[0]."', '".$row[1]."', '".$row[2]."', '".$row[3]."', $ProjectCode, $CostCentCode, '".$row[6]."', '".trim(strtoupper($row[7]))."', '".$row[8]."', '".$vSaDtQty."', ". 
								  " '".$row[10]."', '".$row[11]."', '".$row[12]."', '".$row[13]."', '".$row[14]."', '".$row[15]."', '".$row[16]."', '".$row[17]."', '".$row[18]."', $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, ".
								  " '".addslashes($row[19])."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', ".$row[24].", ".$row[25].", ".$row[26].", ".$row[27].", ".
								  " ".$row[28].", '".$row[29]."', '".$row[30]."', ".$row[31].", $vSaDtCost, $vSaDtCostBase1, $vSaDtCostBase2, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', $row[36], '".$row[37]."', '".$row[38]."', '".$row[39]."', '".$vSaDtTipsAcc."', ".
								  " '".$vSaDtVatAcc."', '".$row[34]."', '".$_SESSION['useraccount']."',$deliverydt_quantitybox,$deliverydt_itemunit,'$deliverydt_itempackage'  ) ";
					//echo $sub_query1; exit; 
				} else {
					$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
								  " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								  " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								  " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Item_QtyPacked, ".
								  " DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code,deliverydt_quantitybox, deliverydt_itemunit, deliverydt_itempackage  ) ".
								  " VALUES ( $vSaDtId, $vSaId, '".$row[0]."', '".$row[1]."', '".$row[2]."', '".$row[3]."', $ProjectCode, $CostCentCode, '".$row[6]."', '".trim(strtoupper($row[7]))."', '".$row[8]."', '".$vSaDtQty."', ". 
								  " 0, 0, 0, $row[13], $row[14], $row[15], $row[16], 0, 0, 0, 0, '".addslashes($row[19])."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', 0, 0, 0, 0, 0, '".$row[29]."', '".$row[30]."', ".
								  " ".$row[31].", $vSaDtCostBase1, $vSaDtCostBase2, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', $row[36], '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$row[34]."', '".$_SESSION['useraccount']."',$deliverydt_quantitybox,$deliverydt_itemunit,'$deliverydt_itempackage' ) ";
					
				}	
				
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))
					$message  = mysql_error(); 	
				$updatequery = "update temp_deliveries set totalWeight = $vSaTotalWeight where Delivery_id = $vSaId"; 
				$resupdate = mysql_query($updatequery,$connection);
			} /* else {
				
				$qtymessage  .= "Qty[".abs($vRemainQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$row[7].").";
			} */
		}
	
		if($message == '') $message = $qtymessage;
	} else 
		$message  = mysql_error();
//exit;
}


//Load Sorder
else if($mainmode == "loadsorder" && $SSaDtId != ''){
		
	
	if (!isset($PSaCurr))
	   $PSaCurr = $base1;
	   
	if (empty($PSaDiscountAmt))
		$PSaDiscountAmt = 0;
	if (empty($PSaDiscount))
		$PSaDiscount = 0;
	
	$PSaCostCentCode = "".$PSaCostCentCode;	
	if ($PSaCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PSaCostCentCode."'";
	
	$PSaProjectCode = "".$PSaProjectCode;		
	if ($PSaProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PSaProjectCode."'";   

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
	$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];
	
	$ErrorExists = 0;
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSaCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSaCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSaProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSaClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSaSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
		
	if ($ErrorExists == 1) 
		$message = 'Load not allowed. Please check for Client/Salesman/Project/Costcenter Code.';
		
	
	//Insert Master Table
	if ($SSaId == "" && $ErrorExists == 0){
		
		fbegin();	
		$vSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
	
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
					 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
		$result = selectData($connection, $query);
		$PSaVatChkbx = $result[0];

		
		fbegin();
		$delivery_date         = $_GET['delivery_date'];
		$delivery_card_msg     = $_GET['delivery_card_msg'];
		$delivery_contact      = $_GET['delivery_contact'];
		$delivery_contactphone = $_GET['delivery_contactphone'];
		if($delivery_date == '') $delivery_date = $PSaDate;
		
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
				 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
				 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
				 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, Delivery_ManualNo, User_Account, Logged_Code, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone) ".
				 " VALUES ( ".$vSaId.", Null, '".insertMySQLDate($PSaDate)."', '".insertMySQLDate($PSaMaturityDate)."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaRemark))."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', '".ereg_replace("'", "\'", trim($PSaDAddress))."', '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaDriverName))."', '".ereg_replace("'", "\'", trim($PSaSalesmanCode))."', '".$PSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PSaDiscount, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
				 "          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PSaVatChkbx, '".ereg_replace("'", "\'", trim($PSaManualNo))."', ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".insertMySQLDate($delivery_date)."', '".$delivery_card_msg."', '".$delivery_contact."', '".$delivery_contactphone."')";
			//echo $query."<br>";exit; 
		$result=mysql_query($query,$connection);
			
		
		if ($result){
			$SSaId = $vSaId;
			fcommit();
		}else{
			$vSaId = "";
			$SSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtCostBase1     = 0;
	$vSaDtCostBase2     = 0;
	$vSaDtDiscPer       = 0;
	$vSaDtDiscAmt       = 0;
	$vSaDtDiscAmtBase1  = 0;
	$vSaDtDiscAmtBase2  = 0;
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;
	$vSaDtItemTax1      = 0;
	$vSaDtItemTax2      = 0;
	$vSaDtItemTax3      = 0;
	$vSaDtItemTax4      = 0;
	$vSaDtItemTax5      = 0;
	
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	
	$qtymessage = '';	
		
	if ($SSaId != '' && $ErrorExists == 0) {
		$vSaId = $SSaId;
		
		$sub_query = " SELECT SorderDt_id, Sorderdt.Currency_Code, Sorderdt.Warehouse_Code, Sorderdt.Item_code, Sorderdt.Item_CodePacked, ifNull(SorderDt_Quantity,0), ".
					 " ifNull(SorderDt_Price,0), ifNull(SorderDt_PriceBase1,0), ifNull(SroderDt_PriceBase2,0), ifNull(SorderDt_Discount,0), ifNull(SorderDt_DiscountAmount,0), ".
					 " ifNull(SorderDt_DiscountBase1,0), ifNull(SorderDt_DiscountBase2,0), ifNull(Sorderdt.Item_Vat,0), ifNull(SorderDt_PriceTTC,0), SorderDt_Remark, SorderDt_DirectStkDbt, ".
					 " SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, ifNull(Sorderdt.Item_Tax1,0), ifNull(Sorderdt.Item_Tax2,0), ifNull(Sorderdt.Item_Tax3,0), ifNull(Sorderdt.Item_Tax4,0), ".
					 " ifNull(Sorderdt.Item_Tax5,0), ifNull(Sorderdt_posted,0), ifNull(Sorderdt_OldData,0), ifNull(Sorderdt_promotion,0), Sorderdt.Item_UnitCoef, Sorderdt.Item_Unit2Qty, Sorderdt.User_Account, ".
					 " ifNull(item_withserialno,0) As ItemWithSerialNo, ifNull(Item_QtyPacked,0) As Item_QtyPacked, Sorderdt.Project_Code, Sorderdt.CostCent_Code ".
					 " FROM Sorderdt Inner Join Items on Sorderdt.Item_Code = Items.Item_Code ".
					 " WHERE SorderDt_id In (".$SSaDtId.")";
			
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
			
			fbegin();
			$vSaDtId = get_nextsequence('deliverydt_id','',$connection);	
			fcommit();
			
			$sub_query4 = " Select Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
					      " From DeliveryDt ".
						  " Where DeliveryDt.RelatedDt_ID =  '".$row[0]."' ".
						  " And DeliveryDt.Journal_Type = 'DI' ".
						  " And DeliveryDt.Delivery_Id != '".$vSaId."' ";
					      
			$sub_result4 = selectData($connection, $sub_query4);
			if ($sub_result4[0] == '') $sub_result4[0] = 0;
	
			$sub_query5 = " Select Sum(ifNull(Temp_DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDeliveredTemp ".
					      " From Temp_DeliveryDt ".
					      " Where Temp_DeliveryDt.RelatedDt_ID =  '".$row[0]."' ".
						   " And Temp_DeliveryDt.Journal_Type = 'DI' ";
			$sub_result5 = selectData($connection, $sub_query5);
			if ($sub_result5[0] == '') $sub_result5[0] = 0;	  
			
			//if Item With SerialNo True Set Qty To Zero
			//if ($Module_DeliveryWithSorder == 0) {
			//Stopped 20120612 due to dajcom request
			$vRemainQty = $row[5] - ($sub_result4[0] + $sub_result5[0]);	
			if ($row[31] == 0) $vSaDtQty = ($row[5] - ($sub_result4[0] + $sub_result5[0]));
			else $vSaDtQty = 0;
			/*if ($Module_SerialNo == 1) {	
				$vSaDtQty = 0;	
			} else {
				$vSaDtQty = ($row[5] - ($sub_result4[0] + $sub_result5[0]));
			}*/
			
					
			$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_dt3 = $result[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) {
				$vItemUnitCoef = $ItemUnit;

				if ($Module_Unit1Method == 1)
					$vItemUnit2Qty = $vSaDtQty*$vItemUnitCoef;
				else	
					$vItemUnit2Qty = $vSaDtQty/$vItemUnitCoef;
			}
				
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
					 " 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];	
			$vSaStpPromoAcc     = $result[6];
			$vSaStpTipsAcc      = $result[7];
				
			$vSaStpCreditNonStockAcc    = $result[8];
			$vSaStpCreditVatNonStockAcc = $result[9];
			$vSaStpVatAcc 		  	  	= $result[10];
			$vSaStpVatNonStockAcc 	  	= $result[11];
			$vSaStpVatAccCash	  	  	= $result[12];
			$vSaStpVatNonStockAccCash 	= $result[13];
					
				
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc ".
					 " 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];
			$vTranStpPromoAcc        = $result[11]; 
			$vTranStpTipsAcc         = $result[12];
					
			if ($Module_RawMaterial == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				$vSaDtTipsAcc      = $vTranStpTipsAcc;
						
				if ($item_vat > 0 && $PSaVatChkbx == 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;		
				//$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
				$vSaDtTipsAcc      = $vSaStpTipsAcc;
						
				if ($item_vat > 0 && $PSaVatChkbx == 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;
				//}
												
			}
			
			$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
			
			
			$QtyExistExceeded = 0;
			$QtyRemainedNeg = 0;
			
			if ($vRemainQty <= 0 && ($Module_NegativeQuantity==0 && $Login_negativeQty==0))
				$QtyRemainedNeg = 1;
			
			if ($ItemNonStock == 0 && $vRemainQty > 0 && ($Module_NegativeQuantity==0 && $Login_negativeQty==0)) {
			
				$sub_query7  = " Select QtyExistsWSorder('".$row[7]."', '".$row[6]."', now(), 0, 'DI', '', '') QtyExists From Dual "; //echo $sub_query7;
				$sub_result7 = selectData($connection, $sub_query7);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result7[0];
			
				//stopped by nadine
				/* if (abs($vRemainQty) > $vItemQtyExists && abs($vRemainQty) > 0)
					$QtyExistExceeded = 1; */
				
				if ($vItemQtyExists>0){
					if ($vRemainQty > $vItemQtyExists) $vSaDtQty = $vItemQtyExists;
				} else $QtyExistExceeded = 1;
				
			}
			//fady
			if (($QtyRemainedNeg == 0 && $QtyExistExceeded == 0) || ($Module_NegativeQuantity==1 && $Login_negativeQty==1  )) {
				
				if ($Module_Delivery == 0) {		
					
					$vSaDtPrice         = $row[6];
					//$vSaDtPriceBase1    = $row[7];
					//$vSaDtPriceBase2    = $row[8];
					$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
					$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
					$vSaDtDiscPer       = $row[9];
					//$vSaDtDiscAmt       = $row[10];
					//$vSaDtDiscAmtBase1  = $row[11];
					//$vSaDtDiscAmtBase2  = $row[12];
					$vSaDtPriceTTC      = $row[14];
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
					$vSaDtItemTax1      = $row[20];	
					$vSaDtItemTax2      = $row[21];	
					$vSaDtItemTax3      = $row[22];	
					$vSaDtItemTax4      = $row[23];	
					$vSaDtItemTax5      = $row[24];	
					
					// Calculation For Detail Discount Amount
					$vSaDtDiscAmt       = ((($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$vSaDtDiscPer/100))*$PSaDiscount)/100;
					$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

					
					if ($row[1] != $PSaCurr) {
						$vSaDtPrice    = ConvertCurrency($row[1], $PSaCurr, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
						$vSaDtDiscAmt  = ConvertCurrency($row[1], $PSaCurr, insertMySQLDate($PSaDate), $vSaDtDiscAmt, $connection);
						$vSaDtPriceTTC = ConvertCurrency($row[1], $PSaCurr, insertMySQLDate($PSaDate), $vSaDtPriceTTC, $connection);
						
						$vSaDtPriceBase1    = ($vSaDtPrice*$rate_dt)/$rate_dt1;
						$vSaDtPriceBase2    = ($vSaDtPrice*$rate_dt)/$rate_dt2;
						$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
					
					}
				} //End if ($Module_Delivery == 0) 
				
				$query_cost = " select ifNull(MeanCostCur('".$row[3]."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".$row[3]."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				$vSaDtCostBase1  = $result_cost[0];
				$vSaDtCostBase2  = $result_cost[1];
				$vSaDtCost=ConvertCurrency($Base1, $PSaCurr, insertMySQLDate($PSaDate), $$vSaDtCostBase1, $connection);
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				//echo $query_cost; exit;
				//$vSaDtCostBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtCostBase1, $connection);		
		
				$ProjectCode = $row[33];
				if (empty($ProjectCode)) $ProjectCode = 'Null';
				else $ProjectCode = "'".$ProjectCode."'";
					
				$CostCentCode = $row[34];
				if (empty($CostCentCode)) $CostCentCode = 'Null';
				else $CostCentCode = "'".$CostCentCode."'";
				
				fbegin(); 
				
				if ($Module_Delivery == 0) {	
					$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
								  " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
								  " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
								  " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Deliverydt_BelongsToGroup, Deliverydt_cost, Deliverydt_costbase1, ".
								  " Deliverydt_costbase2, Item_QtyPacked, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code ) ".
								  " VALUES ( $vSaDtId, $vSaId, '".$row[0]."', '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', $ProjectCode, $CostCentCode, ".
								  " '".$row[2]."', '".trim(strtoupper($row[3]))."', '".$row[4]."', '".$vSaDtQty."', $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $vSaDtDiscPer, $vSaDtDiscAmt, $vSaDtDiscAmtBase1, $vSaDtDiscAmtBase2, '".$row[13]."', $vSaDtPriceTTC, ". 
								  " $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".$row[15]."', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', ".
								  " $vSaDtItemTax1, $vSaDtItemTax2, $vSaDtItemTax3, $vSaDtItemTax4, $vSaDtItemTax5, ".$row[25].", ".$row[26].", ".$row[27].", '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', $FI_BelongsToGrp, '$vSaDtCost', '$vSaDtCostBase1', $vSaDtCostBase2, ".
								  " $row[32], '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$row[30]."', '".$_SESSION['useraccount']."' ) ";
				} else {
					$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
								  " DeliveryDt_Remark, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, ".
								  " Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Deliverydt_costbase1, Deliverydt_costbase2, Item_QtyPacked, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code ) ".
								  " VALUES ( $vSaDtId, $vSaId, '".$row[0]."', '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', $ProjectCode, $CostCentCode, ".
								  " '".$row[2]."', '".trim(strtoupper($row[3]))."', '".$row[4]."', '".$vSaDtQty."', '".$row[15]."', ".$row[25].", ".$row[26].", ".$row[27].", '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', ".
								  " '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', '$FI_BelongsToGrp', $vSaDtCostBase1, $vSaDtCostBase2, $row[32], '".$vSaDtTipsAcc."', '".$vSaDtVatAcc."', '".$row[30]."', '".$_SESSION['useraccount']."' ) ";
					
				}

				 
			//	echo $sub_query1; exit;	
				$sub_result1=mysql_query($sub_query1,$connection);
			
			
				if ($sub_result1){
					fcommit();
				}else{
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}
			} /* else {
				//$ErrorExists = 1;
				$qtymessage  .= "Qty[".abs($vSaDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$row[3].").";
			} */
		}  //End Loop of SorderDt Query
		
		if($message == '') $message = $qtymessage;	
		
		if ($Module_Delivery == 0 && $ErrorExists == 0) {	
			$CalculateResult = Calculate_MasterAmounts($vSaId, $PSaDate, $PSaVatChkbx, $PSaDiscount, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		
		} 
		
		
		
		$vSorderRef = 0;
		$vSorderAllRef = '';
		$vCount = 1;
		
		$sub_query = " SELECT Distinct Sorder.Sorder_Reference ".
					 " FROM Sorder Inner Join SorderDt on SorderDt.Sorder_ID = Sorder.Sorder_ID ".
					 " Inner Join Temp_DeliveryDt As DeliveryDt on DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_ID ".
					 " WHERE SorderDt_ID In (".$SSaDtId.")";

		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
			
			if ($vCount == 1) $vSorderRef    = $sub_row[0];
			
			$pos = strrpos($vSorderAllRef, $sub_row[0]);
			if ($pos === false) { 
				$vSorderAllRef = $vSorderAllRef.','.$sub_row[0];
			}
			
			
			$vCount=$vCount+1;
		
		}
		
		$sub_query1 = " UPDATE temp_deliveries SET ".
					  " Sorder_reference = if(Sorder_reference is null or Sorder_reference='', $vSorderRef, Sorder_reference), ".
					  " Delivery_SorderReferences = Substr('".$vSorderAllRef."',2,length('".$vSorderAllRef."')) ".
 					  " WHERE Delivery_ID = ".$vSaId;
		//echo $sub_query1; exit;		 
		$sub_result1=mysql_query($sub_query1,$connection);
	
	}

}

//Load Sold Items
else if($mainmode == "loaditems"){
	
	if (!isset($PSaCurr))  $PSaCurr = $base1;
	   
	if (empty($PSaDiscountAmt))	$PSaDiscountAmt = 0;
	if (empty($PSaDiscount))	$PSaDiscount = 0;
			
	$PSaCostCentCode = "".$PSaCostCentCode;
	
	if ($PSaCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PSaCostCentCode."'";
	
	$PSaProjectCode = "".$PSaProjectCode;	
	if ($PSaProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PSaProjectCode."'";   

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
	$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];
	
	$ErrorExists = 0;
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSaCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSaCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSaProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSaClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSaSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSaSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
		
	if ($ErrorExists == 1) 
		$message = 'Load not allowed. Please check for Client/Salesman/Project/Costcenter Code.';
		
	
	//Insert Master Table
	if ($SSaId == "" && $ErrorExists == 0){
		
		fbegin();	
		$vSaId = get_nextsequence('delivery_id','',$connection);	
		fcommit();
		
	
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
					 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$PSaClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
		$result = selectData($connection, $query);
		$PSaVatChkbx = $result[0];

		
		fbegin();
		if (empty($PSaVehicleWeight))   $PSaVehicleWeight = 0;
		if (empty($PSaVehicleLoadWeight))   $PSaVehicleLoadWeight = 0;

		$delivery_date         = $_GET['delivery_date'];
		$delivery_card_msg     = $_GET['delivery_card_msg'];
		$delivery_contact      = $_GET['delivery_contact'];
		$delivery_contactphone = $_GET['delivery_contactphone'];
		if($delivery_date == '') $delivery_date = $PSaDate;
		
		$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
				 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
				 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
				 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx, Delivery_ManualNo,Delivery_vehicleweight,Delivery_vehicleLoadweight, User_Account, Logged_Code, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone) ".
				 " VALUES ( ".$vSaId.", Null, '".insertMySQLDate($PSaDate)."', '".insertMySQLDate($PSaMaturityDate)."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaRemark))."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', '".ereg_replace("'", "\'", trim($PSaDAddress))."', '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSaDriverName))."', '".ereg_replace("'", "\'", trim($PSaSalesmanCode))."', '".$PSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
				 "          '".$vSaVatAcc."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PSaVatChkbx, '".ereg_replace("'", "\'", trim($PSaManualNo))."', $PSaVehicleWeight, $PSaVehicleLoadWeight, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".insertMySQLDate($delivery_date)."', '".$delivery_card_msg."', '".$delivery_contact."', '".$delivery_contactphone."' )";
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	

		if ($result){
			$SSaId = $vSaId;
			fcommit();
		}else{
			$vSaId = "";
			$SSaId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtCostBase1     = 0;
	$vSaDtCostBase2     = 0;
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;
		
	if ($SSaId != '' && $ErrorExists == 0) {
		$vSaId = $SSaId;
		
		$sub_query = " SELECT Distinct Item_code, Item_CodePacked, Item_QtyPacked, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ". 
					 " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, DeliveryDt_TipsAccount, DeliveryDt_VatAccount ".
					 " FROM DeliveryDt ".
					 " WHERE Journal_Type = 'DI' ".
					 " ORDER BY Item_code Desc ";
			
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
			
			$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
			//echo "<br><br>".$query;
			$result = selectData($connection, $query);
			$c_sp = $result[0];
	
			$query = " SELECT ifNull(Item_Vat,0), ifNull(Item_Unit,0), ifNull(Item_Promotion,0), ifNull(Item_tax1,0), ifNull(Item_tax2,0), ".
					 " ifNull(Item_tax3,0), ifNull(Item_tax4,0), ifNull(Item_tax5,0), Currency_Code, Item_SellingPrice1, Item_SellingPrice2, ".
					 " Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6 ".
					 " FROM Items WHERE item_Code = '".$row[0]."'";
			$result = selectData($connection, $query);
			$ItemVat    = $result[0];
			$ItemUnit   = $result[1];
			$ItemPromo  = $result[2];
			$ItemTax1   = $result[3];	
			$ItemTax2   = $result[4];	
			$ItemTax3   = $result[5];	
			$ItemTax4   = $result[6];	
			$ItemTax5   = $result[7];	
			$ItemCurr   = $result[8];	
			
			
			$i_sp   = $result[9];
			
			switch ($c_sp){
				case "II":
					$i_sp = $result[10]; break;
				case "III":
					$i_sp = $result[11]; break;
				case "IV":
					$i_sp = $result[12]; break;
				case "V":
					$i_sp = $result[13]; break;
				case "VI":
					$i_sp = $result[14]; break;
			}
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = 0;
			}
				
			
											
			if ($Module_Delivery == 0) {	
				if ($SalesTTC == 1) {
					$vSaDtPriceTTC      = $i_sp;
					$vSaDtPriceTTC      = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $vSaDtPriceTTC, $connection);
					$vSaDtPriceTTCBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $vSaDtPriceTTC, $connection);
					$vSaDtPriceTTCBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtPriceTTC, $connection);

					$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $ItemVat/100));
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
							
				} else	{
					$vSaDtPrice      = $i_sp;
					$vSaDtPrice      = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
					
					$vSaDtPriceTTC      = 0;
					$vSaDtPriceTTCBase1 = 0;
					$vSaDtPriceTTCBase2 = 0;
							
				}
				
			} 
			
			
			$query_cost = " select ifNull(MeanCostCur('".$row[0]."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
			              " ifNull(MeanCostCur('".$row[0]."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
			$result_cost = selectData($connection, $query_cost);
			
			
			
			$vSaDtCostBase1  = $result_cost[0];
			$vSaDtCostBase2  = $result_cost[1];
			$vSaDtCost=ConvertCurrency($Base1, $PSaCurr, insertMySQLDate($PSaDate), $$vSaDtCostBase1, $connection);
			if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
			if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
			//echo $query_cost; exit;
			
			fbegin();
			$vSaDtId = get_nextsequence('deliverydt_id','',$connection);	
			fcommit();
			
			fbegin();
			
			if ($Module_Delivery == 0) {	
				$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
							  " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
							  " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
							  " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Deliverydt_BelongsToGroup, Deliverydt_cost, Deliverydt_costbase1, ".
							  " Deliverydt_costbase2, Item_QtyPacked, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code ) ".
							  " VALUES ( $vSaDtId, $vSaId, null, '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', $ProjectCode, $CostCentCode, ".
							  " '".$lstWarehouse."', '".trim(strtoupper($row[0]))."', '".$row[1]."', 0, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, 0, 0, 0, 0, $ItemVat, $vSaDtPriceTTC, ". 
							  " $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, null, '".$row[3]."', '".$row[4]."', '".$row[5]."', '".$row[6]."', '".$row[7]."', '".$row[8]."', ".
							  " $ItemTax1, $ItemTax2, $ItemTax3, $ItemTax4, $ItemTax5, 0, 0, $ItemPromo, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', $FI_BelongsToGrp, $vSaDtCost, $vSaDtCostBase1, $vSaDtCostBase2, ".
							  " $row[2], '".$row[9]."', '".$row[10]."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ) ";
			} else {
				$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ". 
							  " DeliveryDt_Remark, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Item_UnitCoef, Item_Unit2Qty, Journal_Type, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, ".
							  " Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Deliverydt_costbase1, Deliverydt_costbase2, Item_QtyPacked, DeliveryDt_TipsAccount, DeliveryDt_VatAccount, User_Account, Logged_Code ) ".
							  " VALUES ( $vSaDtId, $vSaId, null, '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', $ProjectCode, $CostCentCode, ".
							  " '".$lstWarehouse."', '".trim(strtoupper($row[0]))."', '".$row[1]."', 0, null, 0, 0, $ItemPromo, '".$vItemUnitCoef."', '".$vItemUnit2Qty."', 'DI', '".$row[3]."', '".$row[4]."', '".$row[5]."', '".$row[6]."', '".$row[7]."', '".$row[8]."', ".
							  " $FI_BelongsToGrp, $vSaDtCostBase1, $vSaDtCostBase2, $row[2], '".$row[9]."', '".$row[10]."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ) ";
				
			}

			 
			//echo $sub_query1; exit;	
			$sub_result1=mysql_query($sub_query1,$connection);
		
		
			if ($sub_result1){
				fcommit();
			}else{
				$message  = mysql_error(); 
				$ErrorExists = 1;
				frollback();
			}
			
		}  //End Loop of Items Query
	
	}

}

//UnConfirmed Sorder
else if($mainmode == "unconfirmorder" && $SSaId != ''){
	$query = "UPDATE Sorder SET sorder_confirmed = 0 WHERE sorder_id = ".$SSaId."";

	if (updateData($connection, $query, true))
		$message = "Preparation Order Unconfirmed";
	else
		$message  = mysql_error();
		
}

  else if($mode == ""  && $mainmode='loadproduct' ){
	
	$i=0;
	$vsorderdtids = '';
	$msg = '';
	$querycheckdt = "select distinct RelatedDt_Id from production where production_id in ($vSelectedRows);";
	$resultcheckdt = mysql_query($querycheckdt,$connection);
	while($rowcheckdt = mysql_fetch_row($resultcheckdt)){
		if($i == 0) $vsorderdtids = $rowcheckdt[0];
		else $vsorderdtids = $vsorderdtids.','.$rowcheckdt[0];
		$i++;
	}
	
	
	$querycheckorderid = "select distinct sorder_id from sorderdt where sorderdt_id in ($vsorderdtids)";
	$rescheckorderid = mysql_query($querycheckorderid,$connection);
	$numrows = mysql_num_rows($rescheckorderid);
	$roworderid = mysql_fetch_row($rescheckorderid);
	if($numrows >1){
		$message = "Recheck Items!";
	} else{
		
		$vSorId = $roworderid[0];
		fbegin();	
		$vSaId = get_nextsequence('Delivery_id','',$connection);	
		fcommit();
		
		fbegin(); 
		$query = " insert into temp_deliveries (Delivery_id,Delivery_Reference,Delivery_Date,Client_code,Project_Code,Costcent_code,Journal_Type, ".
				 " Delivery_QuantityEqual,Delivery_TotalQuantity,Delivery_TotalQuantityRet,Delivery_QuantityEqualSld,Delivery_TotalQuantitySld,Delivery_TotalNoOfItem,Delivery_Edit,Journal_Id, ".
				 " Delivery_CartonGrossWt,Delivery_CartonNetWeight,SALESMAN_cODE,Delivery_VAT,Delivery_VATBase1,Delivery_VATBase2,Delivery_Taxable,Delivery_TaxableBase1,Delivery_TaxableBase2, ".
				 " Delivery_NoneTaxable,Delivery_NoneTaxableBase1,Delivery_NoneTaxableBase2,Delivery_Total,Delivery_DiscountAmount,Delivery_DiscountBase1,Delivery_DiscountBase2,Currency_code,".
				 " Delivery_Cash,Delivery_CashBase1,Delivery_CashBase2,Delivery_CashInBase1,Delivery_CashInBase2,Delivery_CashOutBase1,Delivery_CashOutBase2,Delivery_TipsBase1, ".
				 " USER_Account,Delivery_CREDITACC,Delivery_CREDITACCcur,Delivery_Rate,Delivery_RateBase1,Delivery_RateBase2,Delivery_DiscountPer,".
				 " Delivery_Tax1,Delivery_Tax2,Delivery_Tax3,Delivery_Tax4,Delivery_Tax5,Delivery_Tax1Base1,Delivery_Tax2Base1,Delivery_Tax3Base1,Delivery_Tax4Base1,Delivery_Tax5Base1, ".
				 " Delivery_Tax1Base2,Delivery_Tax2Base2,Delivery_Tax3Base2,Delivery_Tax4Base2,Delivery_Tax5Base2,Synchronized,Delivery_TransportAccount,Delivery_transportAmount,Delivery_TransportAmountBase1,Delivery_TransportAmountBase2, ".
				 " Sorder_Reference,Detail_Code,Delivery_VatChkbx,BRANCH_CODE,Delivery_TransportTTC,srorder_id, Logged_code,delivery_export, Delivery_ClientDeliveryDate, Delivery_ShippingWay, Delivery_ShipName, Delivery_ClientPhone) ".
				 " select $vSaId, null, now(), Client_code, Project_Code, Costcent_code, 'DI',0,0,0,0,0,0,0,0,0,0,Salesman_Code,Sorder_vat,Sorder_VatBase1,Sorder_VatBase2, ".
				 " Sorder_taxable,Sorder_TaxableBase1,Sorder_TaxableBase2,Sorder_nonetaxable,Sorder_NoneTaxableBase1,Sorder_NoneTaxableBase2,Sorder_Total,Sorder_discountamount,Sorder_DiscountBase1,Sorder_DiscountBase2, ".
				 " Currency_code,0,0,0,0,0,0,0,0, User_Account,sorder_CreditAccount,sorder_CreditCur,Sorder_rate,Sorder_ratebase1,Sorder_ratebase2,Sorder_discountper,".
				 " sorder_Tax1,sorder_Tax2,sorder_Tax3,sorder_Tax4,sorder_Tax5,sorder_Tax1Base1,sorder_Tax2Base1,sorder_Tax3Base1,sorder_Tax4Base1,sorder_Tax5Base1, ".
				 " sorder_Tax1Base2,sorder_Tax2Base2,sorder_Tax3Base2,sorder_Tax4Base2,sorder_Tax5Base2,Synchronized,Sorder_TransportAccount,Sorder_TransportAmount,Sorder_TransportBase1,Sorder_TransportBase2,".
				 " Sorder_reference,Detail_Code,Sorder_VATChckbx,BRANCH_CODE,Sorder_TransportTTC,sorder_id,'".$_SESSION['useraccount']."',sorder_export, Sorder_ClientSorderDate, Sorder_ShippingWay, Sorder_ShipName, Sorder_ClientPhone ".
				 " from sorder where sorder_id = $vSorId"; //echo $query; exit;
		
		
		$result = mysql_query($query,$connection);
		if ($result){
			$SSaId = $vSaId;
			fcommit();
		}else{
			$vSaId = "";
			$SSaId = "";
			$message  = mysql_error(); 
			frollback();
		}		 
		if($SSaId != ""){
			$vSelectedRows = explode(',',$vSelectedRows);
			foreach($vSelectedRows as $vPrId){
				$queryRemainQty = "select distinct Production_quantity - (ifnull(deliverydt.DeliveryDt_Quantity,0)+ifnull(temp_deliverydt.DeliveryDt_Quantity,0))
							from production
							left join sorderdt on SorderDt_id = RelatedDt_Id
							Left Join Sorder on Sorder.Sorder_id = sorderdt.Sorder_id
							left join deliveries on deliveries.srorder_id = sorderdt.sorder_id
							left join deliverydt on deliverydt.Delivery_id = deliveries.Delivery_id
							and deliverydt.item_code = production.item_code and deliverydt.relateddt_id = production.relateddt_id
							left join temp_deliveries on temp_deliveries.srorder_id = sorderdt.sorder_id
							left join temp_deliverydt on temp_deliverydt.Delivery_id = temp_deliveries.Delivery_id and temp_deliverydt.item_code = production.item_code
							where production_id = $vPrId
							and Production_quantity - (ifnull(deliverydt.DeliveryDt_Quantity,0)+ifnull(temp_deliverydt.DeliveryDt_Quantity,0)) >0";
				$resRemainQty = mysql_query($queryRemainQty,$connection); 
				$rowRemainQty = mysql_fetch_row($resRemainQty);
				$remainingQty = $rowRemainQty[0];
				fbegin();	
				$vSadtId = get_nextsequence('DeliveryDt_id','',$connection);	
				fcommit();
				fbegin();
				$querydt = " insert into temp_deliverydt (DeliveryDt_id,Delivery_id,Client_Code, Delivery_Date,Project_Code,CostCent_Code,Warehouse_Code,Item_code,DeliveryDt_Quantity,DeliveryDt_ExpireDate,".
						   " RelatedDt_Id,Currency_code,Related_id,Item_CodePacked,Item_Vat,DeliveryDt_Price,DeliveryDt_PriceBase1,DeliveryDt_PriceBase2, ".
						   " SorderDt_CurrencyCode,SorderDt_Price,SorderDt_PriceBase1,SorderDt_PriceBase2,DeliveryDt_PriceTTC,user_account,Logged_code, RelatedDtprod_Id, DeliveryDt_BatchNo".
  						   " )".
						   " select $vSadtId, $SSaId,production.Client_Code,now(),production.Project_Code,production.Costcenter_Code,production.Warehouse_Code,production.Item_Code, $remainingQty, Production_ExpireDate, RelatedDt_Id,production.Currency_Code,0, ".
						   " Item_CodePacked,Item_vat,Sorderdt_price,SorderDt_PriceBase1,SroderDt_PriceBase2,sorderdt.CURRENCY_cODE, ".
						   " Sorderdt_price,SorderDt_PriceBase1,SroderDt_PriceBase2,SorderDt_PriceTTC,'".$_SESSION['useraccount']."','".$_SESSION['useraccount']."',$vPrId, Production_BatchNo ".
						   " from production ".
						   " left join sorderdt on SorderDt_id = RelatedDt_Id where Production_id = $vPrId";
				$resultdt = mysql_query($querydt,$connection);		   
				if ($resultdt){
				$SSadtId = $vSadtId;
				fcommit();
				}else{
				$vSadtId = "";
				$SSadtId = "";
				$message  = mysql_error(); 
				frollback();
				}	
			
			}
		}
		
	}
	
	//exit;
}  
//Confirm Sales 
else if(($mode == "confirmsales" || $mainmode == "confirmsales" || $mainmode == "unconfirmsales") && $SSaId != ''){

	$confirm_flag     = 0;
	$delivery_nettotal  = 0;
	$delivery_client    = '';
	$delivery_journalid = 0;
	$delivery_date      = '';
	$delivery_confirm   = 0;
	
	$query = " SELECT ifNull((ifNull(Delivery_Taxable,0) + ifNull(Delivery_NoneTaxable,0) + IfNull(Delivery_VAT,0) - IfNull(Delivery_DiscountAmount,0)),0) As Delivery_NetTotal, ".
             " Client_Code, ifNull(Journal_Id, -1), Delivery_Date, ifNull(Delivery_Confirmed,0)	FROM Deliveries WHERE Delivery_id = '".$SSaId."'";
	//echo "<br><br>".$query;
	$result = selectData($connection, $query);
	$delivery_nettotal  = $result[0];
	$delivery_client    = $result[1];
	$delivery_journalid = $result[2];
	$delivery_date      = $result[3];
	$delivery_confirm   = $result[4];
	
	
	if(empty($delivery_journalid)) $delivery_journalid = -1;

	if ($delivery_confirm == 0) {	
		$query = "SELECT Client_CreditLimit, Client_PaymentTerms, Client_CashMode, Client_Paymentterms2 FROM Clients WHERE Ledger_Number = '".$delivery_client."'";
		//echo "<br><br>".$query;
		$result = selectData($connection, $query);
		$c_cl = $result[0];
		$c_pt = $result[1];
		$Client_Paymentterms2 = $result[3];
		if ($result[2] == "1"){
			$confirm_flag = 1;
		}else{
			if ($FA_ClientPaymentTerms == 1 && $FA_ClientCreditLimit == 1) {
				$confirm_flag = 1;
			} else {
				if ($FA_ClientCreditLimit == 0 && $Module_CreditLimit == 1 ){
					//Check Client Credit Limit
					//Get Current Balance
					$querybalance = " SELECT IFNULL(SUM(if(journaldt_dbcd = 'D', journaldt_amount1, (-1)*journaldt_amount1)), 0) As Balance FROM journaldt ".
									" where journaldt.journal_id != ".$delivery_journalid." and ledger_number = '".$delivery_client."' ".
									" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".$delivery_date."','%Y%m%d') ";
					//echo "<br><br>".$querybalance;
					$result = selectData($connection, $querybalance);
					$q1 = $result[0];
					
					$q2 = $delivery_nettotal;

					if ($c_cl >= ($q1 + $q2)){
						$confirm_flag = 1;
					} else{
						$confirm_flag = 0;
						$message = "Confirmation not allowed. Exceed credit limit.";
					}
					
				} else
					$confirm_flag = 1;
								
				if ($FA_ClientPaymentTerms == 0 && $Module_PaymentTerms == 1){
					//Check Client payment Term
					$query = "select InvoiceDays('".$delivery_client."', '".$delivery_date."', 0,'".$Client_Paymentterms2."')";
					//echo "<br><br>".$query;
					$result = selectData($connection, $query);
					
					if ($c_pt > $result[0]){
						$confirm_flag = 1;
					}else{
						$confirm_flag = 0;
						$message = "Confirmation not allowed. Exceed payment terms.";
					}
				} else
					$confirm_flag = 1;

			}	
		}		
	} else
		$confirm_flag = 1;
	
	if ($confirm_flag == 1) {
		if ($delivery_confirm == 0 && ($mode == "confirmsales" || $mainmode == "confirmsales")) {	
			$query = "UPDATE Deliveries SET delivery_confirmed = 1 WHERE delivery_id = ".$SSaId."";

			if (updateData($connection, $query, true))
				$message = "Delivery Confirmed";
			else
				$message  = mysql_error();
		} 
		else if ($delivery_confirm == 1 && $mainmode == "unconfirmsales"){
			$query = "UPDATE Deliveries SET delivery_confirmed = 0 WHERE delivery_id = ".$SSaId."";

			if (updateData($connection, $query, true))
				$message = "Delivery Unconfirmed";
			else
				$message  = mysql_error();
			
		}	
	} 


}

//Disapprove Sales Order
else if($mode == "" && $mainmode == "disapproveorder" && $SSaId != ''){

	$query = "UPDATE Sorder SET sorder_disapproved = 1 WHERE sorder_id = ".$SSaId."";	
	//echo "<br><br>".$query;
	if (updateData($connection, $query, true)){
		$message = "Order Disapproved";
	}else{
		$message = "Order COULD NOT be Disapproved!";
	}
		
}

//Cancel Sales Order From Main Page
else if($mode == "" && $mainmode == "disapproveorder1" && $SSaId != ''){

	$ErrorExists = 0;

	$sub_query = " SELECT Distinct DeliveryDt.RelatedDt_Id ".
				 " FROM Temp_DeliveryDt As DeliveryDt ".
				 " WHERE Delivery_Id = '".$SSaId."'";

	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_row=mysql_fetch_array($sub_result)){
		$vRelatedDtID = $sub_row[0]; 
		
		$sub_query1 = " SELECT Distinct SorderDt.Sorder_Id ".
					  " FROM SorderDt ".
					  " WHERE SorderDt.SorderDt_Id = '".$vRelatedDtID."'";
		$sub_result1 = selectData($connection, $sub_query1);
		$vSorderID = $sub_result1[0];
		
		if ($vSorderID != "") {
			$query = "UPDATE Sorder SET sorder_disapproved = 1 WHERE sorder_id = ".$vSorderID."";	
			//echo "<br><br>".$query;
			if (!(updateData($connection, $query, true))){
				$ErrorExists = 1;
				$message = "Order COULD NOT be Disapproved.";
			}
	
			if ($ErrorExists == 0) {
				// Delete From TempPurchasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						 " WHERE PurchaseDt_id In (Select DeliveryDt_id From Temp_DeliveryDt Where Delivery_id = '".$SSaId."' ) ".
						 " AND Journal_Type = 'DI' ";
							 
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 

					
				// Delete From TempDeliveryDt For Selected Record
				$query = " DELETE FROM Temp_DeliveryDt ".
						 " WHERE Delivery_id = '".$SSaId."'";
						 
				if (updateData($connection, $query, true)) {
					// Delete From TempDeliveries For Selected Record
					$query = " DELETE FROM Temp_Deliveries ".
							 " WHERE Delivery_id = '".$SSaId."'";
							
					if (!updateData($connection, $query, true))		 
						$message  = mysql_error(); 
				}
				else {
					$ErrorExists = 1;
					$message  = mysql_error(); 	
				}	
			
			}
		
		}
			
		
	}

		
}

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

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

	
	
	if ($ErrorExists == 0) {
		$query = " Select (ifNull(Delivery_Total,0) + IfNull(Delivery_VAT,0) + IfNull(Delivery_TransportAmount,0) + IfNull(Delivery_BonusAmount,0) - IfNull(Delivery_DiscountAmount,0) + ".
				 "         (ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0))) As Delivery_NetTotal,  ".
				 " ( ifNull(Delivery_TotalBase1,0) + IfNull(Delivery_VatBase1,0) + IfNull(Delivery_TransportAmountBase1,0) + IfNull(Delivery_BonusBase1,0) - IfNull(Delivery_DiscountBase1,0) + ".
				 "  (ifNull(Delivery_Tax1Base1,0) + ifNull(Delivery_Tax2Base1,0) + ifNull(Delivery_Tax3Base1,0) + ifNull(Delivery_Tax4Base1,0) + ifNull(Delivery_Tax5Base1,0))) As Delivery_NetTotalB1,  ".
				 " ( ifNull(Delivery_TotalBase2,0) + IfNull(Delivery_VatBase2,0) + IfNull(Delivery_TransportAmountBase2,0) + IfNull(Delivery_BonusBase2,0) - IfNull(Delivery_DiscountBase2,0) + ".
				 "  (ifNull(Delivery_Tax1Base2,0) + ifNull(Delivery_Tax2Base2,0) + ifNull(Delivery_Tax3Base2,0) + ifNull(Delivery_Tax4Base2,0) + ifNull(Delivery_Tax5Base2,0))) As Delivery_NetTotalB2  ".
				 " From Temp_Deliveries As Deliveries ".
			     " Where Deliveries.Delivery_Id = '".$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_deliveries SET Delivery_Mode = 1, ".
				 " Delivery_CashInBase1 = $vSaCashInB1, Delivery_CashOutBase1 = $vSaCashOutB1, Delivery_CashInBase2 = $vSaCashInB2,  ".
				 " Delivery_CashOutBase2 = $vSaCashOutB2, Delivery_TipsBase1 = $vSaTipsB1, Delivery_TipsAccount = '".$TipsAccount."', ".
				 " Delivery_CashCur = '".$CashCur."', Delivery_CashAccount = '".$CashAccount."', ".
				 " Delivery_Cash = $vSaNetTotal, Delivery_CashBase1 = $vSaNetTotalB1, Delivery_CashBase2 = $vSaNetTotalB2 ".
				 " WHERE Delivery_ID = ".$SSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$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 DeliveryDt.DeliveryDt_Id, DeliveryDt.Client_Code, DeliveryDt.Item_Code, ifNull(Item_NonStock,0) ".
						 " From temp_deliverydt as DeliveryDt Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						 " Where Delivery_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_deliverydt SET DeliveryDt_VatAccount = '".$vSaDtVatAcc."' WHERE DeliveryDt_ID = ".$sub_row[0];
				$result=mysql_query($query,$connection);
			}		
		
		}*/
	}
}

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

	$SaveAllowed = 1;
	$ErrorExists = 0;
	

	
	
	if ($ErrorExists == 0) {
		 
		$query = " UPDATE temp_deliveries SET Delivery_Mode = 0, ".
				 " Delivery_CashInBase1 = 0, Delivery_CashOutBase1 = 0, Delivery_CashInBase2 = 0, Delivery_CashOutBase2 = 0,  ".
				 " Delivery_TipsBase1 = 0, Delivery_Cash = 0, Delivery_CashBase1 = 0, Delivery_CashBase2 = 0 ".
				 " WHERE Delivery_ID = ".$SSaId;
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
		
		if (!($result)){
			$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 DeliveryDt.DeliveryDt_Id, DeliveryDt.Client_Code, DeliveryDt.Item_Code, ifNull(Item_NonStock,0) ".
						 " From temp_deliverydt as DeliveryDt Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						 " Where Delivery_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_deliverydt SET DeliveryDt_VatAccount = '".$vSaDtVatAcc."' WHERE DeliveryDt_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_deliveries WHERE Delivery_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_deliveries SET Currency_Code = '".$txtCurr."' WHERE Delivery_ID = $SSaId ";
	$result=mysql_query($query,$connection);
	
	
	
		
	//Update Detail Amount Columns
	$sub_query = " Select DeliveryDt_id, Currency_Code, ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ".
				 " ifNull(DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ifNull(Deliverydt_DiscountAmount,0), ".
				 " ifNull(Deliverydt_DiscountBase1,0), ifNull(Deliverydt_DiscountBase2,0), ifNull(DeliveryDt_TransportAmount,0), ifNull(DeliveryDt_BonusAmount,0) ".
				 " From temp_deliverydt ".
				 " Where Delivery_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_deliverydt SET  ".
					  " Currency_Code = '".$txtCurr."', ".
					  " DeliveryDt_Price = $vSaDtPrice, DeliveryDt_PriceBase1 = $vSaDtPriceBase1, DeliveryDt_PriceBase2 = $vSaDtPriceBase2, ".
					  " DeliveryDt_PriceTTC = $vSaDtPriceTTC, Deliverydt_priceTTCBase1 = $vSaDtPriceTTCBase1, Deliverydt_priceTTCBase2 = $vSaDtPriceTTCBase2, ".
					  " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2, ".
					  " DeliveryDt_TransportAmount = $vSaDtTrsAmt, DeliveryDt_TransportAmountBase1 = $vSaDtTrsAmtB1, DeliveryDt_TransportAmountBase2 = $vSaDtTrsAmtB2, ".
 					  " DeliveryDt_BonusAmount = $vSaDtBonAmt, DeliveryDt_BonusBase1 = $vSaDtBonAmtB1, DeliveryDt_BonusBase2 = $vSaDtBonAmtB2 ".
					  " Where DeliveryDt_ID = ".$sub_row[0];

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

	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($SSaId, $txtDate, $SSaVatChkbx, $txtSaDiscount, $txtSaDiscountAmt, $txtSaTransportAmt, $txtSaBonusAmt, $vRate, $vRateB1, $vRateB2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, '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(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total ".
				  " From Temp_DeliveryDt ".
				  " Where Delivery_ID = ".$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 DeliveryDt_ID,  ".
				  " ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total ".
				  " From Temp_DeliveryDt As DeliveryDt  ".
				  " Where DeliveryDt.Delivery_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_deliverydt SET ".
					 " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2  ".
					 " Where DeliveryDt_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, '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 ($txthscode == '') $txthscode = "NULL";
	else $txthscode = "'".$txthscode."'";
	
	if ($txtnumber_boxes == '') $txtnumber_boxes = 0;					
	if ($txtgrossweight == '') $txtgrossweight = 0;					
	if ($txtnetweight == '') $txtnetweight = 0;	
	
	if ($txtdestdate == '') $txtdestdate = "NULL";
	else $txtdestdate = "'".insertMySQLDate($PSaMaturityDate)."'";
	
	if (empty($txtSaDiscountAmt))
		$txtSaDiscountAmt = 0;
	if (empty($txtSaDiscount))
		$txtSaDiscount = 0;
	if (empty($txtSaTransportAmt))
		$txtSaTransportAmt = 0;	
	if (empty($txtSaBonusAmt))
		$txtSaBonusAmt = 0;	
	
	$txtCostCentCode = "".$txtCostCentCode;	
	if ($txtCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
	
	$txtProjectCode = "".$txtProjectCode;		
	if ($txtProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
	if (empty($txtSalesmanCode))
		$SalesmanCode = 'Null';
	else
		$SalesmanCode = "'".ereg_replace("'", "\'", trim($txtSalesmanCode))."'";		
		
	if($delivery_cashType == '') $delivery_cashType = "NULL";
	else $delivery_cashType = "'".$delivery_cashType."'";	
		
	$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;
	
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaBonusAmt   	   = 0;
	$vSaBonusAmtB1	   = 0;
	$vSaBonusAmtB2	   = 0;
	
	$vSaDtTrsAmt    = 0;
	$vSaDtTrsAmtB1  = 0;
	$vSaDtTrsAmtB2  = 0;
	
		
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	
	$vSaDtQty     = 0;
	$vSaDtPrice   = 0;
	$vSaDtPriceB1 = 0;
	$vSaDtPriceB2 = 0;
	$vSaDtDiscPer = 0;
	
	$vSaDtPrice         = 0;
	$vSaDtPriceBase1    = 0;
	$vSaDtPriceBase2    = 0;
	$vSaDtPriceTTC      = 0;
	$vSaDtPriceTTCBase1 = 0;
	$vSaDtPriceTTCBase2 = 0;
	$vSaDtDiscAmt       = 0;
	$vSaDtDiscAmtBase1  = 0;
	$vSaDtDiscAmtBase2  = 0;
	$vSaDtItemTax1      = 0;
	$vSaDtItemTax2      = 0;
	$vSaDtItemTax3      = 0;
	$vSaDtItemTax4      = 0;
	$vSaDtItemTax5      = 0;
	
	$ExceedCreditLimit = 0;
	$SaveAllowed = 1;
	$ErrorExists = 0;

	$vSaDtPacking      = 0;
	$vSaDtnbrUnit      = 0;
	
	// Delete From Temp_DeliveryDt For Selected Record Where Qty = 0
	$query = " DELETE FROM Temp_DeliveryDt ".
			 " WHERE Delivery_id = '".$SSaId."' ".
			 " And ifNull(DeliveryDt_Quantity,0) = 0 ";
			 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 			 
	
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_deliverydt ".
				 " Where Delivery_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(DeliveryDt_Quantity,0)) As DeliveryDtQuantity ".
								  " From temp_deliverydt ".
								  " Where Delivery_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;
			$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($ErrorExists== 0){
		$ErrorExists = checkcashdiff('Delivery',$SSaId,$txtCurr,$base1,$base2,$connection);					 
		if($ErrorExists==1) $message  = 'Save not allowed. Net Total And Cash Differs.'; 
	}
	
	if($ErrorExists== 0){
		$ErrorExists = check_date($txtDate, $connection);
		if($ErrorExists==1) $message  = 'Save not allowed. Wrong Date Format.'; 
	}
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_code, ifNull(DeliveryDt_Quantity,0) as DeliveryDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_DeliveryDt As DeliveryDt Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on DeliveryDt.DeliveryDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'DI' ".
					 " 	And Temp_Purchasesserialno.DeliveryDt_ID Is Not Null ".
					 " 	Where DeliveryDt.Delivery_ID = ".$SSaId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By DeliveryDt.DeliveryDt_ID ".
					 " 	Having ifNull(DeliveryDt_Quantity,0) != CountSerialNo ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0 && $module_serialnoout == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Serials.';
		}		 
	}
	
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_code, ifNull(DeliveryDt_Quantity,0) as DeliveryDt_Quantity ".
					 " 	From Temp_DeliveryDt As DeliveryDt ".
					 " 	Where DeliveryDt.Delivery_ID = ".$SSaId.
					 " 	And ifNull(DeliveryDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}
	
	if ($ErrorExists == 0) {
		//Checking If Delivery Related To Sorder And Client Is Changed  XXXXXX
		$sub_query = " Select Distinct Sorder.Client_Code ".
					 " From Sorder Inner Join Temp_Deliveries As Deliveries on Deliveries.Sorder_Reference = Sorder.Sorder_Reference ";
		IF ($Module_ReferenceByCostcenter) 
					 $sub_query =$sub_query." and SORDER.Costcent_code= '".vProjCostCent."'";
		IF ($Module_ReferenceByProject)
					 $sub_query =$sub_query." and SORDER.project_code= '".vProjCostCent."'";	
					 
		$sub_query =$sub_query." Where Delivery_ID = '".$SSaId."'";
		$sub_result = selectData($connection, $sub_query);
		$SorderClientCode = $sub_result[0];
		
		if ($SorderClientCode != '' && $SorderClientCode != $txtClientCode) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Invoice client should be same as Sorder client.';
		}		 
	}
	
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

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

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) >= $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	
	
	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
		if ($Module_Delivery == 0) {	
			$sub_query = " Select DeliveryDt_id, Currency_Code, ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ".
						 " ifNull(DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ifNull(Deliverydt_DiscountAmount,0), ".
						 " ifNull(Deliverydt_DiscountBase1,0), ifNull(Deliverydt_DiscountBase2,0),Item_Code ".
						 " From temp_deliverydt ".
						 " Where Delivery_ID = ".$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];

					
				if ($sub_row[1] != $txtCurr) {
					$vSaDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($PSaDate), $vSaDtPrice, $connection);
					$vSaDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($PSaDate), $vSaDtPriceTTC, $connection);
					$vSaDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($PSaDate), $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;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;
					$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;
					
					$sub_query1 = " UPDATE temp_deliverydt SET  ".
								  " DeliveryDt_Price = $vSaDtPrice, DeliveryDt_PriceBase1 = $vSaDtPriceBase1, DeliveryDt_PriceBase2 = $vSaDtPriceBase2, ".
								  " DeliveryDt_PriceTTC = $vSaDtPriceTTC, Deliverydt_priceTTCBase1 = $vSaDtPriceTTCBase1, Deliverydt_priceTTCBase2 = $vSaDtPriceTTCBase2, ".
								  " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2 ".
								  " Where DeliveryDt_ID = ".$sub_row[0];
					
					//echo $sub_query1; exit;	
					if (!updateData($connection, $sub_query1, true))		 
						$message  = mysql_error(); 
					
				}
				
			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
					" FROM Items WHERE item_Code = '".$sub_row[11]."'";
					
			$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;
			 
			$PSaVatChkbx = $txtSaVatChk;
			
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
					 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
					 " FROM salessetup ";
							 
			$result = selectData($connection, $query);
					
			$vSaStpDirectStkDbt = $result[0];
			$vSaStpDirectStkCrd = $result[1];
			$vSaStpDirectStkCur = $result[2];	
			$vSaStpDiscAcc      = $result[3];	
			$vSaStpCreditVatAcc = $result[4];	
			$vSaStpCreditAcc    = $result[5];	
			$vSaStpPromoAcc     = $result[6];
			$vSaStpTipsAcc      = $result[7];
			
			$vSaStpCreditNonStockAcc    = $result[8];
			$vSaStpCreditVatNonStockAcc = $result[9];
			$vSaStpVatAcc 		  	  	= $result[10];
			$vSaStpVatNonStockAcc 	  	= $result[11];
			$vSaStpVatAccCash	  	  	= $result[12];
			$vSaStpVatNonStockAccCash 	= $result[13];	
			$vSaStpCreditExportAcc	 	= $result[14];
			
			$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_PromotionAcc, Trans_TipsAcc,trans_export ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'SI' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
			// echo $query."<br>";				 
			$result = selectData($connection, $query);
			
			$vTranStpDirectStkDbt = $result[0];
				$vTranStpDirectStkCrd = $result[1];
				$vTranStpDirectStkCur = $result[2];
				$vTranStpVatAcc       = $result[3];
				$vTranStpNonRmVatAcc  = $result[4];
				$vTranStpRmVatAcc     = $result[5];
				$vTranStpNonRmTTCIncAcc  = $result[6];
				$vTranStpRmTTCIncAcc     = $result[7];
				$vTranStpNonRmAcc        = $result[8];
				$vTranStpRmAcc           = $result[9];
				$vTranStpDiscAcc         = $result[10];
				$vTranStpPromoAcc        = $result[11]; 
				$vTranStpTipsAcc         = $result[12]; 
				$vTransStpExportAcc 	 = $result[13];
				
			if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					$vSaDtPromoAcc     = $vTranStpPromoAcc;
					$vSaDtTipsAcc      = $vTranStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 1) {
						if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
						}
					}	
					if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 
				} 
				else {
					$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
					$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
					//$vSaDtVatAcc       = $vSaStpVatAcc;
					$vSaDtDiscAcc      = $vSaStpDiscAcc;
					$vSaDtPromoAcc     = $vSaStpPromoAcc;
					$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
					if ($item_vat > 0 && $PSaVatChkbx == 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 = $vSaStpCreditExportAcc; 						
				}		
						
			$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";//echo $sub_queryVat;exit;
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
			$sub_query1 = " Update temp_deliverydt SET ".
						 " Deliverydt_DirectStkDbt = '".$vSaDtDirectStkDbt."', Deliverydt_DirectStkCrd = '".$vSaDtDirectStkCrd."', ".
						 " Deliverydt_DirectStkCur = '".$vSaDtDirectStkCur."', Deliverydt_discountacc = '".$vSaDtDiscAcc."', ".
						 " Deliverydt_ItemAccount = '".$vSaDtItemAcc."', DeliveryDt_PromoAcc = '".$vSaDtPromoAcc."', ".
						 " DeliveryDt_TipsAccount = '".$vSaDtTipsAcc."', DeliveryDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " Where DeliveryDt_ID = ".$sub_row[0];
				//echo $sub_query1;exit;	
			if (!updateData($connection, $sub_query1, true)){		 
					$message  = mysql_error(); 
				}		
			
			}  //End Loop of DeliveryDt Query
		} //End if ($Module_Delivery == 0) 
		
		
		if ($Module_SerialNo == 0) {
			
			//In Edit Case, If Item Code Is Changed Then SalesOrder and Sales Item
			if ($Module_ChangeInvoiceItems == 1 && $FI_ChangeInvoiceItems == 1) {
			
				$sub_query3 = " Select DeliveryDt_id, Item_Code, RelatedDt_Id, Warehouse_Code ".
							  " From temp_deliverydt ".
							  " Where Delivery_ID = ".$SSaId;	
				$sub_result3 = mysql_query($sub_query3,$connection) or die(mysql_error());
				while($sub_row3=mysql_fetch_array($sub_result3)){
					$vDeliveryDtId = $sub_row3[0];
					$vItemCode     = $sub_row3[1];
					$vRelatedDtId  = $sub_row3[2];
					$vWhCode       = $sub_row3[3];
					
					$sub_query = " Select Item_Code, Warehouse_Code From DeliveryDt Where DeliveryDt_ID = ".$vDeliveryDtId;
					$sub_result = selectData($connection, $sub_query);
					$vExistItemCode = $sub_result[0];
					$vExistWhCode   = $sub_result[1];
					
					if ($vExistItemCode != "" && ($vExistItemCode != $vItemCode || $vExistWhCode != $vWhCode)) {
						
						if ($Module_Delivery == 1) {
							$sub_query1 = " UPDATE SalesDt SET  ".
										  " Item_Code = '".$vItemCode."', ".
										  " Warehouse_Code = '".$vWhCode."' ".
										  " Where RelatedDt_Id = ".$vDeliveryDtId;
							//echo $sub_query1; exit;	
							if (!updateData($connection, $sub_query1, true))		 
								$message  = mysql_error(); 
						}
					
						$sub_query1 = " UPDATE SorderDt SET  ".
									  " Item_Code = '".$vItemCode."', ".
									  " Warehouse_Code = '".$vWhCode."' ".
									  " Where SorderDt_Id = ".$vRelatedDtId;
						//echo $sub_query1; exit;	
						if (!updateData($connection, $sub_query1, true))		 
							$message  = mysql_error(); 
						
						
					}
				
				}				
			}
		}
		
		
		$sub_query2 = " UPDATE temp_deliverydt SET ".
					  " Currency_Code = '".$txtCurr."', Delivery_Date = '".insertMySQLDate($txtDate)."' ";
					  //" Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."' ";
					  
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCent_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Delivery_id = $SSaId ";
		
		//echo $querydt."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
					  
		if ($Module_ProjectDt == 1) {
			$querydt = " UPDATE temp_deliverydt SET Project_Code = $ProjectCode ".
					   " WHERE Delivery_id = $SSaId ".
					   " AND (Project_Code is null or Project_Code = '') ";
			$resultdt=mysql_query($querydt,$connection);
		}
		if ($Module_CostCenterDt == 1) {
			$querydt = " UPDATE temp_deliverydt SET CostCent_Code = $CostCentCode ".
					   " WHERE Delivery_id = $SSaId ".
					   " AND (CostCent_Code is null or CostCent_Code = '') ";
			$resultdt=mysql_query($querydt,$connection);
		}
		
		if ($Module_Delivery == 0) {	
		
			//$DistributeDiscount = Distribute_TotalDiscount($SSaId, $rate_dt, $rate_dt1, $rate_dt2, $connection, $_SESSION['useraccount']);
			
			//Distribute The Total Discount On Detail Table
			$sub_query3 = " Select Sum((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_DeliveryDt ".
						  " Where Delivery_ID = ".$SSaId;
			$sub_result3 = selectData($connection, $sub_query3);
			$vSaTotal   = $sub_result3[0];	
			$vSaDisAmt	= $txtSaDiscountAmt;
			$vSaTrsAmt  = $txtSaTransportAmt;
			
			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 DeliveryDt_ID,  ".
						  " ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ".
						  " ifNull(DeliveryDt_Quantity,0), ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ifNull(DeliveryDt_DiscountPer,0), ".
						  " ifnull(DeliveryDt_DiscountAmount,0) as DeliveryDt_DiscountAmount ".	
						  " From Temp_DeliveryDt As DeliveryDt  ".
						  " Where DeliveryDt.Delivery_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];
				
				
				
				$vSaDtDiscAmt	   = 0;
				if($show_discountAmount == 1) $vSaDtDiscAmt = $sub_rows4[7];
				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;	
				
				$vSaDtSalePrice    = 0;
				$vSaDtSalePriceB1  = 0;
				$vSaDtSalePriceB2  = 0;
				
				if ($vSaDtQty > 0) {
					$vSaDtSalePrice    = $vSaDtPrice   - ($vSaDtPrice*$vSaDtDiscPer/100)   - ($vSaDtDiscAmt/$vSaDtQty)      - ($vSaDtTrsAmt/$vSaDtQty);
					$vSaDtSalePriceB1  = $vSaDtPriceB1 - ($vSaDtPriceB1*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase1/$vSaDtQty) - ($vSaDtTrsAmtB1/$vSaDtQty);
					$vSaDtSalePriceB2  = $vSaDtPriceB2 - ($vSaDtPriceB2*$vSaDtDiscPer/100) - ($vSaDtDiscAmtBase2/$vSaDtQty) - ($vSaDtTrsAmtB2/$vSaDtQty);
				}
				
				$queryupd =  " UPDATE temp_deliverydt SET ".
							 " DeliveryDt_DiscountAmount = $vSaDtDiscAmt, DeliveryDt_DiscountBase1 = $vSaDtDiscAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscAmtBase2,  ".
							 " DeliveryDt_TransportAmount = $vSaDtTrsAmt, DeliveryDt_TransportAmountBase1 = $vSaDtTrsAmtB1, DeliveryDt_TransportAmountBase2 = $vSaDtTrsAmtB2, ".
							 " DeliveryDt_BonusAmount = $vSaDtBonAmt, DeliveryDt_BonusBase1 = $vSaDtBonAmtB1, DeliveryDt_BonusBase2 = $vSaDtBonAmtB2, ".
							 " SaleDt_Price = $vSaDtSalePrice, SaleDt_PriceBase1 = $vSaDtSalePriceB1, SaleDt_PriceBase2 = $vSaDtSalePriceB2 ".
							 " Where DeliveryDt_ID = ".$vSaDtId;
							 //" And Logged_Code = '".$PLoggedCode."' ";
				//echo $queryupd; exit;
				if (!updateData($connection, $queryupd, true))
					$error  = mysql_error(); 
				

			}
			
			//Update Serials ExpireDate and BatchNo From Detail Table
			if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
				$sub_query5 = " Select DeliveryDt_Id, DeliveryDt_ExpireDate, DeliveryDt_BatchNo ".
							  " From Temp_DeliveryDt As DeliveryDt  ".
							  " Where DeliveryDt.Delivery_ID = ".$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 = 'DI' ";
					//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, 'P', $connection);
			$message  = $message . $CalculateResult;
		
			
			if ($Module_InvoiceCheckLimit == 1) {
			
				$clt_query = " SELECT Client_CreditLimit, Client_PaymentTerms, Client_CashMode, Clients.Currency_Code, Client_Paymentterms2  ".
							 " FROM Clients ".
							 " WHERE Ledger_number = '".$txtClientCode."'";
				
				$clt_result = selectData($connection, $clt_query);
				$vCltCreditLimit = $clt_result[0];
				$vCltPaymentTerm = $clt_result[1];
				$vCltCashMode    = $clt_result[2];
				$vCltCurrCode    = $clt_result[3];
				$Client_Paymentterms2    = $clt_result[4];
				
				if ($Module_CreditLimitByProj == 1 && $txtProjectCode != '') {
					$clt_query = "SELECT ifNull(Client_CreditLimit,0) FROM ClientsCreditLimit WHERE Client_Code = '".$txtClientCode."' and '".$txtProjectCode."' like concat(Project_Code,'%') limit 1 ";
					//echo "<br><br>".$clt_query;
					$clt_result = selectData($connection, $clt_query);
					$vCltCreditLimit = $clt_result[0];
				}
				
				// Checking For Client Credit Limit
				$ExceedCreditLimit = 0;
				$vCltCreditLimit   = ConvertCurrency($vCltCurrCode, $txtCurr, insertMySQLDate($txtDate), $vCltCreditLimit, $connection);

				if ($vCltCashMode == "1"){
					$ExceedCreditLimit = 0;
				}else{

				
					if ($FA_ClientPaymentTerms == 1 && $FA_ClientCreditLimit == 1) {
						$ExceedCreditLimit = 0;
					} else {  
						if ($FA_ClientCreditLimit == 0 && $Module_CreditLimit == 1){ 
							$query_sales  = " Select Journal_ID From Temp_Deliveries Where Delivery_id = $SSaId ";
							$result_sales = selectData($connection, $query_sales);
							$vSaJournalID = $result_sales[0];
							if(empty($vSaJournalID)) $vSaJournalID = -1;
							
							//Get Current Balance
							if ($Module_CreditLimitByProj == 1 && $txtProjectCode != '') {
								$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance FROM journaldt ".
												" Left outer Join CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
												" where journaldt.journal_id != ".$vSaJournalID." and journaldt.ledger_number = '".$txtClientCode."' ".
												" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate(displayToday())."','%Y%m%d') ".
												" and CstJour.Project_Code like concat('".$txtProjectCode."', '%') ";
							} else {
								$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(displayToday())."','%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(Delivery_Total,0) + IfNull(Delivery_VAT,0) + ifNull(Delivery_TransportAmount,0) + ifNull(Delivery_BonusAmount,0) - IfNull(Delivery_DiscountAmount,0) ), ".$DecimalBase.") As Delivery_NetTotal ".
										 " From Temp_Deliveries ".
										 " Where Delivery_ID = ".$SSaId;
							$sub_result = selectData($connection, $sub_query);
							$q2 = $sub_result[0];			 
							
							
							if ($vCltCreditLimit >= ($q1 + $q2)){
								$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;
							
						if ($ExceedCreditLimit == 0	) {
							if ($FA_ClientPaymentTerms == 0 && $Module_PaymentTerms == 1 ){
								//Check Client payment Term
								$query = "select IfNull(InvoiceDays('".$txtClientCode."', '".insertMySQLDate(displayToday())."', 0,'".$Client_Paymentterms2."'),0)";
								//echo "<br><br>".$query;exit;
								$result = selectData($connection, $query);
									
								if ($vCltPaymentTerm > $result[0]){
									$ExceedCreditLimit = 0;
								}else{
									$ExceedCreditLimit = 1;
									$message = "Save not allowed. Exceed payment terms.";
								}
							} else
								$ExceedCreditLimit = 0;	
						}	
											
					}
									
				}
			}
					
		} //End if ($Module_Delivery == 0) 		

	 
		//Check If Client Is Changed ==> Change VAT Accounts
		$sub_query7 = " Select Client_Code From Temp_Deliveries Where Delivery_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_deliveries SET ".
					 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', Delivery_VatAccount = '".$vSaVatAcc."' ".
					 " WHERE Delivery_id = '".$SSaId."' ";
			$result=mysql_query($query,$connection);
			
			$sub_query7 = " Select DeliveryDt_ID, DeliveryDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0) ".
						  " From Temp_DeliveryDt as DeliveryDt ".
						  " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						  " Where Delivery_ID = '".$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_deliverydt SET ".
						 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', DeliveryDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " WHERE DeliveryDt_id = '".$sub_rows7[0]."' ";
				$result=mysql_query($query,$connection);
			
			}
			
		}
				 
						 
		if (empty($txtVehicleLoadWeight))   $txtVehicleLoadWeight = 0;
		if (empty($txtVehicleWeight))   $txtVehicleWeight = 0;
        $delivery_date = $_POST['delivery_date'];
		$delivery_card_msg = $_POST['delivery_card_msg'];
		$delivery_contact = $_POST['delivery_contact'];
		$delivery_contactphone = $_POST['delivery_contactphone'];
		if($delivery_date == '') $delivery_date = $txtDate;
		
		$query = " UPDATE temp_deliveries SET ".
				 " Delivery_Date = '".insertMySQLDate($txtDate)."' , ".
				 " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."' , ".
				 " Delivery_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 //" Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
				 " Salesman_Code = $SalesmanCode, Delivery_ShippedTo = '".ereg_replace("'", "\'", trim($txtDAddress))."', ".
				 " Delivery_Marks = '".ereg_replace("'", "\'", trim($txtVehicleNumber))."', Delivery_ShippedVia = '".ereg_replace("'", "\'", trim($txtDriverName))."', ".
				 " Delivery_vehicleweight = $txtVehicleWeight, ".
				 " Delivery_vehicleLoadweight = $txtVehicleLoadWeight, ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode,  ".
				 " Delivery_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."', ".
				 " Delivery_ClientDeliveryDate = '".insertMySQLDate($delivery_date)."', ".
				 " Delivery_ShippingWay = '".$delivery_card_msg."', ".
				 " Delivery_ShipName = '".$delivery_contact."', ".
				 " Delivery_ClientPhone = '".$delivery_contactphone."', ".
				 " GRNNO='".$grnno."', ".
				 " delivery_cashType = ".$delivery_cashType.", ".
				 " delivery_HScode = $txthscode, Delivery_NoCarton = $txtnumber_boxes, Delivery_CartonGrossWt = $txtgrossweight, Delivery_CartonNetWeight = $txtnetweight, ".
				 " deliveries_destinationFrom = ".GetSQLValueString($txtdestfrom,'text').", deliveries_destinationTo = ".GetSQLValueString($txtdestto,'text').", deliveries_destinationDate = ".$txtdestdate." ".
				 " WHERE Delivery_id = $SSaId ";
				
		$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, Costcent_code  FROM Deliveries WHERE Delivery_id = $SSaId ";
				$result  = selectData($connection, $query);
				$vOldProjCode     = $result[0];
				$vOldCostCentCode = $result[1];
				
				$query = "Select Count(*) From Temp_Deliveries where Delivery_ID = '".$SSaId."'";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$ExistInTemp = $result[0];	
				
				//Check If Record Exists In Temp Tables
				if ($ExistInTemp == 1) {
					//echo "test";exit;
					fbegin();
					//echo $SSaId; exit;
					
					$query_module  = "select Module_DirectStockSales as ModuleDirectStockSales from module";
					$result_module = mysql_query($query_module, $connection);
					$row_module    = mysql_fetch_array($result_module);
					extract($row_module);
					
					if($ModuleDirectStockSales == 1){
					
					$query_deliverydt = "select deliverydt_id as DeliveryDtID 
					                     from temp_deliverydt inner join items on temp_deliverydt.item_code = items.item_code
										 where items.Item_Production = 1 and delivery_id = '".$SSaId."'";
					//echo $query_deliverydt; exit;
					$result_deliverydt = mysql_query($query_deliverydt, $connection);
					while($row_deliverydt = mysql_fetch_array($result_deliverydt))
					{
						extract($row_deliverydt);
						$query_cost = "select deliverydt_id, temp_deliverydt.delivery_id, production.Production_Total, production.Production_TotalBase1, production.Production_TotalBase2, production.Production_quantity, production.Currency_Code as ProductionCurrency, temp_deliverydt.Currency_code as DeliverydtCurrency, production.Production_Total/production.Production_quantity as Cost, production.Production_TotalBase1/production.Production_quantity as CostBase1, production.Production_TotalBase2/production.Production_quantity as CostBase2
                                       from production inner join sorderdt on production.RelatedDt_Id = sorderdt.sorderdt_id
                                       inner join temp_deliverydt on temp_deliverydt.RelatedDt_Id = sorderdt.sorderdt_id and deliverydt_id = '".$DeliveryDtID."'";
						//echo $query_cost; exit;
						$result_cost = mysql_query($query_cost, $connection);
						$number_cost = mysql_num_rows($result_cost);
						if($number_cost != 0)
						{
							
							$row_cost = mysql_fetch_array($result_cost);
							extract($row_cost);
							if($ProductionCurrency != $DeliverydtCurrency)
							{
								//echo $Cost."<br>";
								//echo $ProductionCurrency."<br>";
								//echo $DeliverydtCurrency."<br>";
								$Cost = ConvertCurrency($ProductionCurrency, $DeliverydtCurrency, insertMySQLDate($txtDate), $Production_Total, $connection);
								$Cost = $Cost / $Production_quantity;
								//echo $Cost; exit;
							}
							$query_update_cost  = "update temp_deliverydt set Deliverydt_cost = '".$Cost."', Deliverydt_costbase1 = '".$CostBase1."', Deliverydt_costbase2 = '".$CostBase2."' where DeliveryDt_id = '".$deliverydt_id."'";
							$result_update_cost = mysql_query($query_update_cost, $connection);
							//echo $query_update_cost; exit;
						}
						else
						{
							$query_update_cost  = "update temp_deliverydt set Deliverydt_cost = '0', Deliverydt_costbase1 = '0', Deliverydt_costbase2 = '0' where DeliveryDt_id = '".$DeliveryDtID."'";
							$result_update_cost = mysql_query($query_update_cost, $connection);
						}
						//echo $query_update_cost; exit;
						//echo $query_cost."<br>";
					}
					}
					//exit;
					$query_checkDelivery  = "select count(*) as DeliveryExist from deliveries where delivery_id = '$SSaId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($DeliveryExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					//$query_startTransaction  = "start tarnsaction";
					//$result_startTransaction = mysql_query($query_startTransaction, $connection);
					
					//echo $result_insertToHistory;exit;
					//$query_commit  = "COMMIT";
					//$result_commit = mysql_query($query_commit, $connection);
					$query = "SELECT CopyData_TempDelivery('DI', ".$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 Delivery_Reference, Costcent_code, Project_Code, ifNull(Delivery_Mode,0) FROM Deliveries WHERE Delivery_id = $SSaId ";
						$result  = selectData($connection, $query);
						$vSaRef  = $result[0];
						$vCostCentCode = $result[1];
						$vProjectCode  = $result[2];
						$vSaleMode     = $result[3];
						
						$existCode = 0;
						if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vSaRef != ''){
							$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
							$reschk = mysql_query($querychk, $connection);
							$rwchk = mysql_fetch_row($reschk);
							$existCode = $rwchk[0];
						}
						if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vSaRef != ''){
							$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
							$reschk = mysql_query($querychk, $connection);
							$rwchk = mysql_fetch_row($reschk);
							$existCode = $rwchk[0];
						}
						
						if ($vSaRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
							($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							
							if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
							else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
							else $vProjCostCent = '';
							
							fbegin();
							$vSaRef = get_nextsequence('delivery_reference',$vProjCostCent,$connection);	
							fcommit();
							
							$query = " UPDATE deliveries SET ".
									 " Delivery_Reference = $vSaRef ".
									 " WHERE Delivery_id = $SSaId ";
							
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error();
						    
						}	
					
						if ($Module_PostToJournal == 1) {
							$message = Create_DeliveryJv($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_CreateAdjustmentforPack == 1){
							$query = "SELECT create_adjustmentDelivery(".$SSaId.") FROM Dual ";
							//echo $query;exit;
							$result = selectData($connection, $query);
							// $result = $result[0];
						}
						
						if($txtautoReceipt == 1){
						$query_transid = "select deliveries.trans_id,Trans_Reference
										from deliveries
										left join trans on trans.trans_id= deliveries.trans_id
										where delivery_id=$SSaId";
						$res_transid = mysql_query($query_transid,$connection);
						$rw_transid = mysql_fetch_row($res_transid);
						$PTransId = $rw_transid[0];
						$vTransRef = $rw_transid[1];
						if($PTransId == ''){
						fbegin();	
						$PTransId = get_nextsequence('Trans_Id','',$connection);	
						fcommit();
						}
						if($vTransRef == ''){
						fbegin();
							$vTransRef = get_nextsequence('Receipt_RefGovernment',$vProjCostCent,$connection);	
						fcommit();
						
						}
						if($PTransId != '' && $vTransRef != ''){
						
							$query_auto = "call auto_receiptDelivery($SSaId,$PTransId,'$vTransRef', '".$_SESSION['useraccount']."','".$_SESSION['useraccount']."'
                                                ,'".$_SESSION['dbLabel']."','".$_SESSION['dbName']."',0,'$base1', '$base2', @result);";
						//echo $query_auto; 
							
							$res_auto = mysql_query($query_auto,$connection);
							
							$message = Create_TransJv($PTransId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 	
	
						//	echo $message;
						//exit;
						}
						}
						//echo $message; exit; 
						if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSaId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'deliveries', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
					} else{
						$ErrorExists = 1;
						//$message  = mysql_error(); 
						$message  = 'Error In CopyData_TempDelivery 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 ($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);
$PSaDAddress = ereg_replace(' ','%20',$PSaDAddress);
$PSaDriverName = ereg_replace(' ','%20',$PSaDriverName);
$PSaVehicleNumber = ereg_replace(' ','%20',$PSaVehicleNumber);

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

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

$PSaManualNo = ereg_replace(' ','%20',$PSaManualNo);
$PSaManualNo = ereg_replace('#','%23',$PSaManualNo);
$PSaManualNo = ereg_replace('&','%26',$PSaManualNo);


//echo $mode.$message; exit;
//."&txtPurId=".$txtPurId


if($mode == "post") {
	if ($ExceedCreditLimit == 0 && $SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Delivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSaId=".$SSaId."&PrSaRef=".$vSaRef."&langr1=".$PLang);
	else
		header ("Location: ./Form_Delivery.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId."&langr1=".$PLang);
}
//else if($mode == "confirmsales") 
	//header ("Location: ./Form_Delivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSaId=".$SSaId);	
//else if($mode == "" && ($mainmode == "confirmsales" || $mainmode == "unconfirmsales"))
	//header ("Location: ./Form_DeliverySearch.php?message=".$message."&option=".$SOption);	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_DeliverySearch.php?message=".$message."&option=".$SOption);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_DeliverySearchPending.php?message=".$message);
else if ($mode == "cancel" )		
	header ("Location: ./Form_Delivery.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_Delivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_DeliveryDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PSaId=".$SSaId."&PSaDate=".$PSaDate."&PSaDtId=".$SSaDtId);		
else if ($mode == "" && $mainmode == "search" )	{
	if ($AllowEdit == 1)
		header ("Location: ./Form_DeliverySearch.php?PMode=1&message=".$message);	
	else
		header ("Location: ./Form_DeliverySearch.php?PMode=0&message=".$message);

}	
	//header ("Location: ./Form_Delivery.php?actionmode=&mainaction=edit&message=".$message."&txtSaId=".$SSaId);	
else if ($mode == "" && $mainmode == "confirmedsorder" )		
	header ("Location: ./Form_Delivery_LoadSorder.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);		
else if ($mode == "" && $mainmode == "unconfirmorder" )		
	header ("Location: ./Form_Delivery_LoadSorder.php?PMode=0&message=".$message);		
else if ($mode == "" && $mainmode == "disapproveorder" )		
	header ("Location: ./Form_Delivery_LoadSorder.php?PMode=0&message=".$message);
else if ($mode == "" && $mainmode == "disapproveorder1" ) {
	if ($ErrorExists == 0)
		header ("Location: ./Form_Delivery.php");	
	else 
		header ("Location: ./Form_Delivery.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);	
}	
else if ($mode == "" && $mainmode == "loadsorder" )		
	header ("Location: ./Form_Delivery_LoadSorder.php?PMode=1&GeneratedId=".$SSaId."&message=".$message);
else if ($mode == "" && $mainmode == "loaditems" ) {		
	$vActionMode = 'submitrecord';
	if ($message != '') $vActionMode = '';
	
	header ("Location: ./Form_DeliveryLoadItems.php?actionmode=".$vActionMode."&PSaId=".$SSaId."&message=".$message);
}	
else if ($mode == "CashPayment") { 
	if ($message != "")
		header ("Location: ./Form_Delivery_PayCash.php?PMode=0&PSaId=".$SSaId."&message=".$message);
	else
		header ("Location: ./Form_Delivery_PayCash.php?PMode=1&PSaId=".$SSaId."&message=".$message);
}	
else if ($mode == "CreditPayment") { 
	header ("Location: ./Form_Delivery.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
}
else if ($mode == "importfromexcel")	
	header ("Location: ./Form_Delivery.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSaId=".$SSaId);		
else if ($mode == "changecurrency")	
	header ("Location: ./Form_Delivery.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
else if ($mode == "changediscount")	
	header ("Location: ./Form_Delivery.php?actionmode=submitrecord&mainaction=".$mainmode."&txtSaId=".$SSaId."&message=".$message);
else if($mode == "submitrecord") {
    header ("Location: ./Form_DeliveryDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PSaId=".$PSaId.	
			"&PSaDate=".$PSaDate."&PSaMaturityDate=".$PSaMaturityDate."&PSaClientCode=".$PSaClientCode."&PSaSalesmanCode=".$PSaSalesmanCode.
			"&PSaCurr=".$PSaCurr."&PSaProjectCode=".$PSaProjectCode."&PSaCostCentCode=".$PSaCostCentCode."&PSaDiscount=".$PSaDiscount.
			"&PSaDiscountAmt=".$PSaDiscountAmt."&PSaVatChkbx=".$PSaVatChkbx."&lstWarehouse=".$lstWarehouse."&PSaDriverName=".$PSaDriverName.
		    "&PSaVehicleNumber=".$PSaVehicleNumber."&PSaRemark=".$PSaRemark."&PSaIAddress=".$PSaIAddress."&PSaDAddress=".$PSaDAddress.
     		"&PSaManualNo=".$PSaManualNo."&message=".$message."&WarningMsg=".$WarningMsg	);
}else if ($mode == "" && $mainmode == "loadproduct" && $message == '' )		
	header ("Location: ./Form_Delivery_LoadProduction.php?PMode=1&GeneratedId=".$SSaId."&message=".$message);
else if ($mode == "" && $mainmode == "loadproduct" && $message != '' )		
	header ("Location: ./Form_Delivery_LoadProduction.php?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);
	//echo $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;
	
	$vSaTotalWeight = 0;

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

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

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

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

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

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
		$vSaTotalWeight = $vSaTotalWeight + ($sub_rows[10]*$sub_rows[11]);
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		$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;					
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
	
				
	//$vSaTransportAmt   = $PTransportAmt;	
	//$vSaTransportAmtB1 = ($vSaTransportAmt*$PRate)/$PRate1;
	//$vSaTransportAmtB2 = ($vSaTransportAmt*$PRate)/$PRate2;	
				
					
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
	$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();
	$delivery_card_msg     = $_POST['delivery_card_msg'];
	$delivery_contact      = $_POST['delivery_contact'];
	$delivery_contactphone = $_POST['delivery_contactphone'];
	$delivery_date         = $_POST['delivery_date'];
	if($delivery_date == '') $delivery_date = $PDate;
	
	
	//echo $delivery_date;exit;
	$sub_query1 = " UPDATE temp_deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_DiscountPer = $vSaDiscountPer, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_VatChkbx = $PVatChk, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_TransportAmount = $vSaTransportAmt, Delivery_TransportAmountBase1 = $vSaTransportAmtB1, Delivery_TransportAmountBase2 = $vSaTransportAmtB2, Delivery_TransportTTC = $vSaTransportAmtTTC, ".
				  " Delivery_BonusAmount = $vSaBonusAmt, Delivery_BonusBase1 = $vSaBonusAmtB1, Delivery_BonusBase2 = $vSaBonusAmtB2, Delivery_BonusTTC = $vSaBonusAmtTTC, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2,  ".
				  " totalWeight = $vSaTotalWeight, ".
				  " Delivery_ClientDeliveryDate = '".insertMySQLDate($delivery_date)."', ".
				 " Delivery_ShippingWay = '".$delivery_card_msg."', ".
				 " Delivery_ShipName = '".$delivery_contact."', ".
				 " Delivery_ClientPhone = '".$delivery_contactphone."' ".
				  " WHERE Delivery_ID = ".$PId;
	//echo $sub_query1."<br>";exit;	
	$sub_result1=mysql_query($sub_query1,$connection);
	
	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) {
	
	$vSaTotal  = 0;
	$vSaDisAmt = 0;
	$vSaTrsAmt = 0;
	
	$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 Delivery_ID, Deliveries.Currency_code, (ifNull(Delivery_Taxable,0) + ifNull(Delivery_NoneTaxable,0)) As Delivery_Total, ".
				  " ifNull(Delivery_DiscountAmount,0), ifNull(Delivery_TransportAmount,0) ".
				  " From Temp_Deliveries As Deliveries  ".
				  " Where Delivery_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];
	$vSaTrsAmt  = $rowstotal[4];
	
	$query = " Select DeliveryDt_ID,  ".
             " ((DeliveryDt_Quantity*DeliveryDt_Price)-((DeliveryDt_Quantity*DeliveryDt_Price*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ".
			 " ifNull(DeliveryDt_Quantity,0), ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_PriceBase1,0), ifNull(DeliveryDt_PriceBase2,0), ".
			 " ifNull(DeliveryDt_DiscountPer,0), ifNull(DeliveryDt_TransportAmount,0), ifNull(DeliveryDt_TransportAmountBase1,0), ifNull(DeliveryDt_TransportAmountBase2,0) ".
         	 " From Temp_DeliveryDt As DeliveryDt  ".
			 " Where DeliveryDt.Delivery_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];
		//$vSaDtTrsAmt  = $rows[7];
		//$vSaDtTrsAmtB1  = $rows[8];
		//$vSaDtTrsAmtB2  = $rows[9];
		
		$vSaDtDiscountAmt = 0;
		$vSaDtDiscountAmt      = ($vSaDtTotal/$vSaTotal)*$vSaDisAmt;
		$vSaDtDiscountAmtBase1 = ($vSaDtDiscountAmt*$PRate)/$PRate1;
		$vSaDtDiscountAmtBase2 = ($vSaDtDiscountAmt*$PRate)/$PRate2;
		
		$vSaDtTrsAmt = 0;
		$vSaDtTrsAmt    = ($vSaDtTotal/$vSaTotal)*$vSaTrsAmt;
		$vSaDtTrsAmtB1  = ($vSaDtTrsAmt*$PRate)/$PRate1;
		$vSaDtTrsAmtB2  = ($vSaDtTrsAmt*$PRate)/$PRate2;
		
		$vSaDtSalePrice    = 0;
		$vSaDtSalePriceB1  = 0;
		$vSaDtSalePriceB2  = 0;
		
		if ($vSaDtQty > 0) {
			$vSaDtSalePrice    = $vSaDtPrice   - ($vSaDtPrice*$vSaDtDiscPer/100)   - ($vSaDtDiscountAmt/$vSaDtQty)      - ($vSaDtTrsAmt/$vSaDtQty);
			$vSaDtSalePriceB1  = $vSaDtPriceB1 - ($vSaDtPriceB1*$vSaDtDiscPer/100) - ($vSaDtDiscountAmtBase1/$vSaDtQty) - ($vSaDtTrsAmtB1/$vSaDtQty);
			$vSaDtSalePriceB2  = $vSaDtPriceB2 - ($vSaDtPriceB2*$vSaDtDiscPer/100) - ($vSaDtDiscountAmtBase2/$vSaDtQty) - ($vSaDtTrsAmtB2/$vSaDtQty);
		}
		
		$queryupd =  " UPDATE temp_deliverydt SET DeliveryDt_DiscountAmount = $vSaDtDiscountAmt, ".
					 " DeliveryDt_DiscountBase1 = $vSaDtDiscountAmtBase1, DeliveryDt_DiscountBase2 = $vSaDtDiscountAmtBase2,  ".
					 " SaleDt_Price = $vSaDtSalePrice, SaleDt_PriceBase1 = $vSaDtSalePriceB1, SaleDt_PriceBase2 = $vSaDtSalePriceB2, ".
					 " DeliveryDt_TransportAmount = $vSaDtTrsAmt, DeliveryDt_TransportAmountBase1 = $vSaDtTrsAmtB1, DeliveryDt_TransportAmountBase2 = $vSaDtTrsAmtB2 ".
					 " Where DeliveryDt_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_DeliveryJv($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_DeliveryAutoJv(".$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_DeliveryAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_DeliveryJv: '.$error;

	Return $error;
	

}
function Create_TransJv($PTransId, $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_TransAutoJv(".$PTransId.", 1, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', @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 || $cur1[0] == -1)
	   $error = 'Error In Procedure Create_TransAutoJv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_TransJv: '.$error;

	Return $error;
	

}


function check_date($txtdate, $connection){
	$ndates = explode('/', trim($txtdate));

	if (empty($ndates)) {
		$ErrorExists = 1;
	}
	else {
		$ndate = $ndates[2]."-".$ndates[1]."-".$ndates[0];
		$datechk = "select 1 from dual where UNIX_TIMESTAMP('$ndate') != 0";
		$reschk = mysql_query($datechk,$connection);
		$rwchk = mysql_num_rows($reschk);
		if ($rwchk == 0)
			$ErrorExists = 1;
	}

	return $ErrorExists;	
}
/*
print <<<HERE
</form>
</body>

HERE;
*/

?>