
<?php
/*
SaleDt_ItemStatus :
1- Item Gift
2- Item Void
3- Item Waste
4- Item Hold
5- Fire
*/

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

include("config.inc.php");
include("Functions_Sales.php");
include("function.inc.php");
include("Functions_Synchro.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");
 
 
 //Read From CashRegister Table
$queryCashRegister=" Select Currency_Code as cashregcurr ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}



//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(CashReg_Weight,0) As CashReg_Weight, CashReg_StartBarcode, CashReg_EndBarcode, CashReg_StartQty, CashReg_EndQty,  ".
			 " ifNull(CashReg_Price,0) As CashReg_Price, CashReg_StartPrice, CashReg_EndPrice, Setup_Branch,IfNull(Discount_Amount,0) As Discount_AmountPer, ".
			 " company_email, project_no, costcent_no, ifNull(Setup_TipsMaxAmount, 0) As Setup_TipsMaxAmount, ifnull(POS_RedeemPoints,0) as POS_RedeemPoints,  ".
			 " ifNull(CashReg_RoundDivisor,1) As CashReg_RoundDivisor ".
			 " From Setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


//Read From Setup Table							
$querysalessetup= " select ifNull(Sale_ExchangeSellPrice,0) As Sale_ExchangeSellPrice From SalesSetup ";
$resultsalessetup=mysql_query($querysalessetup,$connection) or die(mysql_error());
while($rowsalessetup=mysql_fetch_array($resultsalessetup)){
	extract($rowsalessetup);
}


//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_Delivery,0) As Module_Delivery, ifNull(Module_PriceOffer,0) As Module_PriceOffer, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_PostRetailOneToOne,0) As Module_PostRetailOneToOne, ".
			 " ifNull(Module_PackCostPerc,0) As Module_PackCostPerc, ifNull(Module_PostingByCashRegister,0) As Module_PostingByCashRegister, ".
			 " ifNull(Module_CashRegItemQtyInCode,0) As Module_CashRegItemQtyInCode, ifNull(Module_CashRegItemSeperate,0) As Module_CashRegItemSeperate, ".
			 " ifNull(Module_Synchro,0) As Module_Synchro  , ifNull(Module_GroupHoldFire,0) As Module_GroupHoldFire,  ifNull(Module_sizes,0) As Module_sizes, ".
			 "  ifNull(Module_Color,0) As Module_Color, ifnull(Module_CheckNegativeQtyBeforePosting,0) as Module_CheckNegativeQtyBeforePosting,".
			 " ifnull(Module_RewardPointPer,0) as Module_RewardPointPer, ifnull(module_PriceByQty,0) as module_PriceByQty".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Read From CashRegister Table
$queryCashRegister=" Select Upper(CashRegister_Name) As CashRegister_Name, Currency_Code As StpCurrCode, CostCenter_Code As StpCostCentCode, Project_Code As StpProjectCode, ".
                   " ifNull(CashRegister_SerialNo,0) As CashRegisterSerialNo, CashRegister_Discount, CashRegisterTTC, Client_Account As StpClientAccount, Warehouse_Code As StpWarehouseCode, ".
				   " ifNull(CashRegister_AutoPost,0) As CashRegister_AutoPost, ifNull(CashRegister_RestSerialNo,0) As CashRegister_RestSerialNo, ".
				   " ifNull(CashRegister_DisplayLed,0) As CashRegister_DisplayLed, ifNull(CashRegister_DispCOM,0) As CashRegister_DispCOM, ".
				   " ifNull(CashRegister_LedDescLength,0) As CashRegister_LedDescLength ,ifNull(Module_CashRegAutoItemsList,0) As Module_CashRegAutoItemsList,ifNull(cashregister_DPbeforePosting,0) as cashregister_DPbeforePosting, ".
				   " ifNull(Module_RestaurantDelivery,0) As Module_RestaurantDelivery, ifnull(cashregister_service,0) as cashregister_service, ifnull(cashregister_servicePercentage, 0) as cashregister_servicePercentage, ".
				   " ifnull(cashregister_TaxConsumption,0) as cashregister_TaxConsumption, ifnull(cashregister_TaxConsumptionpPer,0) as cashregister_TaxConsumptionpPer, ifnull(cashregister_ShowTaxConsumptionchkbox,0) as cashregister_ShowTaxConschkbox, ".
				   " RedeemPoints_Account ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}

//Read From Login Table
$querylog=" select ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifnull(FI_MultiplePosting,0) as FI_MultiplePosting,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);
}


$queryListDir = " select ifnull(FC_ChangeRetailDate,0) as FC_ChangeRetailDate ".
				" from  ".$_SESSION['dbLabel'].".ListUserDir ".
				" where Usercode = '".$_SESSION['useraccount']."' and upper(concat(CompanyName,'_',Diryear)) = Upper('".$_SESSION['dbName']."') ";
$resultListDir=mysql_query($queryListDir) or die(mysql_error());
while($rows=mysql_fetch_array($resultListDir)){
	extract($rows);
}



if (empty($FI_BelongsToGrp)) $FI_BelongsToGrp = 0;

$mode		 	= $_GET['mode'];			if ($mode == ""){			$mode 			= $_POST["mode"];} 
$mainmode 		= $_GET['mainmode'];		if ($mainmode == ""){		$mainmode 		= $_POST["mainmode"];}
$noprint 	 	= $_GET["noprint"]; 		if ($noprint == ""){		$noprint 		= $_POST["noprint"];}   
$SRetId 	 	= $_GET['SRetId'];			if ($SRetId == ""){			$SRetId 		= $_POST["SRetId"];}
$SRetDtId    	= $_GET['SRetDtId'];		if ($SRetDtId == ""){		$SRetDtId 		= $_POST["SRetDtId"];}
$SItemOption 	= $_GET['SItemOption'];		if ($SItemOption == ""){	$SItemOption 	= $_POST["SItemOption"];}

$txtDate 		  = $_GET["txtDate"]; 				if ($txtDate == ""){			$txtDate 			= $_POST["txtDate"];} 
$txtCurr 		  = $_GET["txtCurr"]; 				if ($txtCurr == ""){			$txtCurr 			= $_POST["txtCurr"];} 
$txtOrderId 	  = $_GET["txtOrderId"]; 			if ($txtOrderId == ""){			$txtOrderId 		= $_POST["txtOrderId"];} 
$txtClientCode 	  = $_GET["txtClientCode"]; 		if ($txtClientCode == ""){		$txtClientCode	 	= $_POST["txtClientCode"];}
$txtCashRegister  = $_GET["txtCashRegister"]; 		if ($txtCashRegister == ""){	$txtCashRegister 	= $_POST["txtCashRegister"];} 
$txtProjectCode   = $_GET["txtProjectCode"]; 		if ($txtProjectCode == ""){		$txtProjectCode 	= $_POST["txtProjectCode"];} 
$txtTableGuests   = $_GET["txtTableGuests"]; 		if ($txtTableGuests == ""){		$txtTableGuests 	= $_POST["txtTableGuests"];} 
$txtGuestname	  = $_GET["txtGuestname"]; 			if ($txtGuestname == ""){		$txtGuestname 		= $_POST["txtGuestname"];} 	
$txtCostCentCode  = $_GET["txtCostCentCode"]; 		if ($txtCostCentCode == ""){	$txtCostCentCode 	= $_POST["txtCostCentCode"];} 
$PRetDate 		  = $_GET["PRetDate"]; 				if ($PRetDate == ""){			$PRetDate 			= $_POST["PRetDate"];} 
$PRetCurr 		  = $_GET["PRetCurr"]; 				if ($PRetCurr == ""){			$PRetCurr 			= $_POST["PRetCurr"];} 
$PRetCostCentCode = $_GET["PRetCostCentCode"]; 		if ($PRetCostCentCode == ""){	$PRetCostCentCode 	= $_POST["PRetCostCentCode"];} 
$PRetProjectCode  = $_GET["PRetProjectCode"]; 		if ($PRetProjectCode == ""){	$PRetProjectCode 	= $_POST["PRetProjectCode"];} 
$PRetCashRegister = $_GET["PRetCashRegister"]; 		if ($PRetCashRegister == ""){	$PRetCashRegister 	= $_POST["PRetCashRegister"];} 
$PRetClientCode   = $_GET["PRetClientCode"]; 		if ($PRetClientCode == ""){		$PRetClientCode 	= $_POST["PRetClientCode"];} 
$txtItemBarcode   = $_GET["txtItemBarcode"]; 		if ($txtItemBarcode == ""){		$txtItemBarcode 	= $_POST["txtItemBarcode"];} 
$txtItemCode 	  = $_GET["txtItemCode"]; 			if ($txtItemCode == ""){		$txtItemCode 		= $_POST["txtItemCode"];} 
$txtItemQty 	  = $_GET["txtItemQty"]; 			if ($txtItemQty == ""){			$txtItemQty 		= $_POST["txtItemQty"];} 
$txtItemPrice 	  = $_GET["txtItemPrice"]; 			if ($txtItemPrice == ""){		$txtItemPrice 		= $_POST["txtItemPrice"];} 
$txtVendorCode 	  = $_GET["txtVendorCode"]; 		if ($txtVendorCode == ""){		$txtVendorCode		= $_POST["txtVendorCode"];} 
$txtSlipNo 		  = $_GET["txtSlipNo"]; 			if ($txtSlipNo == ""){			$txtSlipNo 			= $_POST["txtSlipNo"];} 

$txtRetDtQty 	  = $_GET["txtRetDtQty"]; 			if ($txtRetDtQty == ""){		$txtRetDtQty 		= $_POST["txtRetDtQty"];} 
$txtRetDtPrice    = $_GET["txtRetDtPrice"]; 		if ($txtRetDtPrice == ""){		$txtRetDtPrice 		= $_POST["txtRetDtPrice"];} 
$txtRetDtDiscount = $_GET["txtRetDtDiscount"]; 		if ($txtRetDtDiscount == ""){	$txtRetDtDiscount 	= $_POST["txtRetDtDiscount"];} 
$txtRetDtVendor   = $_GET["txtRetDtVendor"]; 		if ($txtRetDtVendor == ""){		$txtRetDtVendor 	= $_POST["txtRetDtVendor"];} 
$txtRetDtSlip 	  = $_GET["txtRetDtSlip"]; 			if ($txtRetDtSlip == ""){		$txtRetDtSlip 		= $_POST["txtRetDtSlip"];} 
$txtWarehouseCode = $_GET["txtWarehouseCode"]; 		if ($txtWarehouseCode == ""){	$txtWarehouseCode 	= $_POST["txtWarehouseCode"];} 

$txtRetCurr 		= $_GET["txtRetCurr"]; 			if ($txtRetCurr == ""){				$txtRetCurr 		= $_POST["txtRetCurr"];} 
$txtAllowDisc 		= $_GET["txtAllowDisc"]; 		if ($txtAllowDisc == ""){			$txtAllowDisc 		= $_POST["txtAllowDisc"];} 
$txtRetDiscountAmt 	= $_GET["txtRetDiscountAmt"]; 	if ($txtRetDiscountAmt == ""){		$txtRetDiscountAmt 	= $_POST["txtRetDiscountAmt"];} 
$txtRetDiscountPer 	= $_GET["txtRetDiscountPer"]; 	if ($txtRetDiscountPer == ""){		$txtRetDiscountPer 	= $_POST["txtRetDiscountPer"];} 
$txtDateFrom 		= $_GET["txtDateFrom"]; 		if ($txtDateFrom == ""){			$txtDateFrom 		= $_POST["txtDateFrom"];} 
$txtDateTo 	 		= $_GET["txtDateTo"]; 			if ($txtDateTo == ""){				$txtDateTo 			= $_POST["txtDateTo"];} 

$txtRetDate 		= $_GET["txtRetDate"]; 			if ($txtRetDate == ""){				$txtRetDate 		= $_POST["txtRetDate"];} 
$txtRetCustomerCode = $_GET["txtRetCustomerCode"]; 	if ($txtRetCustomerCode == ""){		$txtRetCustomerCode = $_POST["txtRetCustomerCode"];} 
$txtRetSalesmanCode = $_GET["txtRetSalesmanCode"]; 	if ($txtRetSalesmanCode == ""){		$txtRetSalesmanCode = $_POST["txtRetSalesmanCode"];} 
$txtRetRemark 		= $_GET["txtRetRemark"];		if ($txtRetRemark == ""){			$txtRetRemark	 	= $_POST["txtRetRemark"];} 
$txtRetCouponId 	= $_GET["txtRetCouponId"]; 		if ($txtRetCouponId == ""){			$txtRetCouponId 	= $_POST["txtRetCouponId"];} 
$txtRetCouponAmt 	= $_GET["txtRetCouponAmt"]; 	if ($txtRetCouponAmt == ""){		$txtRetCouponAmt 	= $_POST["txtRetCouponAmt"];}   
$txtRetCreditCard 	= $_GET["txtRetCreditCard"]; 	if ($txtRetCreditCard == ""){		$txtRetCreditCard 	= $_POST["txtRetCreditCard"];}   
$txtRetCreditName 	= $_GET["txtRetCreditName"]; 	if ($txtRetCreditName == ""){		$txtRetCreditName 	= $_POST["txtRetCreditName"];}   
$txtRetCreditCurr 	= $_GET["txtRetCreditCurr"]; 	if ($txtRetCreditCurr == ""){		$txtRetCreditCurr 	= $_POST["txtRetCreditCurr"];}   
$txtRetCreditAmt 	= $_GET["txtRetCreditAmt"]; 	if ($txtRetCreditAmt == ""){		$txtRetCreditAmt 	= $_POST["txtRetCreditAmt"];}   
$txtRetCheckNo 		= $_GET["txtRetCheckNo"]; 		if ($txtRetCheckNo == ""){			$txtRetCheckNo 		= $_POST["txtRetCheckNo"];}   
$txtRetCheckDate 	= $_GET["txtRetCheckDate"]; 	if ($txtRetCheckDate == ""){		$txtRetCheckDate 	= $_POST["txtRetCheckDate"];}   
$txtRetBankName 	= $_GET["txtRetBankName"]; 		if ($txtRetBankName == ""){			$txtRetBankName 	= $_POST["txtRetBankName"];}   
$txtRetBranchName 	= $_GET["txtRetBranchName"]; 	if ($txtRetBranchName == ""){		$txtRetBranchName 	= $_POST["txtRetBranchName"];}   
$txtRetCashCurr 	= $_GET["txtRetCashCurr"]; 		if ($txtRetCashCurr == ""){			$txtRetCashCurr 	= $_POST["txtRetCashCurr"];}   
$txtRetCashAmt 		= $_GET["txtRetCashAmt"]; 		if ($txtRetCashAmt == ""){			$txtRetCashAmt	 	= $_POST["txtRetCashAmt"];}   
$txtRetCashInB1 	= $_GET["txtRetCashInB1"]; 		if ($txtRetCashInB1 == ""){			$txtRetCashInB1 	= $_POST["txtRetCashInB1"];}   
$txtRetCashOutB1 	= $_GET["txtRetCashOutB1"]; 	if ($txtRetCashOutB1 == ""){		$txtRetCashOutB1 	= $_POST["txtRetCashOutB1"];}   
$txtRetCashInB2 	= $_GET["txtRetCashInB2"]; 		if ($txtRetCashInB2 == ""){			$txtRetCashInB2 	= $_POST["txtRetCashInB2"];}   
$txtRetCashOutB2 	= $_GET["txtRetCashOutB2"]; 	if ($txtRetCashOutB2 == ""){		$txtRetCashOutB2 	= $_POST["txtRetCashOutB2"];}   
$txtRetTipsB1H 		= $_GET["txtRetTipsB1H"]; 		if ($txtRetTipsB1H == ""){			$txtRetTipsB1H 		= $_POST["txtRetTipsB1H"];}   

$txtStatusRemark     	= $_GET["txtStatusRemark"]; 		if ($txtStatusRemark == ""){		$txtStatusRemark 		= $_POST["txtStatusRemark"];} 
$txtCashRegisterName 	= $_GET["txtCashRegisterName"]; 	if ($txtCashRegisterName == ""){	$txtCashRegisterName 	= $_POST["txtCashRegisterName"];} 
$txtSaleStatus 			= $_GET["txtSaleStatus"]; 			if ($txtSaleStatus == ""){			$txtSaleStatus 			= $_POST["txtSaleStatus"];} 
$txtRetCustomerCode 	= $_GET["txtRetCustomerCode"]; 		if ($txtRetCustomerCode == ""){		$txtRetCustomerCode 	= $_POST["txtRetCustomerCode"];} 
$txtRetDriverCode 		= $_GET["txtRetDriverCode"]; 		if ($txtRetDriverCode == ""){		$txtRetDriverCode 		= $_POST["txtRetDriverCode"];} 

$TransType 			= $_GET['TransType'];			if ($TransType == ""){				$TransType 			= $_POST["TransType"];}
$CashReg 			= $_GET['CashReg'];				if ($CashReg == ""){				$CashReg 			= $_POST["CashReg"];}
$CloseAmount 		= $_GET['CloseAmount'];			if ($CloseAmount == ""){			$CloseAmount 		= $_POST["CloseAmount"];}
$txtCashCurr   		= $_GET['txtCashCurr'];			if ($txtCashCurr == ""){			$txtCashCurr 		= $_POST["txtCashCurr"];}
$txtCashAmount 		= $_GET['txtCashAmount'];		if ($txtCashAmount == ""){			$txtCashAmount 		= $_POST["txtCashAmount"];}
$txtCashDesc   		= $_GET['txtCashDesc'];			if ($txtCashDesc == ""){			$txtCashDesc 		= $_POST["txtCashDesc"];}
$txtGroupHoldFire   = $_GET['txtGroupHoldFire'];	if ($txtGroupHoldFire == ""){		$txtGroupHoldFire 	= $_POST["txtGroupHoldFire"];}
$REMARKINV			= $_GET['REMARKINV']; 			if($REMARKINV == ""){ 				$REMARKINV 			= $_POST['REMARKINV']; }
$txtLedgernbr 		= $_GET['txtLedgernbr'];		 	
$txtbyPc 		= $_GET['byPc'];		 	
/*
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<script type="text/javascript" language="javascript">


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='insertsales' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SRetId' value='$SRetId'>
<input type='text' name='SRetDtId' value='$SRetDtId'>
<input type='text' name='SItemOption' value='$SItemOption'>

HERE;*/

$query_ledger = "select customer.ledger_number from customer
				left join clients on customer.ledger_number = clients.ledger_number
				where customer.ledger_number = '$txtLedgernbr'"; 
$result_ledger = mysql_query($query_ledger, $connection);
$rownum = mysql_num_rows($result_ledger); 
$row_ledger = mysql_fetch_row($result_ledger); 

//echo $query_ledger;exit;

if($cashregister_ShowTaxConschkbox == 0) $taxConsumptionChk = 1;
if($mainmode =='checkitem' && $txtItemBarcode != '' ){
	$txtItemBarcode = urldecode($txtItemBarcode); 
	$txtItemBarcode = urldecode($txtItemBarcode);
	// $querydel = "select count(*) from items where if( item_weight = 0 ,item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' 
							// or item_code = '".$txtItemBarcode."' , if( item_weight = 0)";
	// // item_code = '$txtItemBarcode' or item_barcode = '$txtItemBarcode'
	// $resdel = mysql_query($querydel,$connection);
	// $row = mysql_fetch_row($resdel);
	// echo "[BRK]";
	// if($row[0] == 0) echo 'item not registered!';
	
	// $txtItemBarcode = GetSQLValueString($txtItemBarcode,'text');
	
	if ($Module_CashRegItemQtyInCode == 1 ) {
		$vSubBarcode = substr($txtItemBarcode,($CashReg_StartBarcode - 1),($CashReg_EndBarcode - $CashReg_StartBarcode + 1));
		$queryexists = "Select 1 from Items 
					WHERE (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' 
							or item_code = '".$vSubBarcode."' )	and ifnull(item_active,0) = 1 and (ifnull(Item_Weight,0) = 1000 or ifnull(Item_NetWeight,0) = 1000 or ifnull(Item_Weight,0) = 1001 or ifnull(Item_NetWeight,0) = 1001) ";
		$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
		$itemExists=mysql_num_rows($resultExists);
		if($itemExists==0) $vSubBarcode = $txtItemBarcode;

	} else $vSubBarcode = $txtItemBarcode;
	$queryexists = "Select 1 from Items 
					WHERE (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' 
							or item_code = '".$vSubBarcode."' )	and ifnull(item_active,0) = 1 and ifnull(item_isNotAvailable,0) = 0 ";
	$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
	$itemExists=mysql_num_rows($resultExists);
	
	echo "[BRK]";
	if($itemExists == 0) echo 'item not registered!';
	
	$querydel = "select if(ifnull(item_qtypack,0)>0 , 1 , 0) from items where (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' 
							or item_code = '".$txtItemBarcode."' ) ";
	// item_code = '$txtItemBarcode' or item_barcode = '$txtItemBarcode'
	$resdel = mysql_query($querydel,$connection);
	$row = mysql_fetch_row($resdel);
	echo "[BRK]";
	echo $row[0];
	echo "[BRK]";
	exit;
	// txtItemBarcode
}
// var_dump($_POST);exit;

if($mainmode == 'deletePromoItem' ){
	$querydel = "delete from item_promotion where promotion_id = $PromoId ";
	$resdel = mysql_query($querydel,$connection);
	$message = mysql_error();
	
	header("location:./Form_RetailEditPromo.php?message=$message");
	exit;	
}

if(($mode == 'checkService' || $mode == 'checkTaxConsumption') && $SRetId != ''){
	$query = "select Sale_NetTotal, Sale_Total, Sale_VAT, sale_TaxConsumption, Sale_DiscountAmount, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Currency_Code, sale_service
			from temp_retail where Sale_ID = $SRetId ";
	$result = mysql_query($query, $connection);
	$row = mysql_fetch_row($result);
	$vRetNetTotal 	= $row[0];
	$vRetGrossTotal = $row[1];
	$vRetVat 		= $row[2];
	$vRetTaxConsp 	= $row[3];
	$vRetDiscountAmt = $row[4];
	$vRetTax1 		= $row[5];
	$vRetTax2 		= $row[6];
	$vRetTax3 		= $row[7];
	$vRetTax4 		= $row[8];
	$vRetTax5 		= $row[9];
	$vRetCurr 		= $row[10];
	$vRetService 	= $row[11];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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($mode == 'checkService'){
		if ($serviceChecked == 1){
			$vRetService = (($vRetGrossTotal)*$cashregister_servicePercentage/100);
			$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
			$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
		}	
		else {
			$vRetService = 0;
			$vRetServiceBase1 = 0;
			$vRetServiceBase2 = 0;
		}
	}
	
	if($mode == 'checkTaxConsumption'){
		if ($taxConsumptionChk == 1){
			$vRetTaxConsp = (($vRetGrossTotal)*$cashregister_TaxConsumptionpPer/100);
			$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
			$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
		}
		else {
			$vRetTaxConsp = 0;
			$vRetTaxConspBase1 = 0;
			$vRetTaxConspBase2 = 0;
		}
	}	
	$vRetNetTotal         = $vRetGrossTotal + $vRetVat + $vRetService +  $vRetTaxConsp - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
	$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
	$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;

	if($mode == 'checkService')
		$query = " UPDATE temp_retail SET ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked ".
				 " WHERE Sale_ID = ".$SRetId;
	else if($mode == 'checkTaxConsumption')	
		$query = " UPDATE temp_retail SET ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, sale_TaxConsumptionChecked = $taxConsumptionChk ".
				 " WHERE Sale_ID = ".$SRetId;	
	$result=mysql_query($query,$connection);
exit;	
}

if($mode=='payment' && $row_ledger[0] != '' && $Module_RewardPointPer == 0){ 
	$query_prevPoint = "select customer_point from customer where ledger_number = '$row_ledger[0]' and Customer_special=1"; //echo $query_prevPoint; exit;
	$result_prevPoint = mysql_query($query_prevPoint, $connection);
	$row_prevPoint = mysql_fetch_row($result_prevPoint);
	if($row_prevPoint[0] !='') $prev_point = $row_prevPoint[0];
	else $prev_point = 0;
	
	
	$query_point = "select FLOOR($txtRetCreditAmt/amount)*retail_point from retailpoint";//echo $query_point;exit;
	$result_point = mysql_query($query_point, $connection); 
	$row_point = mysql_fetch_row($result_point);
	
	$customer_point = $prev_point+$row_point[0]; 
	if($customer_point>0) {
	$query_uppoint = "update customer set customer_point = $customer_point where ledger_number = '$row_ledger[0]' and Customer_special=1"; //echo $query_uppoint; exit;
	$result_uppoint = mysql_query($query_uppoint, $connection);
	}
	
}

$message='';
$IsAvailable = 1;

$txtItemBarcode = trim($txtItemBarcode);
$txtItemCode    = trim($txtItemCode);

//Submit Record Mode
//Case SerialNo ...........

if($mode == 'checkItemSellingPrice'){
	$query = "select ifnull(Item_SellingPrice1,0) from items where item_code='$txtItemBarcode'";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	if($row[0] == '') $row[0] = 0;
	echo "[BRK]";
	//echo $query;
	echo $row[0];
	exit;
}

if($mode == 'checkitemmodifysellingPrice'){
	$query = "select ifnull(Item_ModifySellingPrice,0) from items where item_code='$txtItemBarcode'";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	if($row[0] == 0) $row[0] = 'NO';
	if($row[0] == 1) $row[0] = 'OK';
	echo "[BRK]";
	//echo $query;
	echo $row[0];
	exit;
}

if($mode == 'checkItemCostX'){
	$txtItemPrice = $_POST['txtItemPrice']; if ($txtItemPrice == '' ) $txtItemPrice = $_GET['txtItemPrice'];
	$checkPrice = 1;
	$query = "select meancostcur(item_code,now(),1,'$base1','$base1')  from items where item_code='$txtItemBarcode' or item_barcode = '$txtItemBarcode'";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	if($row[0] == '') $row[0] = 0;
	$message='';
	//JP Solution
	if($txtItemPrice == ''){
		$querySP = "select Item_SellingPrice1Base1  from items where (item_code='$txtItemBarcode' or item_barcode = '$txtItemBarcode')
		and item_code not in (select distinct promotion_itemCode from item_promotion where now() between promotion_fromdate and promotion_todate)";
		$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;
	}
 	if(($txtItemPrice < $row[0] || $txtItemPrice == 0) && $checkPrice == 1)
		$message =  'insert not Allowed Price below Cost !';
	echo "[BRK]";
		echo   $message;
	exit;
}
if ($mode == "submitrecord2" && $txtItemBarcode != '') { 
	
	$vRetId = $SRetId;
	$vItemSerialNo  = $txtItemBarcode;
	$vWarehouseCode = $StpWarehouseCode;	
	
	if ($CashRegister_RestSerialNo == 1) {
	
		$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
				" From purchasesserialno ".
				" where SerialNo_Code =  '".$vItemSerialNo."' ".
				" And Journal_Type in ('PI','DR','TR','AI','PD')";
		//echo $query; exit;		  
		$result = selectData($connection, $query);
		$SerialNoExists = $result[0];
		
		$IsAvailable = 1;
		$ErrorExists = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		$SelectedItemCode      = '';
		
		if ($SerialNoExists != '') {
			if ($vWarehouseCode != '' && isset($vWarehouseCode)) {
			
				$sub_query= " Select SerialNo_Code  ".
							" From temp_purchasesserialno ".
							" where SerialNo_Code =  '".$vItemSerialNo."' ".
							" And Warehouse_Code =  '".$vWarehouseCode."' ".
							" And Journal_Type in ('DI') ".
							" And ifNull(flagunique, 0) = 0  ".
							" Union ".
							" Select SerialNo_Code  ".
							" From Purchasesserialno ".
							" where SerialNo_Code =  '".$vItemSerialNo."' ".
							" And Warehouse_Code =  '".$vWarehouseCode."' ".
							" And Journal_Type in ('DI') ".
							" And ifNull(flagunique, 0) = 0  ";
				 //echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$RecCount=mysql_num_rows($sub_result);
			
				if ($RecCount == 0 || $RecCount == '') {
					$sub_query= " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, ".
								" purchasesserialno.Item_Code As Item_Code, 1 As OrderColumn ".
								" From purchasesserialno ".
								" Inner Join RetailDt on Purchasesserialno.RetailDt_ID = RetailDt.SaleDt_ID ".
								" Where RetailDt.Sale_id = '".$vRetId."' ".
								" And Purchasesserialno.SerialNo_Code =  '".$vItemSerialNo."' ".
								" And Purchasesserialno.Warehouse_Code =  '".$vWarehouseCode."' ".
								" And Purchasesserialno.Journal_Type = 'DI' ".
								" Union ".
								" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, Item_Code, 2 As OrderColumn  ".
								" From purchasesserialno ".
								" where SerialNo_Code =  '".$vItemSerialNo."' ".
								" And Warehouse_Code =  '".$vWarehouseCode."' ".
								" And Journal_Type in ('PI','DR','TR','AI','PD') ".
								" Order by OrderColumn ";
								
								
					//echo $sub_query; exit;			
					$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
					$sub_row=mysql_fetch_array($sub_result);
					$RecCount=mysql_num_rows($sub_result);
					
					if ($RecCount == 0) {
						$IsAvailable = 0;
						$message  = "Insert not allowed, Serial No (".$vItemSerialNo.") is not available in the warehouse (".$vWarehouseCode.") . "; 
					}	
					else {
						
						if ($sub_row[1] == 1)
						{
							$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0), Item_Code  ".
										" From purchasesserialno ".
										" where SerialNo_Code =  '".$vItemSerialNo."' ".
										" And Warehouse_Code =  '".$vWarehouseCode."' ".
										" And ifNull(SerialNo_Used,0) = 0 ".
										" And Journal_Type in ('PI','DR','TR','AI','PD')";
							$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
							$sub_row=mysql_fetch_array($sub_result);
							$RecCount=mysql_num_rows($sub_result);
							
							if ($RecCount == 0) {
								$IsAvailable = 0;
								$message  = "Insert not allowed, Serial No (".$vItemSerialNo.") is used in warehouse (".$vWarehouseCode."). "; 
							}  else {
								$SelectedSerialID      = $sub_row[0];
								$SelectedSerialQty     = $sub_row[3];
								$SelectedSerialQtySold = $sub_row[4];
								$SelectedItemCode      = $sub_row[5];
								$IsAvailable = 1;
							}	
						
						} else {
							$SelectedSerialID      = $sub_row[0];
							$SelectedSerialQty     = $sub_row[3];
							$SelectedSerialQtySold = $sub_row[4];
							$SelectedItemCode      = $sub_row[5];
							$IsAvailable = 1;
						}	

					}	
				}
				else {
					$IsAvailable = 0;
					$message  = "Insert not allowed, serial no. is invoiced."; 
				}	
			}
			else {
				$IsAvailable = 0;
				$message  = "Insert not allowed, warehouse is empty. "; 
			}	
		}

		else {
			$IsAvailable = 0;
			$message  = "Insert not allowed, Serial No (".$vItemSerialNo.") is not available. "; 
		}
	} else {
		$IsAvailable = 1;
		$ErrorExists = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		$SelectedItemCode      = '';
		
		$sub_query= " Select Item_Code  ".
					" From purchasesserialno ".
					" where SerialNo_Code =  '".$vItemSerialNo."' ";
		$sub_result = selectData($connection, $sub_query);
		$SelectedItemCode = $sub_result[0];	
	}
	
}

//if($mode == 'payments' && ){}

	//echo $client_query;exit;
if ($mode == "submitrecord" || $mode == "submitrecord1" || ($mode == "submitrecord2" && $IsAvailable == 1)){
	
	if ($mode == "submitrecord") {
	    $vRetDate = $PRetDate;
		$vRetCurr = $PRetCurr;
		$vRetCostCentCode = $PRetCostCentCode;
		$vRetProjectCode  = $PRetProjectCode;
		$vRetCashRegister = $PRetCashRegister;
		$vRetClientCode   = $PRetClientCode;
		$vRetOrderId = '';
	} else {
	    $vRetDate = $txtDate;
		$vRetCurr = $txtCurr;
		$vRetCostCentCode = $txtCostCentCode;
		$vRetProjectCode  = $txtProjectCode;
		$vRetCashRegister = $txtCashRegister;
		$vRetClientCode   = $txtClientCode;
		$vRetOrderId = $txtOrderId;
	}
	$vRetCustomerDisc = $txtRetCustomerDisc;
	$vRetCustomerPt = $txtRetCustomerPt;
	
	if($vRetCustomerDisc == '') $vRetCustomerDisc = 0;
	if($vRetCustomerPt == '') $vRetCustomerPt = 0;
	
	if (!isset($vRetCurr))	   $vRetCurr = $StpCurrCode;
	if (!isset($vRetCurr))	   $vRetCurr = $base1;   
	   
	if (empty($vRetCostCentCode) )
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vRetCostCentCode."'";
			
	if (empty($vRetProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vRetProjectCode."'"; 

	if (empty($txtGuestname))
		$txtGuestname = "Null";
	else
		$txtGuestname = "'".$txtGuestname."'";	

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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];
	
	$ClientNotFound = 0; 
	$client_query = " Select Ledger_Number, Ledger_Name From Clients ".
				    " Where Ledger_Number = '".$vRetClientCode."' "; 
	$client_result = mysql_query($client_query,$connection); 
	$RecCount=mysql_num_rows($client_result);			
	if ($RecCount == 0) $ClientNotFound = 1; 
	
	if ($ClientNotFound == 1)
		$message  = $message.' Client Code Not Found, Please check in CashRegister table.'; 
	
	
	
	//Insert Master Table
	if ($SRetId == "" && $ClientNotFound == 0){
	
		if($FC_ChangeRetailDate == 1){
			$retdate = explode("/",$vRetDate);
			$newdate = $retdate[2]."-".$retdate[1]."-".$retdate[0];
			if (strlen($newdate) == 10){
				$newdate = $newdate." ".date("H:i:s");
			}
			$newdate = "'".$newdate."'";
		} else $newdate = "now()";
		
			
		fbegin();	
		$vRetId = get_nextsequence('retail_id','',$connection);	
		fcommit();
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$vRetCurr."') As CreditCur, ".
					 " CreditAccount, if( ifNull(CashCurDefault,0)=1, CashCur, '".$vRetCurr."') As CashCur, ClientCur, CreditAccountVAT ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$Acc_Query1 = " SELECT Cash_Account, Client_Account, Sales_Account, Tips_Account, Check_Account, Currency_Code, CashRegister_Account ".
					  " FROM CashRegister ".
					  " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
		$Acc_Result1 = selectData($connection, $Acc_Query1);
		
		$Legder_Query = " SELECT Ledger_Name ".
					    " FROM Ledger ".
					    " Where Ledger_Number = '".$Acc_Result1[1]."' ";
		$Ledger_Result = selectData($connection, $Legder_Query);
		
		if($vRetOrderId != '' && $Module_RestaurantDelivery == 1) {
			$sub_query = " Select RetailOrder.Sale_ID, RetailOrder.Sale_Reference, Customer.Customer_Code, Clients.Ledger_Number ".
						 " From RetailOrder ".
						 " Left Join Clients on RetailOrder.DelDriver_Id = Clients.Ledger_Number ".
						 " Left Join Customer on RetailOrder.Customer_Id =  Customer.Customer_Id ".
						 " Where RetailOrder.Sale_ID = '".$vRetOrderId."'";
			$sub_result = selectData($connection, $sub_query);
			//echo $sub_query; exit;
			$vRetOrderId      = $sub_result[0];
			$vRetOrderRef     = $sub_result[1];
			$vRetCustomerCode = $sub_result[2];
			$vRetDriverCode   = $sub_result[3];
		}
		
		if (empty($vRetOrderId))      $vRetOrderId = 'Null';
		if (empty($vRetOrderRef))     $vRetOrderRef = 'Null';
		
		
		if (empty($vRetCustomerCode)) $vRetCustomerCode = $txtRetCustomerCode;
		
		if (empty($vRetCustomerCode)) $vRetCustomerCode = 'Null';
		else $vRetCustomerCode = "'".ereg_replace("'", "\'", trim($vRetCustomerCode))."'"; 
		if (empty($vRetDriverCode))   $vRetDriverCode = 'Null';
		if (empty($ProjectDtId))   	  $ProjectDtId = 'Null';
			
		// $custQuery = " Select Customer_Code from Customer Where Customer_Name='".$txtGuestname."'"; //echo $custQuery ;exit;
		// $resultCust = selectData($connection, $custQuery);
		// $CustCode = $resultCust[0];
	
		fbegin();
		$query = " INSERT INTO temp_retail (Sale_id, Sale_Reference, Sale_Date, Sale_Remark, Client_code, Currency_Code, Project_Code, Costcenter_code, CashRegister_Name, ".
				 " Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, Sale_DiscountPer, Sale_DiscountAmount, Sale_DiscountBase1, ".
				 " Sale_DiscountBase2, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, ".
				 " Sale_Posted, Sale_Mode, Journal_Type, Journal_Id, Sale_Tax1, Sale_Tax1Base1, Sale_Tax1Base2, Sale_Tax2, Sale_Tax2Base1, Sale_Tax2Base2, Sale_Tax3, Sale_Tax3Base1, ".
				 " Sale_Tax3Base2, Sale_Tax4, Sale_Tax4Base1, Sale_Tax4Base2, Sale_Tax5, Sale_Tax5Base1, Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, ".
				 " Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, Sale_CashCur, Sale_CashAccount, Sale_Cash, Sale_CashBase1, Sale_CashBase2, Sale_CheckDate, Sale_CheckNo, Sale_Bank, ".
				 " Sale_BankBranch, Sales_CashInBase1, Sales_CashOutBase1, Sales_CashInBase2, Sales_CashOutBase2, Sales_TipsBase1, Coupon_amount, Coupon_amountbase1, Coupon_amountbase2, ".
				 " Coupon_id, Sale_information, Sale_ClientCur, Sale_CreditAccountVat, Sales_CreditAmount, Sales_CreditAmountBase1, Sales_CreditAmountBase2, Sales_creditacc, Sales_creditacccur, ".
				 " Login_CardNo, Sale_SupervisorCode, SaleOrder_Id, SaleOrder_Reference, Customer_code, User_Account, Logged_Code, Owner_Branch, ProjectDt_Id,sale_type,driver_Code, Sale_numberofguests, guest_name, ".
				 " Sale_BelongsToGroup, sale_serviceChecked, sale_service, sale_serviceB1, sale_serviceB2, sale_TaxConsumption, sale_TaxConsumptionB1, sale_TaxConsumptionB2, ".
				 " sale_TaxConsumptionChecked, sale_customerDiscount, sale_customerAwardPt) ".
				 " VALUES ( ".$vRetId.", Null, $newdate, null, '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetCurr."', $ProjectCode, $CostCentCode, '".$vRetCashRegister."', ".
				 "          0, 0, 0, 0, 0, 0, ".$Discount_AmountPer.", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'RI', Null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', ".
				 "          '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result1[5]."', '".$Acc_Result1[2]."', '".$Acc_Result1[5]."', '".$Acc_Result1[0]."', 0, 0, 0, Null, Null, Null, ".
				 "          Null, 0, 0, 0, 0, 0, 0, 0, 0, Null, Null, '".$Acc_Result1[5]."', '".$Acc_Result[9]."', 0, 0, 0, $vRetDriverCode, '".$Acc_Result1[5]."', Null, Null, $vRetOrderId, $vRetOrderRef, $vRetCustomerCode, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', ".GetSQLValueString($Setup_Branch,'text')." , ".$ProjectDtId.",'".$txtSaleStatus."' ,'".$txtRetDriverCode."','".$txtTableGuests."',".$txtGuestname." ,
				 $FI_BelongsToGrp, $serviceChecked, 0, 0, 0, 0, 0, 0, $taxConsumptionChk, $vRetCustomerDisc, $vRetCustomerPt )";
		//echo $query."<br>";exit;				 
		//$message1 = $query;	 
		$result=mysql_query($query,$connection);
		
		
		if($ProjectDtId!='') {
			$query = "update projectdt set projectdt_reserved = 1 where projectdt_id = ".$ProjectDtId;
			$result5=mysql_query($query,$connection);
			}
			
		if ($result){
			$SRetId = $vRetId;
			fcommit();
		}else{
			$SRetId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	if ($Module_CashRegItemQtyInCode == 1 ) {
		$vSubBarcode = substr($txtItemBarcode,($CashReg_StartBarcode - 1),($CashReg_EndBarcode - $CashReg_StartBarcode + 1));
		$queryexists = "Select 1 from Items 
					WHERE (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' 
							or item_code = '".$vSubBarcode."' )	and ifnull(item_active,0) = 1 and (ifnull(Item_Weight,0) = 1000 or ifnull(Item_NetWeight,0) = 1000 or ifnull(Item_Weight,0) = 1001 or ifnull(Item_NetWeight,0) = 1001) ";
		$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
		$itemExists=mysql_num_rows($resultExists);
		if($itemExists==0) $vSubBarcode = $txtItemBarcode;

	} else $vSubBarcode = $txtItemBarcode;
	
	$queryexists = "Select 1 from Items 
					WHERE (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' 
							or item_code = '".$vSubBarcode."' )	and ifnull(item_active,0) = 1 and ifnull(item_isNotAvailable,0) = 0 ";
	$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
	$itemExists=mysql_num_rows($resultExists);
	
	
	//Insert Detail Tables
	if ($SRetId != "" && $SRetDtId == "" && ($txtItemCode != "" || $txtItemBarcode != "") && $itemExists > 0){
		$querydate = "select sale_date from temp_retail where sale_id = $SRetId ";
		$resdate = mysql_query($querydate, $connection);
		$rwdate = mysql_fetch_row($resdate);
		
		$newdate = "'".$rwdate[0]."'";
		
		$enterPrice = 0;
		
		
		
		if ($mode == "submitrecord") {
			$txtRetDtQty = $txtRetDtQty;
		} else {
			$txtRetDtQty 	= $txtItemQty;
			$txtRetDtPrice  = $txtItemPrice;
			$txtRetDtVendor = $txtVendorCode;
			$txtRetDtSlip	= $txtSlipNo;
		}
	
		if (empty($txtRetDtPrice))
			$txtRetDtPrice = 0;
		if (empty($txtRetDtDiscount))
		   $txtRetDtDiscount = 0;
		if (empty($txtRetDtQty))
		   $txtRetDtQty = 1; 
		   
		if ($txtRetDtQty > 0) $vRetDtType = 'RI';
		else $vRetDtType = 'RR';
		   
		if (empty($txtRetDtVendor))
		   $txtRetDtVendor = '';    
		if (empty($txtRetDtSlip))
		   $txtRetDtSlip = '';       
					
			
		if (empty($txtWarehouseCode))
			$txtWarehouseCode = $StpWarehouseCode;	
		
		
		$vRetQty = 0;
		$vRetDtTotal = 0;
		$vItemVat = 0;
		$vRetTaxable = 0;
		$vRetNoneTaxable = 0;
		$vRetGrossTotal = 0;
		$vRetDiscountAmt = 0;
		$vRetVat = 0;
		$vRetVatBase1 = 0;
		$vRetVatBase2 = 0;
		$vRetService = 0;
		$vRetServiceBase1 = 0;
		$vRetServiceBase2 = 0;
		$vRetTaxConsp = 0;
		$vRetTaxConspBase1 = 0;
		$vRetTaxConspBase2 = 0;
		
		$vRetDtPriceTTC      = 0;
		$vRetDtPriceTTCBase1 = 0;
		$vRetDtPriceTTCBase2 = 0;					
		$vRetDtPrice         = 0;
		$vRetDtPriceBase1    = 0;
		$vRetDtPriceBase2    = 0;
		$vRetDtDiscAmt       = 0;
		$vRetDtDiscAmtBase1  = 0;
		$vRetDtDiscAmtBase2  = 0;
		$vRetDtActualPrice   = 0;
		
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vRetDtTax1 = 0;
		$vRetDtTax2 = 0;
		$vRetDtTax3 = 0;
		$vRetDtTax4 = 0;
		$vRetDtTax5 = 0;
		
		$vRetTax1 = 0;
		$vRetTax2 = 0;
		$vRetTax3 = 0;
		$vRetTax4 = 0;
		$vRetTax5 = 0;
		$vRetTax1B1 = 0;
		$vRetTax2B1 = 0;
		$vRetTax3B1 = 0;
		$vRetTax4B1 = 0;
		$vRetTax5B1 = 0;
		$vRetTax1B2 = 0;
		$vRetTax2B2 = 0;
		$vRetTax3B2 = 0;
		$vRetTax4B2 = 0;
		$vRetTax5B2 = 0;
		
		$ErrorExists  = 0;
		$ItemNotFound = 0;
		$VendorNotFound = 0;
		$QtyExistExceeded  = 0;
				
		if (!empty($txtRetDtVendor) || $txtRetDtVendor != '') {
		
			$vendor_query = " Select Ledger_Number, Ledger_Name From Vendor ".
						    " Where ifNull(Vendor_active,0) = 1 ".
						    " And Ledger_Number = '".$txtRetDtVendor."' ";
			//$vendor_result = selectData($connection, $vendor_query);
			$vendor_result = mysql_query($vendor_query,$connection);
			$RecCount=mysql_num_rows($vendor_result);			
			
			if ($RecCount == 0) $VendorNotFound = 1; 
		}
		
		$sub_query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$vRetClientCode."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$c_sp = $sub_result[0];
		
		$MinusSignExists = 0;
		if ($Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'-') !== false) {
			$vItemPrefix = substr($txtItemBarcode, 0, strlen(strpbrk($txtItemBarcode,'+-'))*(-1));
			if (is_numeric ($vItemPrefix) || $vItemPrefix == '*') $MinusSignExists = 1;
		}
	//maroun
	$queryexists = "Select 1 from Items 
					WHERE (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' 
							or item_code = '".$txtItemBarcode."' )
					and ifNull(Item_Weight,0) = 0	 ";
	$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
	$RecBarcodeExists=mysql_num_rows($resultExists);
	
	
		if ($mode == "submitrecord" || $mode == "submitrecord1"){	
			$sub_query1 = " SELECT ifNull(Item_Vat,0), Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ".
						  " ifNull(Item_Pack, 0), Item_Code, Item_Barcode, Currency_Code, ".
						  " ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice1Base1,0), ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice2,0), ifNull(Item_SellingPrice2Base1,0), ifNull(Item_SellingPrice2Base2,0), ".
						  " ifNull(Item_SellingPrice3,0), ifNull(Item_SellingPrice3Base1,0), ifNull(Item_SellingPrice3Base2,0), ifNull(Item_SellingPrice4,0), ifNull(Item_SellingPrice4Base1,0), ifNull(Item_SellingPrice4Base2,0), ".
						  " ifNull(Item_SellingPrice5,0), ifNull(Item_SellingPrice5Base1,0), ifNull(Item_SellingPrice5Base2,0), ifNull(Item_SellingPrice6,0), ifNull(Item_SellingPrice6Base1,0), ifNull(Item_SellingPrice6Base2,0), ".
						  " ifNull(Item_NonStock,0), ifNull(Item_Weight,0),ifNull(Item_ModifySellingPrice,0) ".
						  " FROM Items where 1=1";
			
			if ($txtItemBarcode != '' && $CashReg_Weight != 1 && (($Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'+') === false && (strpos($txtItemBarcode,'-') === false || $MinusSignExists != 1)) || ($Module_CashRegItemQtyInCode != 1 && 1 == 1)))
				$sub_query = $sub_query1." and item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' or item_code = '".$txtItemBarcode."'";
			else if ($txtItemBarcode != '' && $CashReg_Weight == 1 && (($Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'+') === false && (strpos($txtItemBarcode,'-') === false || $MinusSignExists != 1))|| ($Module_CashRegItemQtyInCode != 1 && 1 == 1)))	{
				$vSubBarcode = substr($txtItemBarcode,($CashReg_StartBarcode - 1),($CashReg_EndBarcode - $CashReg_StartBarcode + 1));
				//echo $vSubBarcode; exit;
				//maroun
				if($RecBarcodeExists>0) $vSubBarcode = $txtItemBarcode;
				$sub_query = $sub_query1." and ((ifNull(Item_Weight,0) = 0 and (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' or item_code = '".$txtItemBarcode."')) ".
										 " or (ifNull(Item_Weight,0) != 0 and (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' or item_code = '".$vSubBarcode."')) ) ";
			}
			//Case Return of Weight Item
			else if ($txtItemBarcode != '' && $CashReg_Weight == 1 && $Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'-') !== false && strpos($txtItemBarcode,'*') !== false)	{
				$vSubBarcode = substr(strpbrk($txtItemBarcode,'+-'), 1, strlen(strpbrk($txtItemBarcode,'+-')) - 1);
				$vSubBarcode = substr($vSubBarcode,($CashReg_StartBarcode - 1),($CashReg_EndBarcode - $CashReg_StartBarcode + 1));
				//echo $vSubBarcode; exit;
				//maroun
				if($RecBarcodeExists>0) $vSubBarcode = $txtItemBarcode;
				$sub_query = $sub_query1." and ((ifNull(Item_Weight,0) = 0 and '".$txtItemBarcode."' != '' and (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' or item_code = '".$txtItemBarcode."')) ".
										 "     or (ifNull(Item_Weight,0) != 0 and '".$vSubBarcode."' != '' and (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' or item_code = '".$vSubBarcode."')) ) ";
			}
			else if ($txtItemBarcode != '' && (strpos($txtItemBarcode,'+') !== false || (strpos($txtItemBarcode,'-') !== false && $MinusSignExists == 1)) && $Module_CashRegItemQtyInCode == 1)	{
				$vSubBarcode = substr(strpbrk($txtItemBarcode,'+-'), 1, strlen(strpbrk($txtItemBarcode,'+-')) - 1);
				//echo $vSubBarcode; exit;
				//maroun
				if($RecBarcodeExists>0) $vSubBarcode = $txtItemBarcode;
				$sub_query = $sub_query1." and ((item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' or item_code = '".$vSubBarcode."')  and '".$vSubBarcode."' != '') ";
			}			
			else 	
				$sub_query = $sub_query1." and item_code = '".$txtItemCode."'";		 
				
			if ($Module_CashRegAutoItemsList == 1 && (($Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'+') === false && (strpos($txtItemBarcode,'-') === false || $MinusSignExists != 1)) || ($Module_CashRegItemQtyInCode != 1 && 1 == 1))) {
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$RecCount=mysql_num_rows($sub_result);
				
				if ($RecCount == 0) {
					if ($txtItemBarcode != '' && $CashReg_Weight != 1)
						$sub_query = $sub_query1." and item_barcode like '".$txtItemBarcode."%' or item_barcode2 like '".$txtItemBarcode."%' or item_barcode3 like '".$txtItemBarcode."%' or item_code like '".$txtItemBarcode."%' ";
					else if ($txtItemBarcode != '' && $CashReg_Weight == 1)	{
					
						/*$queryexists = "Select 1 from Items WHERE item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' or item_code = '".$txtItemBarcode."' ";
						$resultExists=mysql_query($queryexists,$connection)  or die(mysql_error());
						$RecExists=mysql_num_rows($resultExists);
						if($RecExists > 0)
							$vSubBarcode = $txtItemBarcode;
						else*/	
							$vSubBarcode = substr($txtItemBarcode,($CashReg_StartBarcode - 1),($CashReg_EndBarcode - $CashReg_StartBarcode + 1));
						//echo $vSubBarcode; exit;
						
						$sub_query = $sub_query1." and ((ifNull(Item_Weight,0) = 0 and (item_barcode like '".$txtItemBarcode."%' or item_barcode2 like '".$txtItemBarcode."%' or item_barcode3 like '".$txtItemBarcode."%' or item_code like '".$txtItemBarcode."%')) ".
												 " or (ifNull(Item_Weight,0) != 0 and (item_barcode = '".$vSubBarcode."' or item_barcode2 = '".$vSubBarcode."' or item_barcode3 = '".$vSubBarcode."' or item_code = '".$vSubBarcode."')) ) ";
					}	
					else 	
						$sub_query = $sub_query1." and item_code like '".$txtItemCode."%'";		 
				
					$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
					$RecCount=mysql_num_rows($sub_result);
					
					//If Item Exists More Than Once, Then Treat As No Item Found.
					if ($RecCount > 1) {
						$sub_query = $sub_query1." and 1 = 2 ";
					} 
				}

			}
		 		 
		} else {
			$sub_query = " SELECT ifNull(Item_Vat,0), Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ".
						 " ifNull(Item_Pack, 0), Item_Code, Item_Barcode, Currency_Code, ".
						 " ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice1Base1,0), ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice2,0), ifNull(Item_SellingPrice2Base1,0), ifNull(Item_SellingPrice2Base2,0), ".
						 " ifNull(Item_SellingPrice3,0), ifNull(Item_SellingPrice3Base1,0), ifNull(Item_SellingPrice3Base2,0), ifNull(Item_SellingPrice4,0), ifNull(Item_SellingPrice4Base1,0), ifNull(Item_SellingPrice4Base2,0), ".
						 " ifNull(Item_SellingPrice5,0), ifNull(Item_SellingPrice5Base1,0), ifNull(Item_SellingPrice5Base2,0), ifNull(Item_SellingPrice6,0), ifNull(Item_SellingPrice6Base1,0), ifNull(Item_SellingPrice6Base2,0), ".
						 " ifNull(Item_NonStock,0), IifNull(tem_Weight,0),ifNull(Item_ModifySellingPrice,0) ".
						 " FROM Items WHERE Item_Code = '".$SelectedItemCode."'";
		}	
		//echo $sub_query; exit;
		//$sub_querytest = $sub_query;
		$sub_result = selectData($connection, $sub_query);
		//$message1=$sub_query;exit;
		$ItemVat        = $sub_result[0];
		$ItemGroupCode  = $sub_result[1];
		$ItemProd       = $sub_result[2];
		$ItemTTCInc     = $sub_result[3];
		$ItemUnit       = $sub_result[4];
		$ItemPromo      = $sub_result[5];
		$ItemPack       = $sub_result[6];
		$txtItemCode    = $sub_result[7];
		//$txtItemBarcode1 = $sub_result[8];
		$ItemCurr       = $sub_result[9];
		$ItemNonStock   = $sub_result[28];
		$ItemWeight     = $sub_result[29];
		$ItemModifySellingPrice     = $sub_result[30];
		$vRetDtPrice = $sub_result[10];
		//$ItemSellPrice  = $sub_result[7];
	

	//maroun
	if($RecBarcodeExists == 0){					
		if ($CashReg_Weight == 1 && $ItemWeight != 0 && (($Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'+') === false && (strpos($txtItemBarcode,'-') === false || $MinusSignExists != 1)) || ($Module_CashRegItemQtyInCode != 1 && 1 == 1))) {
			$txtRetDtQty = substr($txtItemBarcode,($CashReg_StartQty - 1),($CashReg_EndQty - $CashReg_StartQty + 1));
			if($ItemWeight == 1001)
				$txtRetDtQty = ($txtRetDtQty );
			else if ($CashReg_Price == 1)
				$txtRetDtQty = ($txtRetDtQty / $vRetDtPrice);
			else
				$txtRetDtQty = ($txtRetDtQty / $ItemWeight);

			if (strpos($txtItemQty,'-') !== false) {
				$txtRetDtQty = $txtRetDtQty * (-1);
				$vRetDtType  = 'RR';
			}
		}
		//Case Return of Weight Item
		else if ($CashReg_Weight == 1 && $ItemWeight != 0 && $Module_CashRegItemQtyInCode == 1 && strpos($txtItemBarcode,'-') !== false && strpos($txtItemBarcode,'*') !== false) {
			$vSubBarcode = substr(strpbrk($txtItemBarcode,'+-'), 1, strlen(strpbrk($txtItemBarcode,'+-')) - 1);
			$txtRetDtQty = substr($vSubBarcode,($CashReg_StartQty - 1),($CashReg_EndQty - $CashReg_StartQty + 1));
			//fady01
			if($ItemWeight == 1001)
				$txtRetDtQty = ($txtRetDtQty );
			elseif ($CashReg_Price == 1)
				$txtRetDtQty = ($txtRetDtQty / $vRetDtPrice);
			else
				$txtRetDtQty = ($txtRetDtQty / $ItemWeight);
			
			// $txtRetDtQty = ($txtRetDtQty / $ItemWeight);
			
			$txtRetDtQty = $txtRetDtQty * (-1);
			$vRetDtType  = 'RR';
		}
		else if ($Module_CashRegItemQtyInCode == 1 && (strpos($txtItemBarcode,'+') !== false || (strpos($txtItemBarcode,'-') !== false && $MinusSignExists == 1))) {
			$txtRetDtQty = substr($txtItemBarcode, 0, strlen($txtItemBarcode) - strlen(strpbrk($txtItemBarcode,'+-')));
			
			if(substr(strpbrk($txtItemBarcode,'+-'), 0, 1) == '-') {
				$txtRetDtQty = $txtRetDtQty * (-1);
				$vRetDtType  = 'RR';
			}	
		}
		
}
		
		//echo $txtRetDtQty;
		//exit;
		$txtItemBarcode1 = $sub_result[8];
	
		if (empty($sub_result)) {
		//    ($CashReg_Weight == 1 && $ItemWeight != 0 && (strlen($txtItemBarcode) < ($CashReg_EndQty + 1) || strlen($txtItemBarcode) > ($CashReg_EndPQty + 1)))) {
			$ItemNotFound = 1;
		}	
		
		if ($txtRetDtQty == 0){
			$ErrorExists = 1;
			$message = "Insert not allowed. Item Qty cannot be zero.";
		}
		
		$tax_flag = 0;
		$notax_flag = 1;
		if ($ItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
		
		if (empty($ItemCurr)) $ItemCurr = $vRetCurr;
		//$ItemSellPrice   = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $ItemSellPrice, $connection);
		
		if ($vRetCurr != $ItemCurr) {
			if ($Sale_ExchangeSellPrice == 1) {
				$Item_SellingPrice1 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[10], $connection);
				$Item_SellingPrice2 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[13], $connection);
				$Item_SellingPrice3 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[16], $connection);
				$Item_SellingPrice4 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[19], $connection);
				$Item_SellingPrice5 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[22], $connection);
				$Item_SellingPrice6 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[25], $connection);
			} else {
				if ($vRetCurr == $base1) { 
					$Item_SellingPrice1 = $sub_result[11];
					$Item_SellingPrice2 = $sub_result[14];
					$Item_SellingPrice3 = $sub_result[17];
					$Item_SellingPrice4 = $sub_result[20];
					$Item_SellingPrice5 = $sub_result[23];
					$Item_SellingPrice6 = $sub_result[26];
				}
				else if ($vRetCurr == $base2) {
					$Item_SellingPrice1 = $sub_result[12];
					$Item_SellingPrice2 = $sub_result[15];
					$Item_SellingPrice3 = $sub_result[18];
					$Item_SellingPrice4 = $sub_result[21];
					$Item_SellingPrice5 = $sub_result[24];
					$Item_SellingPrice6 = $sub_result[27];
				}
				else {
					$Item_SellingPrice1 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[10], $connection);
					$Item_SellingPrice2 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[13], $connection);
					$Item_SellingPrice3 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[16], $connection);
					$Item_SellingPrice4 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[19], $connection);
					$Item_SellingPrice5 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[22], $connection);
					$Item_SellingPrice6 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $sub_result[25], $connection);
				}
			}
		} else {
			$Item_SellingPrice1 = $sub_result[10];
			$Item_SellingPrice2 = $sub_result[13];
			$Item_SellingPrice3 = $sub_result[16];
			$Item_SellingPrice4 = $sub_result[19];
			$Item_SellingPrice5 = $sub_result[22];
			$Item_SellingPrice6 = $sub_result[25];
		}
		
		
		switch ($c_sp){
			case "I":
				$ItemSellPrice = $Item_SellingPrice1; break;
			case "II":
				$ItemSellPrice = $Item_SellingPrice2; break;
			case "III":
				$ItemSellPrice = $Item_SellingPrice3; break;
			case "IV":
				$ItemSellPrice = $Item_SellingPrice4; break;
			case "V":
				$ItemSellPrice = $Item_SellingPrice5; break;
			case "VI":
				$ItemSellPrice = $Item_SellingPrice6; break;
		}		
			
		// meancost < sellingPrice stop UserAccount
		$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;
			
			if($txtItemPrice == ''){
				// echo "<BR>".
				$querySP = "select Item_SellingPrice1Base1  from items where (item_code='$txtItemCode' or item_barcode = '$vSubBarcode')
				and item_code not in (select distinct promotion_itemCode from item_promotion where now() between promotion_fromdate and promotion_todate)";
				$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;
			// echo "<br>".$rowcst[0];
			// echo "<br>".$checkPrice;
			if(($txtItemPrice < $rowcst[0] || $txtItemPrice == 0) && $checkPrice == 1){
				$ErrorExists = 1;
				// echo "<BR>".
				$message = "insert not Allowed Price below Cost !";
			}	
			
			// $message =  'insert not Allowed Price below Cost !';
		}
		// End verification of selling Price
		if ($Module_PriceOffer == 0 ) {
			$vRetDtPriceOffer = 0;	
			if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
			
			$vRetDtActualPrice = $ItemSellPrice;
			
		} else {
			if ($Module_PriceOffer == 1) {
				// Item Selling Price 1
				if ($Item_SellingPrice1 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice1;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}	
			else if ($Module_PriceOffer == 2) {
				// Item Selling Price 2
				if ($Item_SellingPrice2 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice2;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}
			else if ($Module_PriceOffer == 3) {
				// Item Selling Price 3
				if ($Item_SellingPrice3 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice3;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}
			else if ($Module_PriceOffer == 4) {
				// Item Selling Price 4
				if ($Item_SellingPrice4 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice4;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}
			else if ($Module_PriceOffer == 5) {
				// Item Selling Price 5
				if ($Item_SellingPrice5 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice5;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}
			else if ($Module_PriceOffer == 6) {
				// Item Selling Price 6
				if ($Item_SellingPrice6 == 0) { 
					$vRetDtPriceOffer  = 0; 
					$vRetDtActualPrice = $ItemSellPrice;
					if($txtRetDtPrice == 0) $txtRetDtPrice = $ItemSellPrice;
				} else {
					$vRetDtPriceOffer = 1; 
					$txtRetDtPrice = $Item_SellingPrice6;
					$vRetDtActualPrice = $ItemSellPrice;
				}
			}
			
			
		}	

		if($txtRetDtPrice == 0 && $ItemModifySellingPrice ==1 && $mode == "submitrecord1") $enterPrice=1;
		//Add Item To Log File
		if ($ItemNotFound == 1) {
			$logdir = './RetailLogs/'; //assigns log directory 
			if (!is_dir($logdir)) mkdir($logdir, 0700);
							
			$File = $logdir.$_SESSION['cashregister'].".txt"; 
			if (!file_exists($File)) {
				$Handle = fopen($File, 'w');
				$Header = "CashRegister, UserAccount, Date&Time, ItemCode, ItemQty, ItemPrice, RetailDtId "; 
				fwrite($Handle, $Header); 
			}
							
			$Handle = fopen($File, 'a');
			$Data = $_SESSION['cashregister'].", ".$_SESSION['useraccount'].", ".insertMySQLDate($vRetDate).", ".$txtItemBarcode.", ".$txtRetDtQty.", ".$vRetDtPrice.", ".$vRetDtId;
			fwrite($Handle, "\r\n"); 
			fwrite($Handle, $Data);
			fclose($Handle); 
			
		}
		
		if($copiedVers>0 && $CashRegisterEditOnPrint == 0 && $Module_RestaurantDelivery == 1 )	{
			$ErrorExists = 1;
			$message = "Cannot Add new Item! Slip Already Printed!";
		}	
		
		if ($Module_RestaurantDelivery == 1 && $ItemNotFound == 0 && $VendorNotFound == 0 && $ErrorExists == 0 && $enterPrice == 0) {
			$sub_query = " Select SaleOrder_Id, SaleOrder_Reference From Temp_Retail ".
						 " Where Sale_ID = '".$SRetId."'";
			$sub_result = selectData($connection, $sub_query);
			$vRetOrderId  = $sub_result[0];
			$vRetOrderRef = $sub_result[1];
			if(!empty($vRetOrderId)) {
				//Check For Order Item Exists
				$sub_query = " Select Count(*) From RetailOrderDt ".
							 " Where RetailOrderDt.Sale_ID = '".$vRetOrderId."' ".
							 " And RetailOrderDt.Item_Code = '".$txtItemCode."'";
				$sub_result = selectData($connection, $sub_query);
				$vCountOrderItems = $sub_result[0];
				if(empty($vCountOrderItems)) $vCountOrderItems = 0;
				
				if ($vCountOrderItems == 0) {
					$ErrorExists = 1;
					$message = "Insert not allowed. Item doesn't exist in Order items list with Ref.= ".$vRetOrderRef;
				}
				
				//Check For Order Item Qty
				if ($ErrorExists == 0) {
					$sub_query1 = " Select SaleDt_ID, Item_Code, ifNull(SaleDt_Quantity,0) ".
								  " From RetailOrderDt  ".
								  " Where RetailOrderDt.Sale_ID = '".$vRetOrderId."' ".
								  " And RetailOrderDt.Item_Code = '".$txtItemCode."'";
					$sub_result1 = selectData($connection, $sub_query1);
					$vOrderQty   = $sub_result1[2];
					if(empty($vOrderQty)) $vOrderQty = 0;
						
					if (($CashReg_Weight == 1 && $ItemWeight != 0 && abs($vOrderQty - $txtRetDtQty) > 0.5) ||
                        ((($CashReg_Weight == 1 && $ItemWeight == 0) || ($CashReg_Weight != 1 && 1 == 1)) && ($vOrderQty - $txtRetDtQty) != 0 ) ){
						
						//$ErrorExists = 1;
						$message = "Insert not allowed. Item qty (".$txtRetDtQty.") doesn't match Order item qty (".$vOrderQty.").";
					}

				}
			
			}
			}
		//echo $ItemNotFound;
		//exit;
		
		
		// jp exists
		$checkqtyExists = 1;
		$queryExists = "select count(*) from packdt   where item_pack = 0 and item_code='$txtItemCode'";
		$sub_resultExist = selectData($connection, $queryExists);
		$itemIsPack      = $sub_resultExist[0];
		if($ItemPack > 0 ){
			$message = $queryExists = "select  if('$txtRetDtQty' = '' || 'txtRetDtQty' == '0' , 1 , $txtRetDtQty) * PackDt_Quantity,qtyexists(Item_CodePackDt, 'GM',now(),0,'','','') , Item_CodePackDt from items,packdt where items.item_code = packdt.item_code and items.item_code= '$$txtItemCode'";
			$resExist = mysql_query ($queryExists,$connection);
			while($rowExisting = mysql_fetch_array()){
				if($rowExisting[0] < $rowExisting[1]) $checkqtyExists = 0;
				else {
					$ErrorExists=1;
					$message .= "Insert not allowed. Insufficient Quantity of ($rowExisting[2] aaa) ";
					break;					
				}
			}
			
		}
		 
		if ($ItemNotFound == 0 && $VendorNotFound == 0 && $ErrorExists == 0 && $enterPrice == 0 && $checkqtyExists == 1) {		
		
		
		// jp exists
			// Case Not Pack Item
			if ($ItemPack == 0) { 
					$queryhaspack = "select count(*) from packdt where item_code = '".$txtItemCode."'";
					$sub_resultX = selectData($connection, $queryhaspack);
					$haspack  = $sub_resultX[0];
				if ($ItemNonStock == 0 && $haspack == 0) {
					$sub_query1  = " Select QtyExistsWSorder_Temp('".$txtItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($vRetDate)."', 0, 'RI', '', '', 0) QtyExists From Dual ";
					$sub_result1 = selectData($connection, $sub_query1);
					$min_available_qty = 0;
					$min_available_qty = $sub_result1[0];

					$sub_query2 = " Select ifNull(Sum(ifNull(SaleDt_Quantity,0)),0) FROM Temp_RetailDt ".
								  " WHERE Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$txtWarehouseCode."' And Sale_ID = $SRetId And SaleDt_ID != ifNull('".$SRetDtId."',0) ".
								  " And SaleDt_ID Not In (Select SaleDt_ID From RetailDt Where Sale_ID  = $SRetId) ";
					$sub_result2 = selectData($connection, $sub_query2);
					$min_available_qty = $min_available_qty - $sub_result2[0];
					
					if ($txtRetDtQty > $min_available_qty && $txtRetDtQty > 0)
						$QtyExistExceeded = 1;
				}		
				if($txtbyPc == 1){
					$queryQtyPack = "select  ifnull(item_qtypack,0)    from items where  
					 (item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."' 
							or item_code = '".$txtItemBarcode."' )";
					// item_code = '$txtItemCode' ";
					$resQtyPack = mysql_query($queryQtyPack,$connection);
					$rowQtyPack = mysql_fetch_row($resQtyPack);
					$txtRetDtQty = $_GET['txtRetDtQty'] / $rowQtyPack[0];
				}
				if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
					
					
					if($module_PriceByQty == 1){
						$query = "select ifnull(item_priceByQty,0) from items where item_code='$txtItemCode'";
						$res = mysql_query($query,$connection);
						$row = mysql_fetch_row($res);
						$priceByQty = $row[0];
						if($priceByQty == 1)  {
							$queryitem = "select qtyPrice from item_priceByQty where item_code = '$txtItemCode' and '$txtRetDtQty' between fromQty and toQty";
							$resitem = mysql_query($queryitem,$connection);
							$rowitem = mysql_fetch_row($resitem);
							$numrow = mysql_num_rows($resitem);
							$qtyPrice = $rowitem[0];
							if($numrow > 0) $txtRetDtPrice = $qtyPrice;
							
						}
					}
					
					//If Case Price (Total Amount) Included In Barcode
					if ($CashReg_Price == 1 && $ItemWeight != 0) {
						//fady test
						//
						$txtRetDtPrice = substr($txtItemBarcode,($CashReg_StartPrice - 1),($CashReg_EndPrice - $CashReg_StartPrice + 1));
						$txtRetDtPrice = round(($txtRetDtPrice / abs($txtRetDtQty)),0);
						
						//if ($txtRetDtPrice < 100 && $txtRetDtPrice > 0 && $vRetCurr = $base1) $message="Please check item price (".$txtRetDtPrice."  ".$vRetCurr.")";
					}
										
					if ($CashRegisterTTC == 1) {
						
						$vRetDtPriceTTC      = $txtRetDtPrice;
						$vRetDtPriceTTCBase1 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt1;
						$vRetDtPriceTTCBase2 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt2;					
						
						$vRetDtPrice      = ($vRetDtPriceTTC / (1 + $ItemVat/100));
						$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
						$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
									
					} else	{
						$vRetDtPrice      = $txtRetDtPrice;
						$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
						$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
							
						$vRetDtPriceTTC      = 0;
						$vRetDtPriceTTCBase1 = 0;
						$vRetDtPriceTTCBase2 = 0;
									
					}	
					
					//If Item is in Promo Table Automatically Set Discount to promotion_discount					
					$queryPromotion = "select ifnull(promotion_discount,0) 
									from item_promotion, temp_retail 									
									where date_format(Sale_Date,'%Y-%m-%d %H:%i') between date_format(promotion_fromdate,'%Y-%m-%d %H:%i') and  date_format(promotion_todate,'%Y-%m-%d %H:%i') 
									and promotion_itemCode = '$txtItemCode' and Sale_id = '$SRetId' ";
					$resPromotion = mysql_query($queryPromotion,$connection);				
					$rowPromotion = mysql_fetch_row($resPromotion);
					$promotion_discount = $rowPromotion[0];
					if($promotion_discount > 0) $txtRetDtDiscount = $promotion_discount;
					
					//If Item Promo Automatically Set Discount to 100
					if ($ItemPromo == 1) $txtRetDtDiscount = 100;
					
					
					

					if ($Module_AdditionalTaxes == 1) {
						
						// Calculation of Item Tax Amounts
						$sub_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 = '".$vRetClientCode."'";
												 
						$sub_result = selectData($connection, $sub_query);
						$vCltTax1 = $sub_result[0];
						$vCltTax2 = $sub_result[1];
						$vCltTax3 = $sub_result[2];
						$vCltTax4 = $sub_result[3];
						$vCltTax5 = $sub_result[4];
										
						$sub_query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
									 " FROM Items ".
									 " WHERE Item_Code = '".$txtItemCode."'";
												 
						$sub_result = selectData($connection, $sub_query);

							
						if ($vCltTax1 != 0)	$vRetDtTax1 = $sub_result[0];
						if ($vCltTax2 != 0)	$vRetDtTax2 = $sub_result[1];
						if ($vCltTax3 != 0)	$vRetDtTax3 = $sub_result[2];
						if ($vCltTax4 != 0)	$vRetDtTax4 = $sub_result[3];
						if ($vCltTax5 != 0)	$vRetDtTax5 = $sub_result[4];
								
					}
							
						

					
					
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditAccountVAT, CreditAccount, PromotionAccount  ".
							 " FROM salessetup ";
									 
					$result = selectData($connection, $query);
							
					$vSaStpDirectStkDbt = $result[0];
					$vSaStpDirectStkCrd = $result[1];
					$vSaStpDirectStkCur = $result[2];	
					$vSaStpDiscAcc      = $result[3];	
					$vSaStpVatAcc       = $result[4];	
					$vSaStpCreditVatAcc = $result[5];	
					$vSaStpCreditAcc    = $result[6];	
					$vSaStpPromoAcc     = $result[7];	
							
						
					$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 ".
							 " 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]; 
							
					if ($Module_RawMaterial == 1) {
						$vRetDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vRetDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vRetDtDirectStkCur = $vTranStpDirectStkCur;
						$vRetDtVatAcc       = $vTranStpVatAcc;
						$vRetDtDiscAcc      = $vTranStpDiscAcc;
						$vRetDtPromoAcc     = $vTranStpPromoAcc;
								
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vRetDtItemAcc = $vTranStpNonRmVatAcc; else $vRetDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpRmAcc;
							}
						}	
					} 
					else {
						$vRetDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vRetDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vRetDtDirectStkCur = $vSaStpDirectStkCur;		
						$vRetDtVatAcc       = $vSaStpVatAcc;
						$vRetDtDiscAcc      = $vSaStpDiscAcc;
						$vRetDtPromoAcc     = $vSaStpPromoAcc;
								
						if ($ItemVat > 0)
							$vRetDtItemAcc = $vSaStpCreditVatAcc;
						else
							$vRetDtItemAcc = $vSaStpCreditAcc;	
								
					}
					
	
					$sub_query3 = " Select Count(*) ".
								  " From ItemButtons ".
								  " Where ItemButton_Value = '".$txtItemCode."' ";
					$sub_result3 = selectData($connection, $sub_query3);
					$ItemFast = 0;
					if ($sub_result3[0] > 0) $ItemFast = 1;
					
					$sub_query3 = " Select Count(*) FROM Temp_RetailDt ".
								  " WHERE Item_code = '".$txtItemCode."' ".
								  " And Journal_Type = '".$vRetDtType."' ".
                                  " And SaleDt_Price = $vRetDtPrice ".
								  " And ifNull(SaleDt_ItemStatus,0) Not In (2,3) ".
								  " And ifNull(SalesDt_Remark, '') = '' ".
								  " And Not Exists (Select 1 From Temp_RetailDt As RetailDt1 Where RetailDt1.RelatedDt_Id = Temp_RetailDt.SaleDt_Id) ".
								  " And Sale_ID = $SRetId  ";	
					$sub_result3 = selectData($connection, $sub_query3);
					$ItemExists = $sub_result3[0];
					if (empty($ItemExists)) $ItemExists = 0;
					
					if ($ItemExists == 0 || $ItemFast == 1 || $Module_CashRegItemSeperate == 1 || ($ItemExists > 0 && $CashRegisterSerialNo == 1 ) || ($ItemExists > 0 && $_GET['txtModifierNote1'] != '' )) {
					
						fbegin();
						$vRetDtId = get_nextsequence('retaildt_id','',$connection);	
						fcommit();
						
						if($Module_Color==1){
							if(!empty($costcent_no)){
								$CostCentCode = substr($txtItemCode,-($costcent_no));
								$len = strlen($txtItemCode) - $costcent_no;
								$txtItemCode = substr($txtItemCode,0,$len);
							}
						}
						if($Module_sizes==1){
							if(!empty($project_no)){
								$ProjectCode = substr($txtItemCode,-($project_no));
								$len = strlen($txtItemCode) - $project_no;
								$txtItemCode = substr($txtItemCode,0,$len);
							}
						}
						$txtsaleDt_ItemStatus = 0 ;
						if ($txtGroupHoldFire==1)
							$txtsaleDt_ItemStatus = 4;
						fbegin();
						$query = " INSERT INTO temp_retaildt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_Barcode, Item_CodePacked, ". 
								 " Item_Vat, SaleDt_Quantity, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, SaleDt_PriceVat, ".
								 " SaleDt_PriceTTC, SaleDt_PriceTTCBase1, SaleDt_PriceTTCBase2, RelatedDt_Id, SaleDt_Posted, SaleDt_DirectStkDbt, SaleDt_DirectStkCrd, SaleDt_DirectStkCur, SaleDt_DiscountAcc, ".
								 " SaleDt_ItemAccount, SaleDt_PromoAcc, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Vendor_Code, Slip_number, Price_offer, SerialNo_Code, SaleDt_ActualPrice, SalesDt_Remark, Logged_Code, saleDt_ItemStatus ) ".
								 " VALUES ( ".$vRetDtId.", ".$SRetId.", '".$vRetCurr."', $newdate, '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetDtType."', $ProjectCode, $CostCentCode, '".$txtWarehouseCode."', ".
								 "          '".$txtItemCode."', '".$txtItemBarcode1."', Null, '$ItemVat', '$txtRetDtQty', '$vRetDtPrice', '$vRetDtPriceBase1', '$vRetDtPriceBase2', '$txtRetDtDiscount', 0, 0, 0, '$vRetDtPriceTTC', ".
								 "          '$vRetDtPriceTTC', '$vRetDtPriceTTCBase1', '$vRetDtPriceTTCBase2', Null, 0, '".$vRetDtDirectStkDbt."', '".$vRetDtDirectStkCrd."', '".$vRetDtDirectStkCur."', '".$vRetDtDiscAcc."', ".
								 "          '".$vRetDtItemAcc."', '".$vRetDtPromoAcc."', '$vRetDtTax1', '$vRetDtTax2', '$vRetDtTax3', '$vRetDtTax4', '$vRetDtTax5', '".$txtRetDtVendor."', '".$txtRetDtSlip."', '$vRetDtPriceOffer',  ".
								 "          '".$vItemSerialNo."', '$vRetDtActualPrice', '".urldecode($_GET['txtModifierNote1'])."', '".$_SESSION['useraccount']."' , '$txtsaleDt_ItemStatus') ";
					} else {
						//exit;
						$sub_query3 = " Select SaleDt_ID FROM Temp_RetailDt ".
									  " WHERE Item_code = '".$txtItemCode."' ".
									  " And Journal_Type = '".$vRetDtType."' ".
									  " And SaleDt_Price = $vRetDtPrice ".
									  " And ifNull(SaleDt_ItemStatus,0) Not In (2,3) ".
									  " And ifNull(SalesDt_Remark, '') = '' ".
									  " And Not Exists (Select 1 From Temp_RetailDt As RetailDt1 Where RetailDt1.RelatedDt_Id = Temp_RetailDt.SaleDt_Id) ".
									  " And Sale_ID = $SRetId  ".
									  " Limit 1 ";
						$sub_result3 = selectData($connection, $sub_query3);
						$Targ_SaleDtID = $sub_result3[0];
						
						// jp - added the last item scanned on top
						fbegin();
						$vRetDtId = get_nextsequence('retaildt_id','',$connection);	
						fcommit();
						
						$query = " UPDATE temp_retaildt SET ". 
								 " SaleDt_ID = $vRetDtId ,  ". 
								 " SaleDt_Quantity = ifNull(SaleDt_Quantity,0) + $txtRetDtQty ";
								 
						if ($txtRetDtVendor != '')		 
							$query = $query." ,Vendor_Code = '".$txtRetDtVendor."' ";
						if ($txtRetDtSlip != '')	
							$query = $query." ,Slip_number = '".$txtRetDtSlip."' ";
							
						$query = $query." WHERE SaleDt_ID = '".$Targ_SaleDtID."'  ";
						
						/*$query = $query." WHERE Item_code = '".$txtItemCode."'  ".
										" And SaleDt_Price = $vRetDtPrice ".
										" And Sale_ID = $SRetId And Journal_Type = '".$vRetDtType."' ".
										" And ifNull(SaleDt_ItemStatus,0) Not In (2,3) ".
										" And ifNull(SalesDt_Remark, '') = '' ";*/

					}	
					//$message1=$query;//exit;
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
					//if($Discount_Amount>0)
						//add_discount($SRetId,$vRetCurr,$base1,$base2,$CashRegisterTTC,$txtRetDiscountAmt,$vRetAllowDisc,$txtRetDriverCode,$connection);
					
					if ($result){
						//Create a log File For Weight Items
						if ($CashReg_Weight == 1 && $ItemWeight != 0) {
							$logdir = './RetailLogs/'; //assigns log directory 
							if (!is_dir($logdir)) mkdir($logdir, 0700);
							
							$File = $logdir.$_SESSION['cashregister'].".txt"; 
							if (!file_exists($File)) {
								$Handle = fopen($File, 'w');
								$Header = "CashRegister, UserAccount, Date&Time, ItemCode, ItemQty, ItemPrice, RetailDtId "; 
								fwrite($Handle, $Header); 
							}
							
							$Handle = fopen($File, 'a');
							$Data = $_SESSION['cashregister'].", ".$_SESSION['useraccount'].", ".insertMySQLDate($vRetDate).", ".$txtItemBarcode.", ".$txtRetDtQty.", ".$vRetDtPrice.", ".$vRetDtId;
							fwrite($Handle, "\r\n"); 
							fwrite($Handle, $Data);
							fclose($Handle); 
							
						}
						
						
						//Case SerialNo Option == Add The SerialNo
						if ($mode == "submitrecord2") {
							fbegin();
							$vSerId = get_nextsequence('Serial_Id','',$connection);	
							fcommit();
								
							if ($vRetDtType == 'RI') $vSerType = 'DI';
							else if ($vRetDtType == 'RR') $vSerType = 'DR';
							
							$sub_query = " Select SaleDt_ID FROM Temp_RetailDt ".
										 " WHERE Item_code = '".$txtItemCode."' ".
										 " And Journal_Type = '".$vRetDtType."' ".
										 " And SaleDt_Price = $vRetDtPrice ".
										 " And Sale_ID = $SRetId  ".
                                         " Order By SaleDt_ID Desc ";
							$sub_result = selectData($connection, $sub_query);
							$vRetDtId   = $sub_result[0];
					
							$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, RetailDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
									 " VALUES ( ".$vSerId.", '".$vSerType."', $vRetDtId, $vRetDtId, '".$txtItemCode."', '".$vItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$txtWarehouseCode."', '".$_SESSION['useraccount']."' ) ";
		
							$result=mysql_query($query,$connection);
												
							if ($result){
								$ErrorExists = 0;
								fcommit();
							} else {
								$ErrorExists = 1;
								$message  = mysql_error(); 
								frollback();
							}	
						} else {		
							$ErrorExists = 0;
							fcommit();
						}	
					}else{
						$ErrorExists = 1;
						$txtRetDtId = "";
						$message  = mysql_error(); 
						frollback();
					}	
				} else {
					$ErrorExists = 1;
					$txtRetDtId = "";
					$sub_queryloc  = " select concat(description1 , ' - ',description2 , ' - ',description3 ) from item_location  where item_code = '".$txtItemCode."'";
							$sub_resultloc = selectData($connection, $sub_queryloc);
							$item_loc = '';
							$item_loc = $sub_resultloc[0];
					$message  = "Qty[$txtRetDtQty] exceeds Existing Qty[$min_available_qty] for Item (".$txtItemCode.") Location : $item_loc"; 
				}	
				
				
			}	// End Case Not Pack Item
			else {
			
				$promo_display = true;
				$promo_exhausted = 0;
				
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
							
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
						
					// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
					if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
						
						if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
							//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
							$sub_query = " Select Sum(ifNull(SaleDt_Quantity,0)) ".
										 " From RetailDt ".
										 " Inner Join Retail on RetailDt.Sale_id = Retail.Sale_id ".
										 " Where RetailDt.Item_CodePacked = '".$txtItemCode."' ".
										 " And RetailDt.Item_Code = '".$vItemCode."' ".
										 " And Retail.Journal_Type = 'RI' ".
										 " And Retail.Sale_Date >= '".$rowspackdt[6]."' and Retail.Sale_Date <= '".$rowspackdt[7]."' ";

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

							if ($vPackDtPromoQty <= ($sub_result[0] + $txtRetDtQty*$vPackDtQty)){
								$promo_exhausted = 1;
							}
						}else{
							$promo_exhausted = 1;
						}
					
					}
					
					if ($ItemNonStock == 0) {
						$sub_query1  = " Select QtyExistsWSorder_Temp('".$vItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($vRetDate)."', 0, 'RI', '', '', 0) QtyExists From Dual ";
						$sub_result1 = selectData($connection, $sub_query1);
						$min_available_qty = 0;
						$min_available_qty = $sub_result1[0];

						$sub_query2 = " Select ifNull(Sum(ifNull(SaleDt_Quantity,0)),0) FROM Temp_RetailDt ".
									  " WHERE Item_code = '".$vItemCode."'  And  Warehouse_code = '".$txtWarehouseCode."' And Sale_ID = $SRetId And SaleDt_ID != ifNull('".$SRetDtId."',0) ".
									  " And SaleDt_ID Not In (Select SaleDt_ID From RetailDt Where Sale_ID  = $SRetId) ";
						$sub_result2 = selectData($connection, $sub_query2);
						$min_available_qty = $min_available_qty - $sub_result2[0];
							
						if ($txtRetDtQty*$vPackDtQty > $min_available_qty && $txtRetDtQty > 0) {
							$QtyExistExceeded = 1;
							$sub_queryloc  = " select concat(description1 , ' - ',description2 , ' - ',description3 ) from item_location  where item_code = '".$txtItemCode."'";
							$sub_resultloc = selectData($connection, $sub_queryloc);
							$item_loc = '';
							$item_loc = $sub_resultloc[0];
							$message  = "Qty[$txtRetDtQty*$vPackDtQty] exceeds Existing Qty[$min_available_qty] for Item (".$vItemCode.")Location : $item_loc "; 
						}	
					}	
					
					if ($promo_exhausted == 1) break;
					if ($QtyExistExceeded == 1) break;
				}		
				
				fbegin();
				if ($promo_exhausted == 0 && ($QtyExistExceeded == 0  || ($Module_NegativeQuantity==1 && $Login_negativeQty==1))){
					$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 = '".$txtItemCode."'  ";
									   
					$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
					while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
						$vItemCodePacked = $rowspackdt[0];
						$vItemCode       = $rowspackdt[1];
						$vPackDtQty = $rowspackdt[2];
						$vPackDtCostPer = $rowspackdt[3];
						$vPackDtPromo = $rowspackdt[4];
						$vPackDtPromoQty = $rowspackdt[5];
						

						fbegin();
						$vRetDtId = get_nextsequence('retaildt_id','',$connection);
						fcommit();

						$vRetDtQty = $txtRetDtQty*$vPackDtQty;
							
							
								
						$query = " SELECT ifNull(Item_Vat,0), Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), Item_Barcode, Currency_Code, ".
								 " ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice1Base1,0), ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice2,0), ifNull(Item_SellingPrice2Base1,0), ifNull(Item_SellingPrice2Base2,0), ".
								 " ifNull(Item_SellingPrice3,0), ifNull(Item_SellingPrice3Base1,0), ifNull(Item_SellingPrice3Base2,0), ifNull(Item_SellingPrice4,0), ifNull(Item_SellingPrice4Base1,0), ifNull(Item_SellingPrice4Base2,0), ".
								 " ifNull(Item_SellingPrice5,0), ifNull(Item_SellingPrice5Base1,0), ifNull(Item_SellingPrice5Base2,0), ifNull(Item_SellingPrice6,0), ifNull(Item_SellingPrice6Base1,0), ifNull(Item_SellingPrice6Base2,0) ".
								 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$ItemVat       = $result[0];
						$ItemGroupCode = $result[1];
						$ItemProd      = $result[2];
						$ItemTTCInc    = $result[3];
						$ItemUnit      = $result[4];
						$ItemBarcode   = $result[5];
						$ItemCurr      = $result[6];
						
						$tax_flag = 0;
						$notax_flag = 1;
						if ($ItemVat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}

						
								
						$vRetDtPriceTTC      = 0;
						$vRetDtPriceTTCBase1 = 0;
						$vRetDtPriceTTCBase2 = 0;					
						$vRetDtPrice   	    = 0;
						$vRetDtPriceBase1 	= 0;
						$vRetDtPriceBase2    = 0;
						$vRetDtDiscAmt       = 0;
						$vRetDtDiscAmtBase1  = 0;
						$vRetDtDiscAmtBase2  = 0;
								
						$vCltTax1 = 0;
						$vCltTax2 = 0;
						$vCltTax3 = 0;
						$vCltTax4 = 0;
						$vCltTax5 = 0;
						$vRetDtTax1 = 0;
						$vRetDtTax2 = 0;
						$vRetDtTax3 = 0;
						$vRetDtTax4 = 0;
						$vRetDtTax5 = 0;
						
						$vRetDtActualPrice = 0;

						if ($Module_PackCostPerc == 1) {	
							if ($CashRegisterTTC == 1) {
								$vRetDtPriceTTC      = (($txtRetDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vRetDtPriceTTCBase1 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt1;
								$vRetDtPriceTTCBase2 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt2;	

								$vRetDtActualPrice = $vRetDtPriceTTC;
											
								$vRetDtPrice      = ($vRetDtPriceTTC / (1 + $ItemVat/100));
								$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
								$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
							} else	{
								$vRetDtPrice      = (($txtRetDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
								$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
								
								$vRetDtActualPrice = $vRetDtPrice;
											
								$vRetDtPriceTTC      = 0;
								$vRetDtPriceTTCBase1 = 0;
								$vRetDtPriceTTCBase2 = 0;
							}
						} else {
							if (empty($ItemCurr)) $ItemCurr = $vRetCurr;
							//$ItemSellPrice   = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $ItemSellPrice, $connection);
							
							if ($vRetCurr != $ItemCurr) {
								if ($Sale_ExchangeSellPrice == 1) {
									$Item_SellingPrice1 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[7],  $connection);
									$Item_SellingPrice2 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[10], $connection);
									$Item_SellingPrice3 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[13], $connection);
									$Item_SellingPrice4 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[16], $connection);
									$Item_SellingPrice5 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[19], $connection);
									$Item_SellingPrice6 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[22], $connection);
								} else {
									if ($vRetCurr == $base1) { 
										$Item_SellingPrice1 = $result[8];
										$Item_SellingPrice2 = $result[11];
										$Item_SellingPrice3 = $result[14];
										$Item_SellingPrice4 = $result[17];
										$Item_SellingPrice5 = $result[20];
										$Item_SellingPrice6 = $result[23];
									}
									else if ($vRetCurr == $base2) {
										$Item_SellingPrice1 = $result[9];
										$Item_SellingPrice2 = $result[12];
										$Item_SellingPrice3 = $result[15];
										$Item_SellingPrice4 = $result[18];
										$Item_SellingPrice5 = $result[21];
										$Item_SellingPrice6 = $result[24];
									}
									else {
										$Item_SellingPrice1 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[7],  $connection);
										$Item_SellingPrice2 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[10], $connection);
										$Item_SellingPrice3 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[13], $connection);
										$Item_SellingPrice4 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[16], $connection);
										$Item_SellingPrice5 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[19], $connection);
										$Item_SellingPrice6 = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($PRetDate), $result[22], $connection);
									}
								}
							} else {
								$Item_SellingPrice1 = $result[7];
								$Item_SellingPrice2 = $result[10];
								$Item_SellingPrice3 = $result[13];
								$Item_SellingPrice4 = $result[16];
								$Item_SellingPrice5 = $result[19];
								$Item_SellingPrice6 = $result[22];
							}
							
							
							switch ($c_sp){
								case "I":
									$ItemSellPrice = $Item_SellingPrice1; break;
								case "II":
									$ItemSellPrice = $Item_SellingPrice2; break;
								case "III":
									$ItemSellPrice = $Item_SellingPrice3; break;
								case "IV":
									$ItemSellPrice = $Item_SellingPrice4; break;
								case "V":
									$ItemSellPrice = $Item_SellingPrice5; break;
								case "VI":
									$ItemSellPrice = $Item_SellingPrice6; break;
							}
							
							$txtRetDtPrice     = $ItemSellPrice;
							$vRetDtActualPrice = $ItemSellPrice;
							
							if ($CashRegisterTTC == 1) {
								$vRetDtPriceTTC      = $txtRetDtPrice;
								$vRetDtPriceTTCBase1 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt1;
								$vRetDtPriceTTCBase2 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt2;					
								
								$vRetDtPrice      = ($vRetDtPriceTTC / (1 + $ItemVat/100));
								$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
								$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
											
							} else	{
								$vRetDtPrice      = $txtRetDtPrice;
								$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
								$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
									
								$vRetDtPriceTTC      = 0;
								$vRetDtPriceTTCBase1 = 0;
								$vRetDtPriceTTCBase2 = 0;
							}							
							
						}
						
						//If Item Promo Automatically Set Discount to 100
						if ($vPackDtPromo == 1) $txtRetDtDiscount = 100;
								

						if ($Module_AdditionalTaxes == 1) {
								
							// Calculation of Item Tax Amounts
							$sub_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 = '".$vRetClientCode."'";
														 
							$sub_result = selectData($connection, $sub_query);
							$vCltTax1 = $sub_result[0];
							$vCltTax2 = $sub_result[1];
							$vCltTax3 = $sub_result[2];
							$vCltTax4 = $sub_result[3];
							$vCltTax5 = $sub_result[4];
												
							$sub_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."'";
														 
							$sub_result = selectData($connection, $sub_query);

									
							if ($vCltTax1 != 0)	$vRetDtTax1 = $sub_result[0];
							if ($vCltTax2 != 0)	$vRetDtTax2 = $sub_result[1];
							if ($vCltTax3 != 0)	$vRetDtTax3 = $sub_result[2];
							if ($vCltTax4 != 0)	$vRetDtTax4 = $sub_result[3];
							if ($vCltTax5 != 0)	$vRetDtTax5 = $sub_result[4];
									
						}		
							
							
						// Get DirectStock Accounts
						$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditAccountVAT, CreditAccount, PromotionAccount  ".
								 " FROM salessetup ";
										 
						$result = selectData($connection, $query);
									
						$vSaStpDirectStkDbt = $result[0];
						$vSaStpDirectStkCrd = $result[1];
						$vSaStpDirectStkCur = $result[2];	
						$vSaStpDiscAcc      = $result[3];	
						$vSaStpVatAcc       = $result[4];	
						$vSaStpCreditVatAcc = $result[5];	
						$vSaStpCreditAcc    = $result[6];	
						$vSaStpPromoAcc     = $result[7];			
									
								
						$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 ".
								 " 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]; 
									
						if ($Module_RawMaterial == 1) {
							$vRetDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vRetDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vRetDtDirectStkCur = $vTranStpDirectStkCur;
							$vRetDtVatAcc       = $vTranStpVatAcc;
							$vRetDtDiscAcc      = $vTranStpDiscAcc;
							$vRetDtPromoAcc     = $vTranStpPromoAcc;
										
							if ($ItemVat > 0) {
								if ($ItemProd == 1)	$vRetDtItemAcc = $vTranStpNonRmVatAcc; else $vRetDtItemAcc = $vTranStpRmVatAcc;
							}
							else {
								if ($ItemProd == 1) {
									if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpNonRmAcc;
								}	
								else {
									if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpRmAcc;
								}
							}	
						} 
						else {
							$vRetDtDirectStkDbt = $vSaStpDirectStkDbt;
							$vRetDtDirectStkCrd = $vSaStpDirectStkCrd;
							$vRetDtDirectStkCur = $vSaStpDirectStkCur;		
							$vRetDtVatAcc       = $vSaStpVatAcc;
							$vRetDtDiscAcc      = $vSaStpDiscAcc;
							$vRetDtPromoAcc     = $vSaStpPromoAcc;
								
							if ($ItemVat > 0)
								$vRetDtItemAcc = $vSaStpCreditVatAcc;
							else
								$vRetDtItemAcc = $vSaStpCreditAcc;	
						}
							
						
						if($Module_Color==1){
							if(!empty($costcent_no)){
								$CostCentCode = substr($vItemCode,-($costcent_no));
								$len = strlen($vItemCode) - $costcent_no;
								$vItemCode = substr($vItemCode,0,$len);
							}
						}
						if($Module_sizes==1){
							if(!empty($project_no)){
								$ProjectCode = substr($vItemCode,-($project_no));
								$len = strlen($vItemCode) - $project_no;
								$vItemCode = substr($vItemCode,0,$len);
							}
						}
						
						$query = " INSERT INTO temp_retaildt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_Barcode, Item_CodePacked, ". 
								 " Item_Vat, SaleDt_Quantity, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, SaleDt_PriceVat, ".
								 " SaleDt_PriceTTC, SaleDt_PriceTTCBase1, SaleDt_PriceTTCBase2, RelatedDt_Id, SaleDt_Posted, SaleDt_DirectStkDbt, SaleDt_DirectStkCrd, SaleDt_DirectStkCur, SaleDt_DiscountAcc, ".
								 " SaleDt_ItemAccount, SaleDt_PromoAcc, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Vendor_Code, Slip_number, Price_offer, SaleDt_ActualPrice, Logged_Code ) ".
								 " VALUES ( ".$vRetDtId.", ".$SRetId.", '".$vRetCurr."', $newdate, '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetDtType."', $ProjectCode, $CostCentCode, '".$txtWarehouseCode."', ".
								 "          '".$vItemCode."', '".$ItemBarcode."', '".$vItemCodePacked."', $ItemVat, $vRetDtQty, $vRetDtPrice, $vRetDtPriceBase1, $vRetDtPriceBase2, $txtRetDtDiscount, 0, 0, 0, $vRetDtPriceTTC, ".
								 "          $vRetDtPriceTTC, $vRetDtPriceTTCBase1, $vRetDtPriceTTCBase2, Null, 0, '".$vRetDtDirectStkDbt."', '".$vRetDtDirectStkCrd."', '".$vRetDtDirectStkCur."', '".$vRetDtDiscAcc."', ".
								 "          '".$vRetDtItemAcc."', '".$vRetDtPromoAcc."', $vRetDtTax1, $vRetDtTax2, $vRetDtTax3, $vRetDtTax4, $vRetDtTax5, '".$txtRetDtVendor."', '".$txtRetDtSlip."', $vRetDtPriceOffer,  ".
								 "          $vRetDtActualPrice, '".$_SESSION['useraccount']."' ) ";
				
				
						$result=mysql_query($query,$connection);
										
						//echo $query;
						
					} // End Loop Of Packdt
					

									
					if ($result){
						$ErrorExists = 0;
						fcommit();
					}else{
						$ErrorExists = 1;
						$txtRetDtId = "";
						$message  = mysql_error(); 
						frollback();
					}	
				} else{
					$ErrorExists = 1;
					$txtRetDtId = "";
					
					if ($promo_exhausted == 1)  
						$message = $message . "<br>Item ".$txtItemCode." COULD NOT be Added. Promo Qty / Period Exhausted";
					if ($QtyExistExceeded == 1)
						$message = $message;
					
					frollback();
				}
				
			} // End CasePack Item
			
			
			if ($ErrorExists == 0) {
			
				$vRetDiscountAmt = 0;
				$vRetTotal = 0;
				$vRetDtTotal = 0;
			
				//Distribute The Total Discount On Detail Table
				$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
							  " From Temp_Retail ".
							  " Where Sale_ID = '".$SRetId."' ";
				$sub_result1 = selectData($connection, $sub_query1);
				$vRetDiscountAmt = $sub_result1[0];	
				
				if ($vRetDiscountAmt > 0) {
				
					$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt ".
								  " Where Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vRetTotal   = $sub_result2[0];	
					
					$sub_query3 = " Select SaleDt_ID,  ".
								  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt As RetailDt  ".
								  " Where RetailDt.Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
							   
					//echo $sub_query3; 
					$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
					while($sub_rows3=mysql_fetch_array($sub_result3)){
					
						$vRetDtId      = $sub_rows3[0];
						$vRetDtTotal   = $sub_rows3[1];
						
						
						$vRetDtDiscAmt	    = 0;
						$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
						$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
						$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
						
				
						$sub_query4 =  " UPDATE temp_retaildt SET ".
									   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
									   " Where SaleDt_ID = '".$vRetDtId."' ";
									   
									 
						//echo $sub_query4; exit;
						if (!updateData($connection, $sub_query4, true))
							$error  = mysql_error(); 
						

					}
				}	
				
				$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
						 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
						 " From Temp_RetailDt ".
						 " Where Sale_ID = ".$SRetId.
						 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
				//echo $query;
				$result=mysql_query($query,$connection) or die(mysql_error());
				while($rows=mysql_fetch_array($result)){

					$vRetDtTotal  = $rows[1];
					$vItemVat     = $rows[2];
					$vRetQty      = $vRetQty + $rows[3];
						
					$tax_flag = 0;
					$notax_flag = 1;
					if ($vItemVat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
						
							
					$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
					$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
					
					// Calculation of Vat Amount
					if ((insertDate($vRetDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
						$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
					
										
					if ($Module_AdditionalTaxes == 1) {
						if ($vItemVat > 0 && $rows[5] != 0)
							$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
						if ($vItemVat > 0 && $rows[6] != 0)
							$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
						if ($vItemVat > 0 && $rows[7] != 0)
							$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
						if ($vItemVat > 0 && $rows[8] != 0)
							$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
						if ($vItemVat > 0 && $rows[9] != 0)
							$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
					}
						
				}			
					
					
				$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
				if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
				if ($cashregister_service == 1 && $serviceChecked == 1){
					// $vRetService = (($vRetGrossTotal+$vRetVat)*$cashregister_servicePercentage/100);
					$vRetService = (($vRetGrossTotal)*$cashregister_servicePercentage/100);
					$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
					$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
				}	
				if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
					// stoppeed VAT
				//	$vRetTaxConsp = (($vRetGrossTotal+$vRetVat)*$cashregister_TaxConsumptionpPer/100);
					$vRetTaxConsp = (($vRetGrossTotal)*$cashregister_TaxConsumptionpPer/100);
					$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
					$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
				}
				$vRetNetTotal         = $vRetGrossTotal + $vRetVat + $vRetService + $vRetTaxConsp - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
				$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
				$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
				$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
				$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
				$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
				$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
				$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
				$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
				$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
				$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
				$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
				$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				
				if ($vRetTax1 == '') $vRetTax1 = 0;
				if ($vRetTax2 == '') $vRetTax2 = 0;
				if ($vRetTax3 == '') $vRetTax3 = 0;
				if ($vRetTax4 == '') $vRetTax4 = 0;
				if ($vRetTax5 == '') $vRetTax5 = 0;
				
				$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
				$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
				$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
				$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
				$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
				$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
				$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
				$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
				$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
				$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
				$RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ;
				
				if($RetTipsB1 == '')	$RetTipsB1 = 0;
				fbegin();			 
				$query = " UPDATE temp_retail SET ".
						 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
						 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
						 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
						 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
						 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
						 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
						 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
						 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
						 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
						 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
						 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2,  ".
						 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked, ".
						 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
						 " sale_TaxConsumptionChecked = $taxConsumptionChk, Sales_TipsBase1 = $RetTipsB1 ".
						 " WHERE Sale_ID = ".$SRetId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
							 
					// echo $query."<br>";exit;
				$result=mysql_query($query,$connection);
				
				
				if ($result){
					fcommit();
				}else{
					$message  = mysql_error(); 
					frollback();
				}	
			}
		} else {
			if ($ItemNotFound == 1 && $Module_CashRegAutoItemsList == 1 && $mode == "submitrecord1")
				$message  = 'Item Not Found.'; 
			else if ($ItemNotFound == 1)
				$message  = 'Item Not Found.'; 	
			if ($VendorNotFound == 1)
				$message  = $message.' Vendor Code Not Found.'; 
			if($enterPrice == 1) $enterPrice=1;		
		
		}	
	} // End Case Insert In Detail Tables
	
	
	//Display Led Section
	if ($CashRegister_DisplayLed==1 && $ItemNotFound != 1) {
        $com=$CashRegister_DispCOM;
		if (empty($com)) $com = 0;
		
		$query='select item_description from items where item_code="'.$txtItemCode .'"';
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);
		$fp = fopen ("com".$com.":9600,n,8,1,DS", "wb+");
       	$string=chr(12); //simulating device
		fputs ($fp, $string );             
		fclose ($fp);
	    $fp = fopen ("com".$com.":9600,n,8,1,DS", "wb+");
        $line1=$rows[0].'                    ';
	    $line2=$txtRetDtPrice;
	//    $string=substr($line1,0,$CashRegister_LedDescLength).$txtRetDtPrice.' '.substr($vRetCurr,0,3); //simulating device
    	$string=substr($line1,0,$CashRegister_LedDescLength).ROUND(($txtRetDtPrice*$txtRetDtQty)*(1-$txtRetDtDiscount),$DecimalBase1).' '.substr($vRetCurr,0,3); //simulating device
		fputs ($fp, $string );          
	    fclose ($fp);
	}
	//txtRetDtQty  txtRetDtDiscount DecimalBase1
	
	if($POS_RedeemPoints == 1){
		
		 addDiscount ($SRetId,$vRetCustomerDisc,$base1,$base2,$CashRegisterTTC,$Setup_VatPercentage,$txtRetCustomerCode,$connection);
	}

} 

else if ($mode == "submitmodifier" && $SRetId != "" && $SRetDtId != ""){

	$ErrorExists = 0;
	$message = '' ;
	
	if (empty($txtItemPrice))	$txtItemPrice = 0;
	if (empty($txtItemQty))		$txtItemQty = 1; 
	if (empty($txtWarehouseCode)) $txtWarehouseCode = $StpWarehouseCode;	
	
	$vRetDate = $txtDate;
	$vRetCurr = $txtCurr;
	
	$vRetCostCentCode = $txtCostCentCode;
	$vRetProjectCode  = $txtProjectCode;
	$vRetClientCode   = $txtClientCode;
	   
	if (empty($vRetCostCentCode) && $vRetCostCentCode != 0)
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vRetCostCentCode."'";
			
	if (empty($vRetProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vRetProjectCode."'";   

	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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];
	
	$sub_query = " SELECT ifNull(Item_Vat,0), Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ".
				 " ifNull(Item_Pack, 0), Item_Code, Item_Barcode, Currency_Code, ".
				 " ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice1Base1,0), ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice2,0), ifNull(Item_SellingPrice2Base1,0), ifNull(Item_SellingPrice2Base2,0), ".
				 " ifNull(Item_SellingPrice3,0), ifNull(Item_SellingPrice3Base1,0), ifNull(Item_SellingPrice3Base2,0), ifNull(Item_SellingPrice4,0), ifNull(Item_SellingPrice4Base1,0), ifNull(Item_SellingPrice4Base2,0), ".
				 " ifNull(Item_SellingPrice5,0), ifNull(Item_SellingPrice5Base1,0), ifNull(Item_SellingPrice5Base2,0), ifNull(Item_SellingPrice6,0), ifNull(Item_SellingPrice6Base1,0), ifNull(Item_SellingPrice6Base2,0), ".
				 " ifNull(Item_NonStock,0), ifNull(Item_Weight,0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemBarcode."'";
		
	//echo $sub_query; exit;
	$sub_result = selectData($connection, $sub_query);
	
	$ItemVat        = $sub_result[0];
	$ItemGroupCode  = $sub_result[1];
	$ItemProd       = $sub_result[2];
	$ItemTTCInc     = $sub_result[3];
	$ItemUnit       = $sub_result[4];
	$ItemPromo      = $sub_result[5];
	$ItemPack       = $sub_result[6];
	$txtItemCode    = $sub_result[7];
	$txtItemBarcode1 = $sub_result[8];
	$ItemCurr       = $sub_result[9];
	$ItemNonStock   = $sub_result[28];
	$ItemWeight     = $sub_result[29];
		
		   
	if ($CashRegisterTTC == 1) {
		$vRetDtPriceTTC      = $txtItemPrice;
		$vRetDtPriceTTCBase1 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt1;
		$vRetDtPriceTTCBase2 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt2;					
						
		$vRetDtPrice      = ($vRetDtPriceTTC / (1 + $ItemVat/100));
		$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
		$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
	} else	{
		$vRetDtPrice      = $txtItemPrice;
		$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
		$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
							
		$vRetDtPriceTTC      = 0;
		$vRetDtPriceTTCBase1 = 0;
		$vRetDtPriceTTCBase2 = 0;
	}	

	// Get DirectStock Accounts
	$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditAccountVAT, CreditAccount, PromotionAccount  ".
			 " FROM salessetup ";
									 
	$result = selectData($connection, $query);
							
	$vSaStpDirectStkDbt = $result[0];
	$vSaStpDirectStkCrd = $result[1];
	$vSaStpDirectStkCur = $result[2];	
	$vSaStpDiscAcc      = $result[3];	
	$vSaStpVatAcc       = $result[4];	
	$vSaStpCreditVatAcc = $result[5];	
	$vSaStpCreditAcc    = $result[6];	
	$vSaStpPromoAcc     = $result[7];	
							
						
	$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 ".
			 " 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]; 
							
	if ($Module_RawMaterial == 1) {
		$vRetDtDirectStkDbt = $vTranStpDirectStkDbt;
		$vRetDtDirectStkCrd = $vTranStpDirectStkCrd;
		$vRetDtDirectStkCur = $vTranStpDirectStkCur;
		$vRetDtVatAcc       = $vTranStpVatAcc;
		$vRetDtDiscAcc      = $vTranStpDiscAcc;
		$vRetDtPromoAcc     = $vTranStpPromoAcc;
								
		if ($ItemVat > 0) {
			if ($ItemProd == 1)	$vRetDtItemAcc = $vTranStpNonRmVatAcc; else $vRetDtItemAcc = $vTranStpRmVatAcc;
		}
		else {
			if ($ItemProd == 1) {
				if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpNonRmAcc;
			}	
			else {
				if ($ItemTTCInc == 1) $vRetDtItemAcc = $vTranStpRmTTCIncAcc; else $vRetDtItemAcc = $vTranStpRmAcc;
			}
		}	
	} 
	else {
		$vRetDtDirectStkDbt = $vSaStpDirectStkDbt;
		$vRetDtDirectStkCrd = $vSaStpDirectStkCrd;
		$vRetDtDirectStkCur = $vSaStpDirectStkCur;		
		$vRetDtVatAcc       = $vSaStpVatAcc;
		$vRetDtDiscAcc      = $vSaStpDiscAcc;
		$vRetDtPromoAcc     = $vSaStpPromoAcc;
								
		if ($ItemVat > 0)
			$vRetDtItemAcc = $vSaStpCreditVatAcc;
		else
			$vRetDtItemAcc = $vSaStpCreditAcc;	
								
	}
					
	$querydate = "select sale_date from temp_retail where sale_id = $SRetId ";
	$resdate = mysql_query($querydate, $connection);
	$rwdate = mysql_fetch_row($resdate);
	
	$newdate = "'".$rwdate[0]."'";
	
	if ($txtItemCode != '') {				
		fbegin();
		$vRetDtId = get_nextsequence('retaildt_id','',$connection);	
		fcommit();

		fbegin();
		$query = " INSERT INTO temp_retaildt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_Barcode, Item_CodePacked, ". 
				 " Item_Vat, SaleDt_Quantity, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, SaleDt_PriceVat, ".
				 " SaleDt_PriceTTC, SaleDt_PriceTTCBase1, SaleDt_PriceTTCBase2, RelatedDt_Id, SaleDt_Posted, SaleDt_DirectStkDbt, SaleDt_DirectStkCrd, SaleDt_DirectStkCur, SaleDt_DiscountAcc, ".
				 " SaleDt_ItemAccount, SaleDt_PromoAcc, SaleDt_ActualPrice, Logged_Code ) ".
				 " VALUES ( ".$vRetDtId.", ".$SRetId.", '".$vRetCurr."', $newdate, '".ereg_replace("'", "\'", trim($vRetClientCode))."', 'RI', $ProjectCode, $CostCentCode, '".$txtWarehouseCode."', ".
				 "          '".$txtItemCode."', '".$txtItemBarcode1."', Null, $ItemVat, $txtItemQty, $vRetDtPrice, $vRetDtPriceBase1, $vRetDtPriceBase2, 0, 0, 0, 0, $vRetDtPriceTTC, ".
				 "          $vRetDtPriceTTC, $vRetDtPriceTTCBase1, $vRetDtPriceTTCBase2, ".$SRetDtId.", 0, '".$vRetDtDirectStkDbt."', '".$vRetDtDirectStkCrd."', '".$vRetDtDirectStkCur."', '".$vRetDtDiscAcc."', ".
				 "          '".$vRetDtItemAcc."', '".$vRetDtPromoAcc."', $txtItemPrice, '".$_SESSION['useraccount']."' ) ";
	} else {
						
			$query = " UPDATE temp_retaildt SET ". 
					 " SalesDt_Remark = if(SalesDt_Remark != '', concat(SalesDt_Remark,'\r','$txtItemBarcode'), '$txtItemBarcode') ".
					 " WHERE SaleDt_ID = $SRetDtId";	
	}	
	$message1=$query;
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();	
						
		$vRetDiscountAmt = 0;
		$vRetTotal = 0;
		$vRetDtTotal = 0;
			
		//Distribute The Total Discount On Detail Table
		$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
					  " From Temp_Retail ".
					  " Where Sale_ID = '".$SRetId."' ";
		$sub_result1 = selectData($connection, $sub_query1);
		$vRetDiscountAmt = $sub_result1[0];	
				
		if ($vRetDiscountAmt > 0) {
				
			$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt ".
						  " Where Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
			$sub_result2 = selectData($connection, $sub_query2);
			$vRetTotal   = $sub_result2[0];	
					
			$sub_query3 = " Select SaleDt_ID,  ".
						  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt As RetailDt  ".
						  " Where RetailDt.Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
							   
			//echo $sub_query3; 
			$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
			while($sub_rows3=mysql_fetch_array($sub_result3)){
					
				$vRetDtId      = $sub_rows3[0];
				$vRetDtTotal   = $sub_rows3[1];
						
				$vRetDtDiscAmt	    = 0;
				$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
				$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
				$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
				
				$sub_query4 =  " UPDATE temp_retaildt SET ".
							   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
							   " Where SaleDt_ID = '".$vRetDtId."' ";
									   
									 
				//echo $sub_query4; exit;
				if (!updateData($connection, $sub_query4, true))
					$error  = mysql_error(); 
			
			}
		}	
				
		$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_RetailDt ".
				 " Where Sale_ID = ".$SRetId.
				 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
										 
		//echo $query;
		$result=mysql_query($query,$connection) or die(mysql_error());
		while($rows=mysql_fetch_array($result)){

			$vRetDtTotal  = $rows[1];
			$vItemVat     = $rows[2];
			$vRetQty      = $vRetQty + $rows[3];
						
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ((insertDate($vRetDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
				$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
						
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $rows[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
				if ($vItemVat > 0 && $rows[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
				if ($vItemVat > 0 && $rows[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
				if ($vItemVat > 0 && $rows[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
				if ($vItemVat > 0 && $rows[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
			}
						
		}			
					
					
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
		if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
					
		$vRetNetTotal         = $vRetGrossTotal + $vRetVat - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2  ".
				 " WHERE Sale_ID = ".$SRetId;
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;			
	}else{
		$ErrorExists = 1;
		$message  = mysql_error($connection); 
		frollback();
	}
}
//Edit Detail Tables
else if ($mode == "editdt" && $SRetId != "" && $SRetDtId != ""){

	
		
	if (empty($txtRetDtPrice))
		$txtRetDtPrice = 0;
	if (empty($txtRetDtDiscount))
	   $txtRetDtDiscount = 0;
	if (empty($txtRetDtQty))
	   $txtRetDtQty = 1; 
		   
	if ($txtRetDtQty > 0) $vRetDtType = 'RI';
	else $vRetDtType = 'RR';
		   
	if (empty($txtRetDtVendor))
	   $txtRetDtVendor = '';    
	if (empty($txtRetDtSlip))
	   $txtRetDtSlip = '';       
					
			
	if (empty($txtWarehouseCode))
		$txtWarehouseCode = $StpWarehouseCode;	
		
	$vRetDate = $PRetDate;
	
	
	$retdate = explode("/",$vRetDate);
	$newdate = $retdate[2]."-".$retdate[1]."-".$retdate[0];
	if (strlen($newdate) == 10){
		$newdate = $newdate." ".date("H:i:s");
	}
	
	
	$vRetQty = 0;
	$vRetDtTotal = 0;
	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetVat = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetService = 0;
	$vRetServiceBase1 = 0;
	$vRetServiceBase2 = 0;
	$vRetTaxConsp = 0;
	$vRetTaxConspBase1 = 0;
	$vRetTaxConspBase2 = 0;
	
	$vRetDtPriceTTC      = 0;
	$vRetDtPriceTTCBase1 = 0;
	$vRetDtPriceTTCBase2 = 0;					
	$vRetDtPrice         = 0;
	$vRetDtPriceBase1    = 0;
	$vRetDtPriceBase2    = 0;
	$vRetDtDiscAmt       = 0;
	$vRetDtDiscAmtBase1  = 0;
	$vRetDtDiscAmtBase2  = 0;
		
				
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
		
	$ErrorExists  = 0;
	$ItemNotFound = 0;
	$QtyExistExceeded  = 0;
	$VendorNotFound = 0;			
	
	$sub_query = "SELECT ifNull(Item_Vat,0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) FROM Items WHERE item_Code = '".$txtItemCode."'";
	$sub_result = selectData($connection, $sub_query);
	$ItemVat      = $sub_result[0];
	$ItemPromo    = $sub_result[1];
	$ItemNonStock = $sub_result[2];

	$tax_flag = 0;
	$notax_flag = 1;
	if ($ItemVat > 0){
		$tax_flag = 1;
		$notax_flag = 0;
	}	
			
	if ($ItemNonStock == 0) {	

		
		$sub_query1  = " Select QtyExistsWSorder_Temp('".$txtItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($vRetDate)."', 0, 'RI', '', '', 0) QtyExists From Dual ";
		$sub_result1 = selectData($connection, $sub_query1);
		$min_available_qty = 0;
		$min_available_qty = $sub_result1[0];

		$sub_query2 = " Select ifNull(Sum(ifNull(SaleDt_Quantity,0)),0) FROM Temp_RetailDt ".
					  " WHERE Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$txtWarehouseCode."' And Sale_ID = $SRetId And SaleDt_ID != ifNull('".$SRetDtId."',0) ";	
		$sub_result2 = selectData($connection, $sub_query2);
		$min_available_qty = $min_available_qty - $sub_result2[0];
					
		if ($txtRetDtQty > $min_available_qty && $txtRetDtQty > 0)
			$QtyExistExceeded = 1;
	}		
		
	if (!empty($txtRetDtVendor) || $txtRetDtVendor != '') {
		
		$vendor_query = " Select Ledger_Number, Ledger_Name From Vendor ".
						    " Where ifNull(Vendor_active,0) = 1 ".
						    " And Ledger_Number = '".$txtRetDtVendor."' ";
		//$vendor_result = selectData($connection, $vendor_query);
		$vendor_result = mysql_query($vendor_query,$connection);
		$RecCount=mysql_num_rows($vendor_result);			
		
		if ($RecCount == 0) {
			$VendorNotFound = 1; 
			$message  = "Vendor Code Not Found.";
		}
			
	}	
	
	if (($QtyExistExceeded == 0  || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) && $VendorNotFound==0) {
		
		$sub_query3 = " Select Currency_code, ifNull(Sale_DiscountPer,0), Client_code ".
					  " From Temp_Retail As Retail ".
					  " Where Sale_ID = ".$SRetId;
					  //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
					 
			
		$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
		$sub_rows3=mysql_fetch_array($sub_result3);
			
		$vRetCurr        = $sub_rows3[0];
		$vRetDiscount    = $sub_rows3[1];
		$vRetCltCode     = $sub_rows3[2];
			
			
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
		$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 is in Promo Table Automatically Set Discount to promotion_discount					
		$queryPromotion = "select ifnull(promotion_discount,0) 
						from item_promotion, temp_retail 									
						where date_format(Sale_Date,'%Y-%m-%d %H:%i') between date_format(promotion_fromdate,'%Y-%m-%d %H:%i') and  date_format(promotion_todate,'%Y-%m-%d %H:%i') 
						and promotion_itemCode = '$txtItemCode' and Sale_id = '$SRetId' ";
		$resPromotion = mysql_query($queryPromotion,$connection);				
		$rowPromotion = mysql_fetch_row($resPromotion);
		$promotion_discount = $rowPromotion[0];
		if($promotion_discount > 0) $txtRetDtDiscount = $promotion_discount;	
			
			
		if ($CashRegisterTTC == 1) {
			$vRetDtPriceTTC      = $txtRetDtPrice;
			$vRetDtPriceTTCBase1 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt1;
			$vRetDtPriceTTCBase2 = ($vRetDtPriceTTC*$rate_dt)/$rate_dt2;					
				
			$vRetDtPrice      = ($vRetDtPriceTTC / (1 + $ItemVat/100));
			$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
			$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
							
		} else	{
			$vRetDtPrice      = $txtRetDtPrice;
			$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
			$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
					
			$vRetDtPriceTTC      = 0;
			$vRetDtPriceTTCBase1 = 0;
			$vRetDtPriceTTCBase2 = 0;
							
		}	
					
			
					 
		fbegin();
		$query = " UPDATE temp_retaildt SET  SaleDt_Quantity = $txtRetDtQty, ".
			     " SaleDt_Price = $vRetDtPrice, SaleDt_PriceBase1 = $vRetDtPriceBase1, SaleDt_PriceBase2 = $vRetDtPriceBase2, ".
				 " SaleDt_PriceTTC = $vRetDtPriceTTC, SaleDt_PriceTTCBase1 = $vRetDtPriceTTCBase1, SaleDt_PriceTTCBase2 = $vRetDtPriceTTCBase2, ".
				 " SaleDt_PriceVat = $vRetDtPriceTTC, SaleDt_DiscountPer = $txtRetDtDiscount, Journal_Type = '".$vRetDtType."', ".
				 " Vendor_Code = '".$txtRetDtVendor."', Slip_number = '".$txtRetDtSlip."' ".
				 " Where SaleDt_ID = ".$SRetDtId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		//$message1=$query;			 
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
		
		
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	} else {
		$ErrorExists = 1;
		if($VendorNotFound!=1){
			$sub_queryloc  = " select concat(description1 , ' - ',description2 , ' - ',description3 ) from item_location  where item_code = '".$txtItemCode."'";
			$sub_resultloc = selectData($connection, $sub_queryloc);
			$item_loc = '';
			$item_loc = $sub_resultloc[0];
			$message  = "Qty[$txtRetDtQty] exceeds Existing Qty[$min_available_qty] for Item (".$txtItemCode.") Location : $item_loc "; 
}		}
	
	

	if ($ErrorExists == 0) {
	
		$vRetDiscountAmt = 0;
		$vRetTotal = 0;
		$vRetDtTotal = 0;
		if($serviceChecked == '') 	$serviceChecked = 0;	
		if($taxConsumptionChk == '') $taxConsumptionChk = 0;	
		//Distribute The Total Discount On Detail Table
		$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
					  " From Temp_Retail ".
					  " Where Sale_ID = '".$SRetId."' ";
		$sub_result1 = selectData($connection, $sub_query1);
		$vRetDiscountAmt = $sub_result1[0];	
				
		if ($vRetDiscountAmt > 0) {
				
			$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt ".
						  " Where Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
			$sub_result2 = selectData($connection, $sub_query2);
			$vRetTotal   = $sub_result2[0];	
					
			$sub_query3 = " Select SaleDt_ID,  ".
						  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt As RetailDt  ".
						  " Where RetailDt.Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
							   
			//echo $sub_query3; 
			$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
			while($sub_rows3=mysql_fetch_array($sub_result3)){
					
				$vRetDtId      = $sub_rows3[0];
				$vRetDtTotal   = $sub_rows3[1];
						
						
				$vRetDtDiscAmt	    = 0;
				$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
				$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
				$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
						
				
				$sub_query4 =  " UPDATE temp_retaildt SET ".
							   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
							   " Where SaleDt_ID = '".$vRetDtId."' ";
									   
									 
				//echo $sub_query4; exit;
				if (!updateData($connection, $sub_query4, true))
					$error  = mysql_error(); 
						

			}
		}
		
		$totalPt = 0;
		if($POS_RedeemPoints == 1){
			$query = "select temp_retail.customer_code, ifnull(Customer_point,0), ifnull(customer.customer_special,0) from temp_retail 
					inner join customer on customer.customer_code = temp_retail.customer_code where sale_id = $SRetId ";
			$result =mysql_query($query,$connection);
			$row = mysql_fetch_row($result);
			$txtRetCustomerCode = $row[0];
			$Customer_point = $row[1];
			$customer_special = $row[2];
			if($Customer_point == '') $Customer_point = 0;
			if($customer_special == '') $customer_special = 0;
			if($customer_special == 0) $Customer_point = 0;
	
			$query = "select retail_salespoint from retailpoint limit 1; ";
			$result =mysql_query($query,$connection);
			$row = mysql_fetch_row($result);
			$retail_salespoint = $row[0];
			$totalPt = $Customer_point;	
		}		
		$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_RetailDt ".
				 " Where Sale_ID = ".$SRetId.
				 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
		//echo $query;
		$result=mysql_query($query,$connection) or die(mysql_error());
		while($rows=mysql_fetch_array($result)){

			$vRetDtTotal  = $rows[1];
			$vItemVat     = $rows[2];
			$vRetQty      = $vRetQty + $rows[3];
			if($customer_special == 1) $totalPt += ($retail_salespoint*$vRetDtTotal);		
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ((insertDate($vRetDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
				$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
				
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $rows[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
				if ($vItemVat > 0 && $rows[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
				if ($vItemVat > 0 && $rows[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
				if ($vItemVat > 0 && $rows[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
				if ($vItemVat > 0 && $rows[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
			}
						
		}			
					
					
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
		// Calculation of Discount Amount	
		if ($vRetDiscount > 0)
			$vRetDiscountAmt = (($vRetGrossTotal * $vRetDiscount) / 100);
			
		if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
		
		if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
			$vRetTaxConsp = (($vRetGrossTotal)*$cashregister_TaxConsumptionpPer/100);
			$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
			$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
		}		
		if ($cashregister_service == 1 && $serviceChecked == 1){
			$vRetService = (($vRetGrossTotal)*$cashregister_servicePercentage/100);
			$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
			$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
		}
		$vRetNetTotal         = $vRetGrossTotal + $vRetVat + $vRetTaxConsp + $vRetService - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				
		
		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
		$RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ;
		if($RetTipsB1 == '')	$RetTipsB1 = 0;			
					 
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2,  ".
				 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked, ".
				 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
				 " sale_TaxConsumptionChecked = $taxConsumptionChk, sale_customerAwardPt = $totalPt, Sales_TipsBase1 = $RetTipsB1 ".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
							 
		//echo $query."<br>";exit;			 
		$result=mysql_query($query,$connection);
		
				
		if ($result){
			fcommit();
		}else{
			$message  = mysql_error(); 
			frollback();
		}	
	}	
	
} 
else if ($mode == "refunddt" && $SRetId != "" && $SRetDtId != ""){
	
	$query = " update  Temp_RetailDt ".
					 " Set Saledt_quantity = abs(Saledt_quantity) * -1, journal_type='RR' WHERE SaleDt_id = '".$SRetDtId."'";
		$result = selectData($connection, $query);		
	

	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetDiscountPer = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	$vRetQty = 0;
		$vRetDtTotal = 0;
		$vItemVat = 0;
		$vRetTaxable = 0;
		$vRetNoneTaxable = 0;
		$vRetGrossTotal = 0;
		$vRetDiscountAmt = 0;
		$vRetDiscountPer = 0;
		$vRetVat = 0;
		$vRetVatBase1 = 0;
		$vRetVatBase2 = 0;

		
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vRetDtTax1 = 0;
		$vRetDtTax2 = 0;
		$vRetDtTax3 = 0;
		$vRetDtTax4 = 0;
		$vRetDtTax5 = 0;
		
		$vRetTax1 = 0;
		$vRetTax2 = 0;
		$vRetTax3 = 0;
		$vRetTax4 = 0;
		$vRetTax5 = 0;
		$vRetTax1B1 = 0;
		$vRetTax2B1 = 0;
		$vRetTax3B1 = 0;
		$vRetTax4B1 = 0;
		$vRetTax5B1 = 0;
		$vRetTax1B2 = 0;
		$vRetTax2B2 = 0;
		$vRetTax3B2 = 0;
		$vRetTax4B2 = 0;
		$vRetTax5B2 = 0;
		
	
	$vRetCurr         = $txtRetCurr;
	//$vRetDiscountAmt  = $txtRetDiscountAmt;
	//$vRetDiscountPer  = $txtRetDiscountPer;
	//$vRetVatAmt      = $txtRetVatAmt;
	//$vRetNetTotal    = $txtRetNetTotal;
	
	if(empty($txtAllowDisc)) $txtAllowDisc = 0;
	$vRetAllowDisc = $txtAllowDisc;
	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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 ( $ErrorExists == 0 ){

				$vRetDiscountAmt = 0;
				$vRetTotal = 0;
				$vRetDtTotal = 0;
					
				//Distribute The Total Discount On Detail Table
				$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
							  " From Temp_Retail ".
							  " Where Sale_ID = '".$SRetId."' ";
				$sub_result1 = selectData($connection, $sub_query1);
				$vRetDiscountAmt = $sub_result1[0];	
					
				if ($vRetDiscountAmt > 0) {
						
					$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt ".
								  " Where Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vRetTotal   = $sub_result2[0];	
							
					$sub_query3 = " Select SaleDt_ID,  ".
								  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt As RetailDt  ".
								  " Where RetailDt.Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
									   
					//echo $sub_query3; 
					$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
					while($sub_rows3=mysql_fetch_array($sub_result3)){
							
						$vRetDtId      = $sub_rows3[0];
						$vRetDtTotal   = $sub_rows3[1];
								
								
						$vRetDtDiscAmt	    = 0;
						$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
						$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
						$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
								
						
						$sub_query4 =  " UPDATE temp_retaildt SET ".
									   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
									   " Where SaleDt_ID = '".$vRetDtId."' ";
											   
											 
						//echo $sub_query4; exit;
						if (!updateData($connection, $sub_query4, true))
							$error  = mysql_error(); 
								

					}
				}
			
				$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
						 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
						 " From Temp_RetailDt ".
						 " Where Sale_ID = ".$SRetId.
						 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
				//echo $query;
				$result=mysql_query($query,$connection) or die(mysql_error());
				while($rows=mysql_fetch_array($result)){

					$vRetDtTotal  = $rows[1];
					$vItemVat     = $rows[2];
					$vRetQty      = $vRetQty + $rows[3];
						
					$tax_flag = 0;
					$notax_flag = 1;
					if ($vItemVat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
						
							
					$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
					$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
					// Calculation of Vat Amount
					if ((insertDate($txtDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
						$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
						
					if ($Module_AdditionalTaxes == 1) {
						if ($vItemVat > 0 && $rows[5] != 0)
							$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
						if ($vItemVat > 0 && $rows[6] != 0)
							$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
						if ($vItemVat > 0 && $rows[7] != 0)
							$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
						if ($vItemVat > 0 && $rows[8] != 0)
							$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
						if ($vItemVat > 0 && $rows[9] != 0)
							$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
					}
						
				}			
					
					
				$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
				if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
				$vRetDiscountPer      = ($vRetDiscountAmt/$vRetGrossTotal)*100;
					
				$vRetNetTotal         = $vRetGrossTotal + $vRetVat - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
				$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
				$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
				$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
				$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
				$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
				$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
				$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
				$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
				$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
				$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
				$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
				$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				

				$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
				$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
				$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
				$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
				$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
				$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
				$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
				$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
				$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
				$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
				fbegin();			 
				$query = " UPDATE temp_retail SET ".
						 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
						 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
						 " Sale_DiscountPer = $vRetDiscountPer, Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
						 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
						 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
						 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
						 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
						 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
						 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
						 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
						 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2, Journal_Type = 'RR'  ".
						 " WHERE Sale_ID = ".$SRetId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
				 
				$result=mysql_query($query,$connection);
				//echo $query."<br>";exit;
				
				if ( $result ){ 
					
					fcommit();
				} else
				{
				   $message  = mysql_error(); 
				   frollback();
				} 
		} 
		
		
}
else if ($mode == "refunddtall" && $SRetId != ""){
	
	$query = " update  Temp_RetailDt ".
					 " Set Saledt_quantity = abs(Saledt_quantity) * -1,  Journal_Type = 'RR' WHERE Sale_id = '".$SRetId."'";
		$result = selectData($connection, $query);	

$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetDiscountPer = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	$vRetQty = 0;
		$vRetDtTotal = 0;
		$vItemVat = 0;
		$vRetTaxable = 0;
		$vRetNoneTaxable = 0;
		$vRetGrossTotal = 0;
		$vRetDiscountAmt = 0;
		$vRetDiscountPer = 0;
		$vRetVat = 0;
		$vRetVatBase1 = 0;
		$vRetVatBase2 = 0;

		
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vRetDtTax1 = 0;
		$vRetDtTax2 = 0;
		$vRetDtTax3 = 0;
		$vRetDtTax4 = 0;
		$vRetDtTax5 = 0;
		
		$vRetTax1 = 0;
		$vRetTax2 = 0;
		$vRetTax3 = 0;
		$vRetTax4 = 0;
		$vRetTax5 = 0;
		$vRetTax1B1 = 0;
		$vRetTax2B1 = 0;
		$vRetTax3B1 = 0;
		$vRetTax4B1 = 0;
		$vRetTax5B1 = 0;
		$vRetTax1B2 = 0;
		$vRetTax2B2 = 0;
		$vRetTax3B2 = 0;
		$vRetTax4B2 = 0;
		$vRetTax5B2 = 0;
		$vRetCurr         = $txtCurr;
	//$vRetDiscountAmt  = $txtRetDiscountAmt;
	//$vRetDiscountPer  = $txtRetDiscountPer;
	//$vRetVatAmt      = $txtRetVatAmt;
	//$vRetNetTotal    = $txtRetNetTotal;
	
	if(empty($txtAllowDisc)) $txtAllowDisc = 0;
	$vRetAllowDisc = $txtAllowDisc;
	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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 ( $ErrorExists == 0 ){

				$vRetDiscountAmt = 0;
				$vRetTotal = 0;
				$vRetDtTotal = 0;
					
				//Distribute The Total Discount On Detail Table
				$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
							  " From Temp_Retail ".
							  " Where Sale_ID = '".$SRetId."' ";
				$sub_result1 = selectData($connection, $sub_query1);
				$vRetDiscountAmt = $sub_result1[0];	
					
				if ($vRetDiscountAmt > 0) {
						
					$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt ".
								  " Where Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vRetTotal   = $sub_result2[0];	
							
					$sub_query3 = " Select SaleDt_ID,  ".
								  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt As RetailDt  ".
								  " Where RetailDt.Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
									   
					//echo $sub_query3; 
					$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
					while($sub_rows3=mysql_fetch_array($sub_result3)){
							
						$vRetDtId      = $sub_rows3[0];
						$vRetDtTotal   = $sub_rows3[1];
								
								
						$vRetDtDiscAmt	    = 0;
						$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
						$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
						$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
								
						
						$sub_query4 =  " UPDATE temp_retaildt SET ".
									   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
									   " Where SaleDt_ID = '".$vRetDtId."' ";
											   
											 
						//echo $sub_query4; exit;
						if (!updateData($connection, $sub_query4, true))
							$error  = mysql_error(); 
								

					}
				}
			
				$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
						 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
						 " From Temp_RetailDt ".
						 " Where Sale_ID = ".$SRetId.
						 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
				//echo $query;
				$result=mysql_query($query,$connection) or die(mysql_error());
				while($rows=mysql_fetch_array($result)){

					$vRetDtTotal  = $rows[1];
					$vItemVat     = $rows[2];
					$vRetQty      = $vRetQty + $rows[3];
						
					$tax_flag = 0;
					$notax_flag = 1;
					if ($vItemVat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
						
							
					$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
					$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
					// Calculation of Vat Amount
					if ((insertDate($txtDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
						$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
						
					if ($Module_AdditionalTaxes == 1) {
						if ($vItemVat > 0 && $rows[5] != 0)
							$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
						if ($vItemVat > 0 && $rows[6] != 0)
							$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
						if ($vItemVat > 0 && $rows[7] != 0)
							$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
						if ($vItemVat > 0 && $rows[8] != 0)
							$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
						if ($vItemVat > 0 && $rows[9] != 0)
							$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
					}
						
				}			
					
					
				$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
				if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
				$vRetDiscountPer      = ($vRetDiscountAmt/$vRetGrossTotal)*100;
					
				$vRetNetTotal         = $vRetGrossTotal + $vRetVat - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
				$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
				$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
				$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
				$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
				$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
				$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
				$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
				$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
				$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
				$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
				$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
				$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				

				$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
				$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
				$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
				$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
				$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
				$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
				$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
				$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
				$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
				$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
				fbegin();			 
				$query = " UPDATE temp_retail SET ".
						 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
						 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
						 " Sale_DiscountPer = $vRetDiscountPer, Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
						 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
						 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
						 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
						 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
						 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
						 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
						 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
						 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2, Journal_Type = 'RR'  ".
						 " WHERE Sale_ID = ".$SRetId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
				 
				$result=mysql_query($query,$connection);
				//echo $query."<br>";exit;
				
				if ( $result ){ 
					
					fcommit();
				} else
				{
				   $message  = mysql_error(); 
				   frollback();
				} 
		} 		
}
//Delete Detail Mode
else if ($mode == "deletedt" && $SRetId != "" && $SRetDtId != ""){

	$AllowDelete = 0;
	$message  = '';
	
	//Check If RetailDt Is Posted
	$query = "SELECT ifNull(SaleDt_Posted,0) As SaleDtPosted FROM RetailDt WHERE SaleDt_id = ".$SRetDtId;
	$result = selectData($connection, $query);
	$RetDtPosted = $result[0];
	
	if ($RetDtPosted == 1 ){
		$message  = 'Delete not allowed, record posted.';
		$AllowDelete = 1;
	}
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		
		if (!isset($txtCurr))
		   $txtCurr = $StpCurrCode;
		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];
		

		$ErrorExists    = 0;
		
		$vRetQty = 0;
		$vRetDtTotal = 0;
		$vItemVat = 0;
		$vRetTaxable = 0;
		$vRetNoneTaxable = 0;
		$vRetGrossTotal = 0;
		$vRetDiscountAmt = 0;
		$vRetDiscountPer = 0;
		$vRetVat = 0;
		$vRetVatBase1 = 0;
		$vRetVatBase2 = 0;
		$vRetService = 0;
		$vRetServiceBase1 = 0;
		$vRetServiceBase2 = 0;
		$vRetTaxConsp = 0;
		$vRetTaxConspBase1 = 0;
		$vRetTaxConspBase2 = 0;

		
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vRetDtTax1 = 0;
		$vRetDtTax2 = 0;
		$vRetDtTax3 = 0;
		$vRetDtTax4 = 0;
		$vRetDtTax5 = 0;
		
		$vRetTax1 = 0;
		$vRetTax2 = 0;
		$vRetTax3 = 0;
		$vRetTax4 = 0;
		$vRetTax5 = 0;
		$vRetTax1B1 = 0;
		$vRetTax2B1 = 0;
		$vRetTax3B1 = 0;
		$vRetTax4B1 = 0;
		$vRetTax5B1 = 0;
		$vRetTax1B2 = 0;
		$vRetTax2B2 = 0;
		$vRetTax3B2 = 0;
		$vRetTax4B2 = 0;
		$vRetTax5B2 = 0;
		
		
		$sub_query = " SELECT RetailDt.Item_CodePacked, RetailDt.Item_code ".
			         " FROM Temp_RetailDt As RetailDt ".
					 " Where RetailDt.SaleDt_ID = '".$SRetDtId."'";
			
		$sub_result = selectData($connection, $sub_query);
		$vItemCodePacked  = $sub_result[0];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
			
			// Delete From TempPucrhasesSerialNo For Selected Record
			$query = " DELETE FROM Temp_Purchasesserialno ".
					 " WHERE RetailDt_ID  = ".$SRetDtId.
					 " AND Journal_Type In ('DI','DR') ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
			
			// Delete From TempRetailDt For Selected Record
			$query = " DELETE FROM Temp_RetailDt ".
					 " WHERE SaleDt_id = '".$SRetDtId."'";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
		
			
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select SaleDt_ID, RetailDt.Item_CodePacked, RetailDt.Item_code  ".
					   " From Temp_RetailDt As RetailDt  ".
					   " Where RetailDt.Sale_ID = ".$SRetId.
					   " And RetailDt.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 RetailDt_ID  = ".$vSaDtId.
						" AND Journal_Type In ('DI','DR') ";
						//" And Logged_Code = '".$_SESSION['useraccount']."' ";
						
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 		
						
				// Delete From TempRetailDt For Selected Record
				$query = " DELETE FROM Temp_RetailDt ".
						 " WHERE SaleDt_id = ".$vSaDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}	
			}
		
		}	
		
			
		if ( $ErrorExists == 0 ){

				$vRetDiscountAmt = 0;
				$vRetTotal = 0;
				$vRetDtTotal = 0;
					
				//Distribute The Total Discount On Detail Table
				$sub_query1 = " Select ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
							  " From Temp_Retail ".
							  " Where Sale_ID = '".$SRetId."' ";
				$sub_result1 = selectData($connection, $sub_query1);
				$vRetDiscountAmt = $sub_result1[0];	
					
				if ($vRetDiscountAmt > 0) {
						
					$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt ".
								  " Where Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vRetTotal   = $sub_result2[0];	
							
					$sub_query3 = " Select SaleDt_ID,  ".
								  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
								  " From Temp_RetailDt As RetailDt  ".
								  " Where RetailDt.Sale_ID = '".$SRetId."' ".
								  " And ifNull(Price_offer,0) = 0 ".
								  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
									   
					//echo $sub_query3; 
					$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
					while($sub_rows3=mysql_fetch_array($sub_result3)){
							
						$vRetDtId      = $sub_rows3[0];
						$vRetDtTotal   = $sub_rows3[1];
								
								
						$vRetDtDiscAmt	    = 0;
						$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
						$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
						$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
								
						
						$sub_query4 =  " UPDATE temp_retaildt SET ".
									   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
									   " Where SaleDt_ID = '".$vRetDtId."' ";
											   
											 
						//echo $sub_query4; exit;
						if (!updateData($connection, $sub_query4, true))
							$error  = mysql_error(); 
								

					}
				}
				$totalPt = 0;
				if($POS_RedeemPoints == 1){
					$query = "select temp_retail.customer_code, ifnull(Customer_point,0), ifnull(customer.customer_special,0) from temp_retail 
							inner join customer on customer.customer_code = temp_retail.customer_code where sale_id = $SRetId ";
					$result =mysql_query($query,$connection);
					$row = mysql_fetch_row($result);
					$txtRetCustomerCode = $row[0];
					$Customer_point = $row[1];
					$customer_special = $row[2];
					if($Customer_point == '') $Customer_point = 0;
					if($customer_special == '') $customer_special = 0;
					if($customer_special == 0) $Customer_point = 0;
			
					$query = "select retail_salespoint from retailpoint limit 1; ";
					$result =mysql_query($query,$connection);
					$row = mysql_fetch_row($result);
					$retail_salespoint = $row[0];
					$totalPt = $Customer_point;	
				}
				
				$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
						 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
						 " From Temp_RetailDt ".
						 " Where Sale_ID = ".$SRetId.
						 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
				//echo $query;
				$result=mysql_query($query,$connection) or die(mysql_error());
				while($rows=mysql_fetch_array($result)){

					$vRetDtTotal  = $rows[1];
					$vItemVat     = $rows[2];
					$vRetQty      = $vRetQty + $rows[3];
					if($customer_special == 1) $totalPt += ($retail_salespoint*$vRetDtTotal);	
					$tax_flag = 0;
					$notax_flag = 1;
					if ($vItemVat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
						
							
					$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
					$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
					// Calculation of Vat Amount
					if ((insertDate($txtDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
						$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
						
					if ($Module_AdditionalTaxes == 1) {
						if ($vItemVat > 0 && $rows[5] != 0)
							$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
						if ($vItemVat > 0 && $rows[6] != 0)
							$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
						if ($vItemVat > 0 && $rows[7] != 0)
							$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
						if ($vItemVat > 0 && $rows[8] != 0)
							$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
						if ($vItemVat > 0 && $rows[9] != 0)
							$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
					}
						
				}			
					
					
				$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
				if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
				$vRetDiscountPer      = ($vRetDiscountAmt/$vRetGrossTotal)*100;
				
				if ($cashregister_service == 1 && $serviceChecked == 1){
					$vRetService = (($vRetGrossTotal)*$cashregister_servicePercentage/100);
					$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
					$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
				}	
				if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
					$vRetTaxConsp = (($vRetGrossTotal)*$cashregister_TaxConsumptionpPer/100);
					$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
					$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
				}
				
				$vRetNetTotal         = $vRetGrossTotal + $vRetVat + $vRetService + $vRetTaxConsp - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
				$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
				$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
				$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
				$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
				$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
				$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
				$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
				$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
				$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
				$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
				$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
				$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				

				$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
				$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
				$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
				$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
				$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
				$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
				$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
				$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
				$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
				$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
				$RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ;
				if($RetTipsB1 == '')	$RetTipsB1 = 0;		
					 
				fbegin();			 
				$query = " UPDATE temp_retail SET ".
						 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
						 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
						 " Sale_DiscountPer = $vRetDiscountPer, Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
						 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
						 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
						 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
						 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
						 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
						 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
						 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
						 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2,  ".
						 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked,".
						 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
						 " sale_TaxConsumptionChecked = $taxConsumptionChk, sale_customerAwardPt = $totalPt, Sales_TipsBase1 = $RetTipsB1  ".
						 " WHERE Sale_ID = ".$SRetId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
				 
				$result=mysql_query($query,$connection);
				//echo $query."<br>";exit;
				
				if ( $result ){ 
					
					fcommit();
				} else
				{
				   $message  = mysql_error(); 
				   frollback();
				} 
		} // End If No Error Exists 
		else {
			fcommit();
		}	
			
		
		
	
	} // End If No Constraints Found On Delete
	
	
}

//Calculate Discounts
else if ($mode == "adddiscount" && $SRetId != ""){

	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetDiscountPer = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	
	$vRetService 	  = 0;
	$vRetServiceBase1 = 0;
	$vRetServiceBase2 = 0;
	
	$vRetTaxConsp 		= 0;
	$vRetTaxConspBase1 	= 0;
	$vRetTaxConspBase2 	= 0;
	
	$vRetCurr         = $txtRetCurr;
	//$vRetDiscountAmt  = $txtRetDiscountAmt;
	//$vRetDiscountPer  = $txtRetDiscountPer;
	//$vRetVatAmt      = $txtRetVatAmt;
	//$vRetNetTotal    = $txtRetNetTotal;
	
	if(empty($txtAllowDisc)) $txtAllowDisc = 0;
	$vRetAllowDisc = $txtAllowDisc;
	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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];
		
	
	$DiscNotAllowed = 0;
	if ($CashRegisterTTC == 1) {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		
		$sub_query = " Select ifNull(Sale_Total,0) As GrossTotal, ((ifNull(Sale_Taxable,0)* (1 + $Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0)) As GrossTotalTTC ".
					 " From Temp_Retail ".
					 " Where Sale_ID = '".$SRetId."' ";//echo $sub_query;
		$sub_result = selectData($connection, $sub_query);
		$vRetGrossTotal    = $sub_result[0];	
		$vRetGrossTotalTTC = $sub_result[1];	
		
		$vRetDiscountPer  = (($txtRetDiscountAmt/$vRetGrossTotalTTC)*100);
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotal)/100);
		
	} else {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		$vRetDiscountPer  = $txtRetDiscountPer;
	}
	
	//echo $vRetDiscountAmt;exit;
	
	//Distribute The Total Discount On Detail Table
	$sub_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
				  " Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
				  " From Temp_RetailDt ".
				  " Where Sale_ID = '".$SRetId."' ".
				  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
	if ($vRetAllowDisc != 1) $sub_query3 = $sub_query3." And ifNull(Price_offer,0) = 0 ";			  
				  
	$sub_result3 = selectData($connection, $sub_query3);
	$vRetTotal   = $sub_result3[0];	
	
	if ($vRetAllowDisc == 0) {
		if ($vRetTotal == 0 || $vRetTotal == ''){
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, all items are offer.';
		}
		else if (Round(abs($vRetDiscountAmt),2) > Round(abs($vRetTotal),2)) {
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, discount amount should be less than total items amount.';
		}
	}
	
	if ( $DiscNotAllowed == 0 ){ 
		$sub_query1 = " Select SaleDt_ID,  ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_RetailDt As RetailDt  ".
					  " Where RetailDt.Sale_ID = '".$SRetId."' ".
					  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
					  
		if ($vRetAllowDisc != 1) $sub_query1 = $sub_query1." And ifNull(Price_offer,0) = 0 ";
					  
				   
		//echo $sub_query1; exit;
		$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
		while($sub_rows1=mysql_fetch_array($sub_result1)){
		
			$vRetDtId      = $sub_rows1[0];
			$vRetDtTotal   = $sub_rows1[1];
			
			
			$vRetDtDiscAmt	    = 0;
			$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
			$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
			$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
			
	
			$sub_query2 =  " UPDATE temp_retaildt SET ".
						   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
						   " Where SaleDt_ID = '".$vRetDtId."' ";
						   
						 
			//echo $sub_query2; exit;
			if (!updateData($connection, $sub_query2, true))
				$error  = mysql_error(); 
			

		}
		
			
		$sub_query3 = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
					  " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					  //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
		//echo $sub_query3;
		$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
		while($sub_rows3=mysql_fetch_array($sub_result3)){

			$vRetDtTotal  = $sub_rows3[1];
			$vItemVat     = $sub_rows3[2];
			//echo $vRetDtTotal;exit;			
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ($vItemVat > 0)
				$vRetVatAmt = $vRetVatAmt + (($vRetDtTotal - $sub_rows3[4])*$vItemVat/100);
						
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $sub_rows3[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[5]/100);
				if ($vItemVat > 0 && $sub_rows3[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[6]/100);
				if ($vItemVat > 0 && $sub_rows3[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[7]/100);
				if ($vItemVat > 0 && $sub_rows3[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[8]/100);
				if ($vItemVat > 0 && $sub_rows3[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[9]/100);	
			}
						
		}		
		
		$queryChk = "select ifnull(sale_serviceChecked,0), ifnull(sale_TaxConsumptionChecked,0) from temp_retail where Sale_ID = $SRetId "; 
		$resChk = mysql_query($queryChk, $connection);
		$rowChk = mysql_fetch_row($resChk);
		$serviceChecked = $rowChk[0];
		$taxConsumptionChk = $rowChk[1];
		 
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
		
		if ($cashregister_service == 1 && $serviceChecked == 1){
			$vRetService = ((($vRetGrossTotal)-$vRetDiscountAmt)*$cashregister_servicePercentage/100);
			$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
			$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
		}	
		if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
			$vRetTaxConsp = ((($vRetGrossTotal)-$vRetDiscountAmt)*$cashregister_TaxConsumptionpPer/100);
			$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
			$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
		}
		
		$vRetNetTotal         = $vRetGrossTotal + $vRetVatAmt + $vRetService + $vRetTaxConsp-$vRetDiscountAmt  + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;			
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVatAmt*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVatAmt*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
		$RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ;
		if($RetTipsB1 == '')	$RetTipsB1 = 0;			
					 
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_DiscountPer = $vRetDiscountPer, Sale_VAT = $vRetVatAmt, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2,  ".
				 " Driver_Code = '".$txtRetDriverCode."',Discount_user = '".$discount_user."', ".
				 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked, ".
				 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
				 " sale_TaxConsumptionChecked = $taxConsumptionChk , Sales_TipsBase1 = $RetTipsB1 ".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			//echo $query."<br>";exit;			 
				 
		$result=mysql_query($query,$connection);
		
				
		if ( $result ){ 
			//jp add viewer disc
			
			// add view for discount
			
			
			$Parameters = array();
			$Parameters['sale_id'] = $SRetId;
			$Parameters['user_account'] = $_SESSION['useraccount'];
			$Parameters['cashregister'] = $_SESSION['cashregister'];
			
			createviewer('Retail','Ds',$Parameters,$connection);
			
			fcommit();
		} else
		{
		   $message  = mysql_error(); 
		   frollback();
		} 
	} 

}


else if ($mode == "adddiscount2" && $SRetId != ""){

	$vItemVat = 0;
	$vRetTipsB1 = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetDiscountPer = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	
	$vRetCurr         = $txtRetCurr;
		
	$vRetAllowDisc = 1;
	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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($Module_PriceOffer > 0) {
		$sub_query1 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
					  " Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And ifNull(Price_offer,0) = 0 ";
		$sub_result1 = selectData($connection, $sub_query1);
		
		if ($CashRegisterTTC == 1)
			$txtRetGrossTotalOffer = $sub_result1[1];
		else
			$txtRetGrossTotalOffer = $sub_result1[0];
		
		$txtRetDiscountAmt  = $txtRetGrossTotalOffer*$txtRetDiscountPer/100;
	}		
	else{
		$sub_query = " Select Round(ifNull(Sale_Taxable,0) + ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As GrossTotal, ".
				 " Round((ifNull(Sale_Taxable,0)* (1 + $Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As GrossTotalTTC ".
				 " From Temp_Retail As Retail ".
				 " Where Sale_ID = ".$SRetId;
				 
		//echo $sub_query;
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_rows=mysql_fetch_array($sub_result);
		
		if ($CashRegisterTTC == 1) {
			$txtRetGrossTotal    = $sub_rows[1];
		}	
		else {
			$txtRetGrossTotal    = $sub_rows[0];
		}	
		$txtRetDiscountAmt  = $txtRetGrossTotal*$txtRetDiscountPer/100;
		
	}
	$txtRetDiscountAmt = round(($txtRetDiscountAmt)*pow(10,$DecimalBase))/pow(10,$DecimalBase);
	
	$DiscNotAllowed = 0;
	if ($CashRegisterTTC == 1) {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		
		$sub_query = " Select ifNull(Sale_Total,0) As GrossTotal, ((ifNull(Sale_Taxable,0)* (1 + $Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0)) As GrossTotalTTC  ".
					 " From Temp_Retail ".
					 " Where Sale_ID = '".$SRetId."' ";
		$sub_result = selectData($connection, $sub_query);
		$vRetGrossTotal    = $sub_result[0];	
		$vRetGrossTotalTTC = $sub_result[1];	
		
		$vRetDiscountPer  = (($txtRetDiscountAmt/$vRetGrossTotalTTC)*100);
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotal)/100);
		
	} else {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		$vRetDiscountPer  = $txtRetDiscountPer;
	}
	
	
	//Distribute The Total Discount On Detail Table
	$sub_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
				  " Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
				  " From Temp_RetailDt ".
				  " Where Sale_ID = '".$SRetId."' ".
				  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
	if ($vRetAllowDisc != 1) $sub_query3 = $sub_query3." And ifNull(Price_offer,0) = 0 ";			  
				  
	$sub_result3 = selectData($connection, $sub_query3);
	$vRetTotal   = $sub_result3[0];	
	
	if ($vRetAllowDisc == 0) {
		if ($vRetTotal == 0 || $vRetTotal == ''){
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, all items are offer.';
		}
		else if (Round(abs($vRetDiscountAmt),2) > Round(abs($vRetTotal),2)) {
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, discount amount should be less than total items amount.';
		}
	}
	
	if ( $DiscNotAllowed == 0 ){ 
		$sub_query1 = " Select SaleDt_ID,  ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_RetailDt As RetailDt  ".
					  " Where RetailDt.Sale_ID = '".$SRetId."' ".
					  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
					  
		if ($vRetAllowDisc != 1) $sub_query1 = $sub_query1." And ifNull(Price_offer,0) = 0 ";
					  
				   
		//echo $sub_query1; exit;
		$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
		while($sub_rows1=mysql_fetch_array($sub_result1)){
		
			$vRetDtId      = $sub_rows1[0];
			$vRetDtTotal   = $sub_rows1[1];
			
			
			$vRetDtDiscAmt	    = 0;
			$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
			$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
			$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
			
	
			$sub_query2 =  " UPDATE temp_retaildt SET ".
						   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
						   " Where SaleDt_ID = '".$vRetDtId."' ";
						   
						 
			//echo $sub_query2; exit;
			if (!updateData($connection, $sub_query2, true))
				$error  = mysql_error(); 
			

		}
		
			
		$sub_query3 = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
					  " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					  //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
		//echo $sub_query3;
		$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
		while($sub_rows3=mysql_fetch_array($sub_result3)){

			$vRetDtTotal  = $sub_rows3[1];
			$vItemVat     = $sub_rows3[2];
						
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ($vItemVat > 0)
				$vRetVatAmt = $vRetVatAmt + (($vRetDtTotal - $sub_rows3[4])*$vItemVat/100);
						
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $sub_rows3[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[5]/100);
				if ($vItemVat > 0 && $sub_rows3[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[6]/100);
				if ($vItemVat > 0 && $sub_rows3[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[7]/100);
				if ($vItemVat > 0 && $sub_rows3[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[8]/100);
				if ($vItemVat > 0 && $sub_rows3[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[9]/100);	
			}
						
		}			
					
					
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
	
		if ($cashregister_service == 1 && $serviceChecked == 1){
					// $vRetService = (($vRetGrossTotal+$vRetVat)*$cashregister_servicePercentage/100);
					$vRetService = (($vRetGrossTotal)*$cashregister_servicePercentage/100);
					$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
					$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
				}	
		if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
					// stoppeed VAT
				//	$vRetTaxConsp = (($vRetGrossTotal+$vRetVat)*$cashregister_TaxConsumptionpPer/100);
					$vRetTaxConsp = (($vRetGrossTotal)*$cashregister_TaxConsumptionpPer/100);
					$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
					$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
				}
				
	
       $sub_queryt = " Select Sales_TipsBase1  ".
					 " From Temp_Retail ".
					 " Where Sale_ID = '".$SRetId."' ";
		$sub_resulttip = selectData($connection, $sub_queryt);
		$RetTipsB1    = $sub_resulttip[0];	
		
		$vRetTipsB1   =$RetTipsB1   ;
				
				
		$vRetNetTotal         = $vRetGrossTotal + $vRetVatAmt + $vRetService + $vRetTaxConsp- $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5-$vRetTipsB1;			
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		

       // $RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ;
		//if($RetTipsB1 == '')	$RetTipsB1 = 0;			
		// // JP
		// echo "<BR>cashregister_TaxConsumption". $cashregister_TaxConsumption ;
		// echo "<BR>taxConsumptionChk". $taxConsumptionChk ;
		// echo "<BR>vRetGrossTotal". $vRetGrossTotal ;
		// echo "<BR>vRetVatAmt". $vRetVatAmt ;
		// echo "<BR>vRetService". $vRetService ;
		// echo "<BR>vRetTaxConsp". $vRetTaxConsp;
		// echo "<BR>vRetDiscountAmt". $vRetDiscountAmt ;
		// echo "<BR>vRetTax1". $vRetTax1 ;
		// echo "<BR>vRetTax2". $vRetTax2 ;
		// echo "<BR>vRetTax3". $vRetTax3 ;
		// echo "<BR>vRetTax4". $vRetTax4 ;
		// echo "<BR>vRetTax5". $vRetTax5 ;
		// ECHO "<br>RetTipsB1: ". $RetTipsB1 =	$vRetNetTotalBase1 - RoundTotal($vRetNetTotalBase1, $CashReg_RoundDivisor, $connection) ; 
		// if($RetTipsB1 == '')	$RetTipsB1 = 0;
		// ECHO "<br>vRetNetTotal: ".$vRetNetTotal         = $vRetGrossTotal + $vRetVatAmt + $vRetService + $vRetTaxConsp- $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5 -$RetTipsB1;			
		// ECHO "<br>vRetNetTotalBase1: ".$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		// // JP 
		
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVatAmt*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVatAmt*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
		
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_DiscountPer = $vRetDiscountPer, Sale_VAT = $vRetVatAmt, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2  ".
				 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked, ".
				 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
				 " sale_TaxConsumptionChecked = $taxConsumptionChk, Sales_TipsBase1 = $RetTipsB1 ".
				 " ,Driver_Code = '".$txtRetDriverCode."'".
				 " ,Discount_user = '".$discount_user."'".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
				 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
				
		if ( $result ){ 
					
			fcommit();
		} else
		{
		   $message  = mysql_error(); 
		   frollback();
		} 
	}
	$sub_query = " Select Round(ifNull(Sale_NetTotal,0), ".$DecimalBase.")  ".
				 " From Temp_Retail As Retail ".
				 " Where Sale_ID = ".$SRetId;//echo $sub_query;	
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
    $sub_rows=mysql_fetch_row($sub_result);		
	$txtRetNetTotal      = $sub_rows[0];
	echo "[BRK]";
	echo $txtRetNetTotal;
	exit;
}


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

	$AllowDelete = 0;
	$message  = '';
	
	//Check If Sales Is Posted
	$query = "SELECT ifNull(Sale_Posted,0) As SalePosted FROM Retail WHERE Sale_id = ".$SRetId;
	$result = selectData($connection, $query);
	$RetPosted = $result[0];
	
	if ($RetPosted == 1 ){
		$message  = 'Delete not allowed, invoice posted.';
		$AllowDelete = 1;
	}
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
	
		$sub_query = " Select Journal_Id From Retail Where Sale_id = ".$SRetId;
		$sub_result = selectData($connection, $sub_query);
		$vRetJournalID = $sub_result[0];
		if(empty($vRetJournalID)) $vRetJournalID = -1;
		
		
		//Update Used Serials Set USed=0 For Related Delivery Serials
		$sub_query = " SELECT RelatedSerial_Id FROM Purchasesserialno ".
					 " WHERE RetailDt_ID In (Select SaleDt_id From RetailDt Where Sale_id = ".$SRetId." ) ".
					 " AND Journal_Type In ('DI','DR') ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
		
			$sub_query1 = " UPDATE purchasesserialno ".
						  " Set SerialNo_Used = 0 ".
						  "	WHERE Serial_ID = '".$sub_rows[0]."'";
						  
			if (!updateData($connection, $sub_query1, true))		 
				$message  = mysql_error(); 		  
		}	
				
		$Parameters = array();
		$Parameters['sale_id'] = $SRetId;
		$Parameters['user_account'] = $_SESSION['useraccount'];
		$Parameters['cashregister'] = $_SESSION['cashregister'];
		
		createviewer('Retail','D',$Parameters,$connection);
	 
		// Delete From PurchasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE RetailDt_ID In (Select SaleDt_id From RetailDt Where Sale_id = ".$SRetId." ) ".
				 " AND Journal_Type In ('DI','DR') ";
				 
		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', '$SRetId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'retail', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		// Delete From RetailDt For Selected Record
		$query = " DELETE FROM RetailDt ".
				 " WHERE Sale_id = ".$SRetId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From Retail For Selected Record
			$query = " DELETE FROM Retail ".
					 " WHERE Sale_id = ".$SRetId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
			if ($vRetJournalID != -1) {
				
				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vRetJournalID;
				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	

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

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

	// Delete From TempPurchasesSerialNo For Selected Record
	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE RetailDt_ID In (Select SaleDt_id From Temp_RetailDt Where Sale_id = ".$SRetId." ) ".
			 " AND Journal_Type In ('DI','DR') ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 

		
	// Delete From TempRetailDt For Selected Record
	$query = " DELETE FROM Temp_RetailDt ".
			 " WHERE Sale_id = ".$SRetId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempRetail For Selected Record
		$query = " DELETE FROM Temp_Retail ".
				 " WHERE Sale_id = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

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

	$ErrorExists = 0;
	$AllowEdit = 1;
	$message  = '';
	
	//Check If Sales Is Posted
	$query = "SELECT ifNull(Sale_Posted,0) As SalePosted FROM Retail WHERE Sale_id = ".$SRetId;
	$result = selectData($connection, $query);
	$RetPosted = $result[0];
	
	if ($RetPosted == 1 ){
		$message  = 'Edit not allowed, invoice posted.';
		$AllowEdit = 0;
	}
	
	
	//If No Constraints Exists On Edit
	if ($AllowEdit == 1) {
	
	
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_retail (Sale_id, Sale_Reference, Sale_Date, Sale_Remark, Client_code, Currency_Code, Project_Code, Costcenter_code, CashRegister_Name, Sale_TotalQuantity, Sale_TotalQuantityRet, ".
				 " Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, Sale_DiscountPer, Sale_DiscountAmount, Sale_DiscountBase1, ".
				 " Sale_DiscountBase2, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, ".
				 " Sale_Posted, Sale_Mode, Journal_Type, Journal_Id, Sale_Tax1, Sale_Tax1Base1, Sale_Tax1Base2, Sale_Tax2, Sale_Tax2Base1, Sale_Tax2Base2, Sale_Tax3, Sale_Tax3Base1, ".
				 " Sale_Tax3Base2, Sale_Tax4, Sale_Tax4Base1, Sale_Tax4Base2, Sale_Tax5, Sale_Tax5Base1, Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, ".
				 " Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, Sale_CashCur, Sale_CashAccount, Sale_Cash, Sale_CashBase1, Sale_CashBase2, Sale_CheckDate, Sale_CheckNo, Sale_Bank, ".
				 " Sale_BankBranch, Sales_CashInBase1, Sales_CashOutBase1, Sales_CashInBase2, Sales_CashOutBase2, Sales_TipsBase1, Coupon_amount, Coupon_amountbase1, Coupon_amountbase2, ".
				 " Coupon_id, Sale_information, Sale_ClientCur, Sale_CreditAccountVat, Sales_CreditAmount, Sales_CreditAmountBase1, Sales_CreditAmountBase2, Sales_creditacc, Sales_creditacccur, ".
				 " Login_CardNo, Sale_SupervisorCode, Customer_Code, Salesman_code, SaleOrder_Id, SaleOrder_Reference, User_Account, Logged_Code, Owner_Branch, ProjectDt_Id, sale_type, driver_Code, ".
				 " Sale_numberofguests, Sale_BelongsToGroup, payment_description, sale_service, sale_serviceB1, sale_serviceB2, sale_TaxConsumption, sale_TaxConsumptionB1, sale_TaxConsumptionB2, ".
				 " guest_name, sale_serviceChecked, sale_TaxConsumptionChecked, sale_customerDiscount, sale_customerAwardPt, RedeemPoints_Account, sale_redeemPtAmount, sale_redeemPtAmount1, ".
				 " sale_redeemPtAmount2, sale_customerRedeemedPt, sale_customerRedeemChk ) ".
				 " SELECT Sale_id, Sale_Reference, Sale_Date, Sale_Remark, Client_code, Currency_Code, Project_Code, Costcenter_code, CashRegister_Name, Sale_TotalQuantity, Sale_TotalQuantityRet, ".
				 " Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, Sale_DiscountPer, Sale_DiscountAmount, Sale_DiscountBase1, ".
				 " Sale_DiscountBase2, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, ".
				 " Sale_Posted, Sale_Mode, Journal_Type, Journal_Id, Sale_Tax1, Sale_Tax1Base1, Sale_Tax1Base2, Sale_Tax2, Sale_Tax2Base1, Sale_Tax2Base2, Sale_Tax3, Sale_Tax3Base1, ".
				 " Sale_Tax3Base2, Sale_Tax4, Sale_Tax4Base1, Sale_Tax4Base2, Sale_Tax5, Sale_Tax5Base1, Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, ".
				 " Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, Sale_CashCur, Sale_CashAccount, Sale_Cash, Sale_CashBase1, Sale_CashBase2, Sale_CheckDate, Sale_CheckNo, Sale_Bank, ".
				 " Sale_BankBranch, Sales_CashInBase1, Sales_CashOutBase1, Sales_CashInBase2, Sales_CashOutBase2, Sales_TipsBase1, Coupon_amount, Coupon_amountbase1, Coupon_amountbase2, ".
				 " Coupon_id, Sale_information, Sale_ClientCur, Sale_CreditAccountVat, Sales_CreditAmount, Sales_CreditAmountBase1, Sales_CreditAmountBase2, Sales_creditacc, Sales_creditacccur, ".
				 " Login_CardNo, Sale_SupervisorCode, Customer_Code, Salesman_code, SaleOrder_Id, SaleOrder_Reference, User_Account, '".$_SESSION['useraccount']."', Owner_Branch , ProjectDt_Id, ".
				 " sale_type, driver_Code, Sale_numberofguests, Sale_BelongsToGroup , payment_description, sale_service, sale_serviceB1, sale_serviceB2, sale_TaxConsumption, sale_TaxConsumptionB1, ".
				 " sale_TaxConsumptionB2, guest_name, sale_serviceChecked, sale_TaxConsumptionChecked, sale_customerDiscount, sale_customerAwardPt, RedeemPoints_Account, sale_redeemPtAmount, sale_redeemPtAmount1, ".
				 " sale_redeemPtAmount2, sale_customerRedeemedPt, sale_customerRedeemChk ".
				 " FROM Retail ".
				 " WHERE Sale_id = ".$SRetId;
		
		if (!updateData($connection, $query, true)) {
		  $ErrorExists = 1;
		  $message  = mysql_error(); 	
		}  
		//echo $message.$query; exit;		
			 
		if ($ErrorExists == 0) {	 
			$query = " INSERT INTO temp_retaildt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_Barcode, Item_Vat, Item_Measure, ". 
					 " SaleDt_Quantity, SaleDt_QuantityReturn, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, SaleDt_PriceVat, ".
					 " SaleDt_PriceTTC, SaleDt_PriceTTCBase1, SaleDt_PriceTTCBase2, SaleDt_ExpireDate, RelatedDt_Id, SaleDt_Posted, Size_Measure, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, SaleDt_DirectStkDbt, ".
					 " SaleDt_DirectStkCrd, SaleDt_DirectStkCur, SaleDt_DiscountAcc, SaleDt_ItemAccount, SaleDt_PromoAcc, Vendor_Code, Slip_number, Price_offer, Item_CodePacked, SerialNo_Code, SaleDt_ActualPrice, SaleDt_ItemStatus, ".
					 " SaleDt_ItemStatusRemark, SalesDt_Remark, Logged_Code  ) ".
					 " SELECT SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, Warehouse_Code, Item_code, Item_Barcode, Item_Vat, Item_Measure, ". 
					 " SaleDt_Quantity, SaleDt_QuantityReturn, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, SaleDt_PriceVat, ".
					 " SaleDt_PriceTTC, SaleDt_PriceTTCBase1, SaleDt_PriceTTCBase2, SaleDt_ExpireDate, RelatedDt_Id, SaleDt_Posted, Size_Measure, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, SaleDt_DirectStkDbt, ".
					 " SaleDt_DirectStkCrd, SaleDt_DirectStkCur, SaleDt_DiscountAcc, SaleDt_ItemAccount, SaleDt_PromoAcc, Vendor_Code, Slip_number, Price_offer, Item_CodePacked, SerialNo_Code, SaleDt_ActualPrice, SaleDt_ItemStatus, ".
					 " SaleDt_ItemStatusRemark, SalesDt_Remark, '".$_SESSION['useraccount']."'  ".
					 " FROM Retaildt ".
					 " WHERE Sale_id = ".$SRetId;
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 	

			
			$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, SaleDt_ID, PurchaseDt_id, RetailDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
					 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.DeliveryDt_ID, Purchasesserialno.SaleDt_ID, Purchasesserialno.PurchaseDt_id, Purchasesserialno.RetailDt_ID, Purchasesserialno.Item_Code, Purchasesserialno.SerialNo_Code, ".
					 " SerialNo_Used,  RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Purchasesserialno.Warehouse_code, '".$_SESSION['useraccount']."' ".
					 " FROM Purchasesserialno ".
					 " Inner Join Temp_RetailDt on Purchasesserialno.RetailDt_ID = Temp_RetailDt.SaleDt_ID ".
					 " WHERE Temp_RetailDt.Sale_id = ".$SRetId.
					 " AND Purchasesserialno.Journal_Type In ('DI','DR') ";
					 
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 	

		}
	}
	
	
}


//Posting Transactions
else if ($mode == "postretails" ){
	//var_dump($_POST);exit;
	set_time_limit(0);
	
	 
	
	$cashregisters = array();
	$c= 0;
	if($FI_MultiplePosting == 1){
		
		$query = "select CashRegister_Name from cashregister order by CashRegister_Name";			 
		$res = mysql_query($query,$connection);
		$i=0;
		while($rw = mysql_fetch_row($res)){
			$chkCashregister = 'chkCashregister'.$i;
			if($$chkCashregister == 1) {
				$cashregisters[$c] = $rw[0];
				$c++;
			}
			$i++; 
		}
	} else $cashregisters[0] = $_SESSION['cashregister'];
	
	// echo"<BR> sess cashregister : ". $_SESSION['cashregister'];
	// echo"<BR> cashregister [ 0 ]  : ". $cashregisters[0];
	if ($cashregister_DPbeforePosting==0) {	
	// Delete From TempPurchasesSerialNo For Selected Record
		$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE RetailDt_ID In (Select SaleDt_id From Temp_RetailDt Where Sale_id In (Select Sale_id From Temp_Retail Where User_Account = '".$_SESSION['useraccount']."' )) ".
			 " AND Journal_Type In ('DI','DR') ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 

		
	// Delete From TempRetailDt For Selected Record
		$query = " DELETE FROM Temp_RetailDt ".
			 " WHERE Sale_id In (Select Sale_id From Temp_Retail Where User_Account = '".$_SESSION['useraccount']."' )";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
		if (updateData($connection, $query, true)) {
		// Delete From TempRetail For Selected Record
			$query = " DELETE FROM Temp_Retail ".
				 " WHERE User_Account = '".$_SESSION['useraccount']."' ";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		}
	}
	// create adjustmnet before posting
	foreach($cashregisters as $cashregister){
			//fbegin();
					// echo "<br>xxx";
			if ($ischecked == 1){
				// echo"<BR>".
				$sub_queryX = "select create_adjustmentPOS('". $cashregister."',  '".insertMySQLDate($txtDateFrom)."', '".insertMySQLDate($txtDateTo)."' ) ";
				$sub_resultX = mysql_query($sub_queryX,$connection);
				$error = mysql_error();
			}
	}
	// exit;
	$negativeQty = 0;
	if($Module_CheckNegativeQtyBeforePosting == 1){
		
		foreach($cashregisters as $cashregister){	
			$Qry_QtyExists = " select ifnull(QtyExists(item_code,Warehouse_Code,retail.Sale_Date,0,'RI','',''),0)
							from retaildt
							inner join retail on retail.Sale_id = retaildt.Sale_id
							where CashRegister_Name = '$cashregister' and sale_posted <> 1
							and date_format(retail.Sale_Date,'%Y-%m-%d') between date_format('".insertMySQLDate($txtDateFrom)."','%Y-%m-%d') and date_format('".insertMySQLDate($txtDateTo)."','%Y-%m-%d');";		
			//echo $Qry_QtyExists;echo"<br>";		 
			$result = mysql_query($Qry_QtyExists, $connection);
			while($row = mysql_fetch_row($result)){
				$min_exists_qty = $row[0];
			echo $min_exists_qty." ".$cashregister."<br>";
				if($min_exists_qty <= 0) {
					$negativeQty = 1;
					break;
				}
			}
			if($min_exists_qty <= 0) {
				$message = "Posting is not allowed! Negative Quantity Exists!";
				break;
			}
		}
	}
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($_SESSION['dbName'], $conn) or die("Could not find DB");
	
	if($negativeQty == 0){
		foreach($cashregisters as $cashregister){
			//fbegin();
			
			$resultvars = mysql_query("set @Result := 0, @JvResult := 0, @SaleId :=0, @SaleRef := 0, @SaleDtId := 0 ", $conn);

			//if ($Module_PostRetailOneToOne == 1)
				//$sub_query = " call Posting_RetailOneToOne('". $_SESSION['cashregister']."', 0, 0, '". $_SESSION['dbName']."', '". $_SESSION['dbLabel']."', ".
				//			 "                	           '". $_SESSION['useraccount']."', '". $_SESSION['username']."', $Module_PostingByCashRegister, @Result, @JvResult) ";
			//else 
				$sub_query = " call Posting_Retail('". $cashregister."', 0, '". $_SESSION['dbName']."', '". $_SESSION['dbLabel']."', ".
							 "                     '". $_SESSION['useraccount']."', '". $_SESSION['username']."', $Module_PostingByCashRegister, ".
							 "                     '".insertMySQLDate($txtDateFrom)."', '".insertMySQLDate($txtDateTo)."', @Result, @JvResult) ";
							
			echo $sub_query;echo "<br>"; exit;
			$sub_result = mysql_query($sub_query,$conn);
			$error = mysql_error();
			
			
			$sub_query1 = " select @Result, @JvResult from dual ";
			$sub_result1 = mysql_query($sub_query1,$conn) or die(mysql_error());
			$cur1 = mysql_fetch_row($sub_result1);
			
			 if ($cur1[0] == -5) {
			   $message = 'Error In Procedure Posting_Retail: '.$error;
			   //frollback();
			}   
			else if ($cur1[0] == -2) {
			   $message = 'Error In Procedure Create_DeliveryAutoJv/Create_SaleAutoJv: '.$error;
			   //frollback();
			}   
			else if ($cur1[1] == -3) {
			   $message = 'Error In Procedure Create_RetailAutoJv: '.$error;   
			   //frollback();
			}   
			else if  ($cur1[0] == -1)  {
			   $message = 'Error In Procedure Create_Jv: '.$error;   
			   //frollback();
			}   
			else if ($cur1[0] >= 0 && $cur1[1] >= 0) {
				$message = 'Posting transactions done successfully. ';	
				//fcommit();
			}	
			
		} 
	$query_module  = "select Module_DirectStockSales, Module_Delivery from module";
	$result_module = mysql_query($query_module, $connection);
	$row_module    = mysql_fetch_array($result_module);
	extract($row_module);
	
	if($Module_Delivery == 0)
	{
		if($ModuleDirectStockSales == 1)
		{
			$txtDateFrom;
			$txtDateTo;
			
			$from_date = explode("/", $txtDateFrom);
		    $from_date = $from_date[2]."-".$from_date[1]."-".$from_date[0];
			
			$to_date = explode("/", $txtDateTo);
			$to_date = $to_date[2]."-".$to_date[1]."-".$to_date[0]." 23:59:59";
		    $query_deliveries     = "select Delivery_id as DeliveryID from deliveries where delivery_date between '".$from_date."' and '".$to_date."'";
			$result_deliveries    = mysql_query($query_deliveries, $connection);
			while($row_deliveries = mysql_fetch_array($result_deliveries))
			{
				extract($row_deliveries);
				$query_deliverydt     = "select deliverydt_id as DeliveryDtID 
					                     from deliverydt inner join items on temp_deliverydt.item_code = items.item_code
								         where items.Item_Production = 1 and delivery_id = '".$DeliveryID."'";
				$result_deliverydt    = mysql_query($query_deliverydt, $connection);
				while($row_deliverydt = mysql_fetch_array($result_deliverydt))
				{
					extract($row_deliverydt);
					$query_update_cost  = "update deliverydt set Deliverydt_cost = '0', Deliverydt_costbase1 = '0', Deliverydt_costbase2 = '0' where DeliveryDt_id = '".$DeliveryDtID."'";
					$result_update_cost = mysql_query($query_update_cost, $connection);
				}
			}
		}
	}
	
	} //negative qty

}

//Closing CashRegister
else if ($mode == "closingcashreg" ){

	$ClosingAmountB1 = 0;
	$ClosingAmountB2 = 0;
	
	
	/*$sub_query = " Select Count(*) From Temp_Retail ".
				 " Where Upper(CashRegister_Name) = Upper('".$_SESSION['cashregister']."') ";
	if ($txtDateFrom != "") 
		$sub_query .= " And Sale_Date >= '".formatDateClosing($txtDateFrom)."' ";
	$sub_result = selectData($connection, $sub_query);
	$ExistsPendingInv = $sub_result[0];*/
	if (empty($ExistsPendingInv)) $ExistsPendingInv = 0;
	
	if ($ExistsPendingInv == 0) {
	
		$sub_query = " Select ifNull(Sum(ifNull(Sale_NetTotalBase1,0)),0), ifNull(Sum(ifNull(Sale_NetTotalBase2,0)),0) From Retail ".
					 " Where Upper(CashRegister_Name) = Upper('".$_SESSION['cashregister']."') ";
		if ($txtDateFrom != "")			 
			$sub_query .= " And Sale_Date >= '".formatDateClosing($txtDateFrom)."'";
		
		$sub_result = selectData($connection, $sub_query);
		$ClosingAmountB1 = $sub_result[0];
		$ClosingAmountB2 = $sub_result[1];
		//echo $sub_query; exit;
		
		if ($ClosingAmountB1 != 0 || $ClosingAmountB2 != 0) {
		
			fbegin();
			$query = " INSERT INTO cashregisterclosing (CashRegister_Name, CashRegisterClosing_Date, CashRegisterClosing_AmountB1, CashRegisterClosing_AmountB2) ".
					 " VALUES ( '".$_SESSION['cashregister']."', now(), $ClosingAmountB1, $ClosingAmountB2 )";
							 
					 
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
				
			if ($result){
				fcommit();
			}else{
				$message  = mysql_error($connection); 
				frollback();
			}
		}
	} else {	
		$message  = "Closing not allowed. Pending invoice(s) exist."; 
	}
}

//Payment
else if ($mode == "payment" && $SRetId != ""){
	
	$chkRedeemCustomerPt = $_GET['chkRedeemCustomerPt'];
	$slipNo 			 = $_GET['slipNo'];
	
	$vRetCurr         = $txtRetCurr;
	$vRetDate         = $txtRetDate;
	$vRetCustomerCode = $txtRetCustomerCode;
	$vRetSalesmanCode = $txtRetSalesmanCode;
	$vRetRemark       = $txtRetRemark;
	$vRetCouponId     = $txtRetCouponId;
	$vRetCouponAmt    = $txtRetCouponAmt;
	
	$vRetCreditCard = $txtRetCreditCard;
	$vRetCreditName = $txtRetCreditName;
	$vRetCreditCurr = $txtRetCreditCurr;
	$vRetCreditAmt  = $txtRetCreditAmt;

	$vRetCheckNo    = $txtRetCheckNo;
	$vRetCheckDate  = $txtRetCheckDate;
	$vRetBankName   = $txtRetBankName;
	$vRetBranchName = $txtRetBranchName;
	$vRetCashCurr   = $txtRetCashCurr;
	$vRetCashAmt    = $txtRetCashAmt;
	
	$vRetCashInB1   	= $txtRetCashInB1; 
	$vRetCashOutB1  	= $txtRetCashOutB1; 
	$vRetCashInB2   	= $txtRetCashInB2;
	$vRetCashOutB2  	= $txtRetCashOutB2;
	$vRetCustomerAmount = $txtRetCustomerAmount;
	
	$vRetTipsB1     = abs($txtRetTipsB1);
	//$vRetTipsB1     = $txtRetTipsB1H; by nadine
	
	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	
	if (empty($vRetCreditAmt)) 		$vRetCreditAmt = 0;
	if (empty($vRetCashAmt))   		$vRetCashAmt = 0;
	if (empty($vRetCashInB1))  		$vRetCashInB1 = 0;
	if (empty($vRetCashOutB1)) 		$vRetCashOutB1 = 0;
	if (empty($vRetCashInB2))  		$vRetCashInB2 = 0;
	if (empty($vRetCashOutB2)) 		$vRetCashOutB2 = 0;
	if (empty($vRetTipsB1))    		$vRetTipsB1 = 0;
	if (empty($vRetCustomerAmount)) $vRetCustomerAmount = 0;
	if (empty($pointToRedeem)) 		$pointToRedeem = 0;
	if (empty($chkRedeemCustomerPt)) $chkRedeemCustomerPt = 0;
	
	if (empty($vRetCouponId)) $vRetCouponId = 'Null';
	else $vRetCouponId = $vRetCouponId;
	
	if (empty($vRetCheckDate)) $vRetCheckDate = 'Null';
	else $vRetCheckDate = "'".insertMySQLDate($vRetCheckDate)."'";
	
	if($RedeemPoints_Account == '') $RedeemPoints_Account = "NULL";
	else $RedeemPoints_Account = "'".$RedeemPoints_Account."'";
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCreditCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCreditCurr."' )";
	$result = selectData($connection, $query);
	$ratecredit_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCashCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCashCurr."' )";
	$result = selectData($connection, $query);
	$ratecash_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];
	
	
	$vRetCouponAmtBase1 = ($vRetCouponAmt*$rate_dt)/$rate_dt1;
	$vRetCouponAmtBase2 = ($vRetCouponAmt*$rate_dt)/$rate_dt2;
	$vRetCreditAmtBase1 = ($vRetCreditAmt*$ratecredit_dt)/$rate_dt1;
	$vRetCreditAmtBase2 = ($vRetCreditAmt*$ratecredit_dt)/$rate_dt2;
	$vRetCashAmtBase1   = ($vRetCashAmt*$ratecash_dt)/$rate_dt1;
	$vRetCashAmtBase2   = ($vRetCashAmt*$ratecash_dt)/$rate_dt2;
	
	$vRetCustomerAmountB1   = ($vRetCustomerAmount*$rate_dt)/$rate_dt1;
	$vRetCustomerAmountB2   = ($vRetCustomerAmount*$rate_dt)/$rate_dt2;
	
	
	if($POS_RedeemPoints == 1 && $vRetCustomerAmount > 0){
		$queryRetail = "select retail_salespoint, retail_redeemPoint from retailpoint limit 1";
		$resRetail = mysql_query($queryRetail,$connection);
		$rowRetail = mysql_fetch_row($resRetail);
		$salespoint = $rowRetail[0];
		$redeemPoint = $rowRetail[1];
		
		$pointToRedeem = round($vRetCustomerAmount*$redeemPoint);
	}
	//Check For Customer and Salesman Codes Before Insert
	if ($vRetCustomerCode != '') {
		$sub_query = " Select Count(Customer_Code) From Customer ".
					 " Where Customer_Code = '".$vRetCustomerCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0){
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Customer Code.';
		}	
	}
	if ($vRetSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$vRetSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Salesman Code.';
		}	
	}
	
	//If Retail Related To Delivery Order Then Check For Order Items Count and Qty
	if ($Module_RestaurantDelivery == 1 && $ErrorExists == 0) {
		$sub_query = " Select SaleOrder_Id From Temp_Retail ".
					 " Where Sale_ID = '".$SRetId."'";
		$sub_result = selectData($connection, $sub_query);
		$vRetOrderId = $sub_result[0];
		if(!empty($vRetOrderId)) {
			//Check For Order Items Count
			$sub_query = " Select Count(*) From Temp_RetailDt ".
						 " Where Sale_ID = '".$SRetId."'";
			$sub_result = selectData($connection, $sub_query);
			$vCountRetailItems = $sub_result[0];
			if(empty($vCountRetailItems)) $vCountRetailItems = 0;
			
			$sub_query = " Select Count(*) From RetailOrderDt ".
						 " Where Sale_ID = '".$vRetOrderId."'";
			$sub_result = selectData($connection, $sub_query);
			$vCountOrderItems = $sub_result[0];
			if(empty($vCountOrderItems)) $vCountOrderItems = 0;
			
			if ($vCountOrderItems != $vCountRetailItems) {
				$ErrorExists = 1;
				$message = "Save not allowed. Items count doesn't match Order items count.";
			}
			
			//Check For Order Items Qty
			if ($ErrorExists == 0) {
				$sub_query1 = " Select RetailDt.SaleDt_ID, RetailDt.Item_Code, ifNull(RetailDt.SaleDt_Quantity,0), ifNull(Items.Item_Weight,0) ".
							  " From Temp_RetailDt As RetailDt  ".
							  " Inner Join Items on RetailDt.Item_Code = Items.Item_Code ".
							  " Where RetailDt.Sale_ID = '".$SRetId."' ".
							  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
				//echo $sub_query1; exit;
				$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
				while($sub_rows1=mysql_fetch_array($sub_result1)){
				
					$vRetDtId    = $sub_rows1[0];
					$vItemCode   = $sub_rows1[1];
					$vItemQty    = $sub_rows1[2];
					$vItemWeight = $sub_rows1[3];
					
					
					$sub_query2 = " Select SaleDt_ID, Item_Code, ifNull(SaleDt_Quantity,0) ".
								  " From RetailOrderDt  ".
								  " Where RetailOrderDt.Sale_ID = '".$vRetOrderId."' ".
								  " And RetailOrderDt.Item_Code = '".$vItemCode."'";
					$sub_result2 = selectData($connection, $sub_query2);
					$vOrderQty   = $sub_result2[2];
					if(empty($vOrderQty)) $vOrderQty = 0;

					if (($CashReg_Weight == 1 && $vItemWeight != 0 && abs($vOrderQty - $vItemQty) > 0.5) ||
                        ((($CashReg_Weight == 1 && $vItemWeight == 0) || ($CashReg_Weight != 1 && 1 == 1)) && ($vOrderQty - $vItemQty) != 0 ) ){
						
						$ErrorExists = 1;
						$message = "Save not allowed. Item(s) qty doesn't match Order item(s) qty.";
						Break;
					}
					
				}

			}
		
		}
	}	
	
	
	//Check All Invoice Items Qty Should Not Be Zero
	if ($ErrorExists == 0) {
		$sub_query = " Select Count(*) From Temp_RetailDt ".
					 " Where Sale_ID = '".$SRetId."' ".
					 " And ifNull(abs(SaleDt_Quantity),0) = 0 ";
		$sub_result = selectData($connection, $sub_query);
		$vCountItems = $sub_result[0];
		if(empty($vCountItems)) $vCountItems = 0;
			
		if ($vCountItems > 0) {
			$ErrorExists = 1;
			$message = "Save not allowed. Invoice has item(s) with qty equal to zero.";
		}
	
	}
	// Check Slip No With Bank jp and Fady
	// if ($ErrorExists == 0) {
		 // $sub_query = " Select Count(*) From Retail  ".
					 // " Where sale_slipNo = '". $slipNo ."' ".
					 // " And sales_creditacc = '".$vRetCreditCard."' ";
		
		// $sub_result = selectData($connection, $sub_query);
		// $vCountItems = $sub_result[0];
		// if(empty($vCountItems)) $vCountItems = 0;
			
		// if ($vCountItems > 0) {
			// $ErrorExists = 1;
			// $message = "Save not allowed. Invoice has Duplicated Slip.";
		// }
	
	// }
	
	if ($ErrorExists == 0) {
		$queryRef = "select sale_reference from retail where sale_id = '".$SRetId."' ";
		$sub_resultRef  = selectData($connection, $queryRef);
		$vSaleRef     = $sub_resultRef[0];
		
		
		
		if($vSaleRef == ''){
	// 		$sub_query1 = " UPDATE temp_retaildt SET ".
	// 					  " Sale_Date = '".insertMySQLDate($vRetDate)."' ".
	// 					  " WHERE Sale_id = '".$SRetId."' ";
	//    }else{
		   $sub_query1 = " UPDATE temp_retaildt SET ".
						 " Sale_Date = now() ".
						 " WHERE Sale_id = '".$SRetId."' ";
		// echo $sub_query1."<br> 111";exit;		   
		if (!updateData($connection, $sub_query1, true))		 
			$message  = mysql_error(); 
	   }
		
		/**/			  
		
		
		
		if($vSaleRef == ''){
	// 		$sub_query1 = " UPDATE temp_retail SET ".
	// 					  " Sale_Date = '".insertMySQLDate($vRetDate)."' ".
	// 					  " WHERE Sale_id = '".$SRetId."' ";
	//    }else{
		   $sub_query1 = " UPDATE temp_retail SET ".
						 " Sale_Date = now() ".
						 " WHERE Sale_id = '".$SRetId."' ";
						//  echo $querydt."<br> 222";exit;		   
		if (!updateData($connection, $sub_query1, true))		 
			$message  = mysql_error(); 
		
	   }
		
		
		$vTotalQty        = 0;
		$vTotalQtyReturn  = 0;

		$sub_query2 = " Select Sum(if(Journal_Type = 'RI', SaleDt_Quantity, 0)) As TotalQty,  Sum(if(Journal_Type = 'RR', abs(SaleDt_Quantity), 0)) As TotalQtyReturn ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
		//echo $sub_query2;
		$sub_result2  = selectData($connection, $sub_query2);
		$vTotalQty        = $sub_result2[0];
		$vTotalQtyReturn  = $sub_result2[1];
		
		if (empty($vTotalQty)) $vTotalQty = 0;
		if (empty($vTotalQtyReturn)) $vTotalQtyReturn = 0;
					
		if (empty($vRetCustomerCode)) $vRetCustomerCode = 'Null';
		else $vRetCustomerCode = "'".ereg_replace("'", "\'", trim($vRetCustomerCode))."'"; 
		if (empty($vRetSalesmanCode)) $vRetSalesmanCode = 'Null';
		else $vRetSalesmanCode = "'".ereg_replace("'", "\'", trim($vRetSalesmanCode))."'"; 
		
		//Calculations For Tips
		$sub_query1 = " Select ifNull(Sale_NetTotalBase1,0) ".
					  " From Temp_Retail ".
					  " Where Sale_Id = '".$SRetId."' ";
		$sub_result1  = selectData($connection, $sub_query1);
		$vRetNetTotalB1 = $sub_result1[0];
		
		/*$vRetTipsB1 = ($vRetNetTotalB1 - $vRetCouponAmtBase1 - $vRetCreditAmtBase1 - $vRetCashAmtBase1 - 
					  ($vRetCashInB1 - $vRetCashOutB1) - (($vRetCashInB2 - $vRetCashOutB2)*$rate_dt2/$rate_dt1));	
		*/
		if ($vRetCouponAmt != '' && $vRetCouponAmt < 0 &&  $vRetCouponId == 'Null') {
			$vCouponName = $txtRetCouponName;
			
			fbegin();	
			$vRetCouponId = get_nextsequence('Coupon_Id','',$connection);	
			$vCouponRef   = get_nextsequence('Coupon_Reference','',$connection);
			fcommit();
			
			$query = " Insert Into Coupon (Coupon_Id, Coupon_Reference, Coupon_Name, Coupon_Active, Coupon_Amount, ".
					 " Coupon_AmountBase1, Coupon_AmountBase2, Currency_Code, Coupon_AmountConsum, Coupon_AmountConsumBase1, ".
					 " Coupon_AmountConsumBase2, Coupon_Date ) ".
					 " Values ( ".$vRetCouponId.", ".$vCouponRef.", '".ereg_replace("'", "\'", trim($vCouponName))."', 1, ".
					 "			".abs($vRetCouponAmt).", ".abs($vRetCouponAmtBase1).", ".abs($vRetCouponAmtBase2).", '".$vRetCurr."', ".
					 "          0, 0, 0, '".insertMySQLDate($vRetDate)."' ) ";
			//echo $query; exit;		 
			$result=mysql_query($query,$connection);
		}
		
		$query   = " SELECT Sale_Reference FROM Retail WHERE Sale_id = '".$SRetId."' ";
					$result  = selectData($connection, $query);
					$vSaRef  = $result[0];
										
					/*if ($vSaRef != '') {
						$query   = " SELECT Sales_creditacc,Sales_CreditAmount,Sale_Cash,Sales_CashInBase1,Sales_CashOutBase1, Sale_Total
										FROM Temp_Retail WHERE Sale_id = '".$SRetId."' ";
						$result  = selectData($connection, $query);
						
		
						$Parameters['sale_id'] = $SRetId;
						$Parameters['user_account'] = $_SESSION['useraccount'];
						$Parameters['cashregister'] = $_SESSION['cashregister'];
						$Parameters['Old_Sales_creditacc'] = $result[0];
						$Parameters['Old_Sales_CreditAmount'] = $result[1];
						$Parameters['Old_Sale_Cash'] = $result[2];
						$Parameters['Old_Sales_CashInBase1'] = $result[3];
						$Parameters['Old_Sales_CashOutBase1'] = $result[4];
						$Parameters['Old_Sale_Total'] = $result[5];
						//createviewer('Retail','U',$Parameters,$connection);
					}*/
		$newRetail = 0;		
		if ($vSaRef == '') {
			$newRetail = 1;
		}
		if ($vSaRef == '' && $FC_ChangeRetailDate == 1){
			$vRetDate1  = $PRetDate;
			$retdate = explode("/",$vRetDate1);
			$newdate = $retdate[2]."-".$retdate[1]."-".$retdate[0];
			if (strlen($newdate) == 10){
				$newdate = $newdate." ".date("H:i:s");
			}	
				$query1 = "update temp_retail set sale_date = '$newdate' where Sale_ID = $SRetId ";
				$res1 = mysql_query($query1,$connection);
				$query2 = "update temp_retaildt set sale_date = '$newdate' where Sale_ID = $SRetId ";
				$res2 = mysql_query($query2,$connection);
		} 
		$query = " UPDATE temp_retail SET ".
				 " Customer_code = $vRetCustomerCode, Salesman_code = $vRetSalesmanCode, Sale_information = '".ereg_replace("'", "\'", ereg_replace("\\\\", "", trim($vRetRemark)))."', ".
				 " Coupon_id = $vRetCouponId, Coupon_amount = $vRetCouponAmt, Coupon_amountbase1 = $vRetCouponAmtBase1, Coupon_amountbase2 = $vRetCouponAmtBase2, ".
				 " Sales_creditacc = '".$vRetCreditCard."', Sales_creditacccur = '".$vRetCreditCurr."',   ".
				 " Sales_CreditAmount = $vRetCreditAmt, Sales_CreditAmountBase1 = $vRetCreditAmtBase1, Sales_CreditAmountBase2 = $vRetCreditAmtBase2, ".
				 " Sale_CashCur = '".$vRetCashCurr."', Sale_Cash = $vRetCashAmt, Sale_CashBase1 = $vRetCashAmtBase1, Sale_CashBase2 = $vRetCashAmtBase2, ".
				 " Sale_CheckDate = $vRetCheckDate, Sale_CheckNo = '".$vRetCheckNo."', Sale_Bank = '".$vRetBankName."', Sale_BankBranch = '".$vRetBranchName."', ".
				 " Sales_CashInBase1 = $vRetCashInB1, Sales_CashOutBase1 = $vRetCashOutB1, Sales_CashInBase2 = $vRetCashInB2, Sales_CashOutBase2 = $vRetCashOutB2, ".
				 " Sales_TipsBase1 = $vRetTipsB1, Sale_TotalQuantity = $vTotalQty, Sale_TotalQuantityRet = $vTotalQtyReturn  ".
				 " ,Payment_Description = '$vRetCreditName', sale_redeemPtAmount = $vRetCustomerAmount, sale_redeemPtAmount1 = $vRetCustomerAmountB1, ".
				 " sale_redeemPtAmount2 = $vRetCustomerAmountB2, RedeemPoints_Account = ".$RedeemPoints_Account.", sale_customerRedeemedPt = ".$pointToRedeem.", ".
				 " sale_slipNo = '$slipNo', ".
				 " sale_customerRedeemChk = ".$chkRedeemCustomerPt." ";
		if ($vSaRef == '')
		$query .= ", User_Account = '".$_SESSION['useraccount']."', CashRegister_Name = '".$_SESSION['cashregister']."' ";		
		$query .= " WHERE Sale_ID = ".$SRetId;
						 
		 // echo $query."<br>";exit;			 
		$result=mysql_query($query,$connection);
		
		
		if ($result){
						
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
				
			$query = "Select Count(*) From Temp_Retail where Sale_ID = '".$SRetId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
				if ($vSaRef != '') {
					$Parameters['sale_id'] = $SRetId;
					$Parameters['user_account'] = $_SESSION['useraccount'];
					$Parameters['cashregister'] = $_SESSION['cashregister'];

					createviewer('Retail','U',$Parameters,$connection);
				}
				if ($vSaRef == '') {
					$Parameters['sale_id'] = $SRetId;
					$Parameters['user_account'] = $_SESSION['useraccount'];
					$Parameters['cashregister'] = $_SESSION['cashregister'];
					$queryDisc = "select ifnull(Sale_DiscountPer,0) from temp_retail where sale_id = $SRetId ";
					$resDisc = mysql_query($queryDisc,$connection);
					$rowDisc = mysql_fetch_row($resDisc);
					$discp = $rowDisc[0];
					if($discp >0)
					createviewer('Retail','I',$Parameters,$connection);
				}	
				
			calculatebases($SRetId, $base1, $base2, $Module_AdditionalTaxes, $Setup_VatStartDate, $cashregister_TaxConsumption, $cashregister_TaxConsumptionpPer, $cashregister_service, $cashregister_servicePercentage, $connection);		
					$query_checkDelivery  = "select count(*) as RetailExist from retail where sale_id = '$SRetId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($RetailExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);		
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempRetail('".$SMode."', ".$SRetId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$result = $result[0];
				
				//echo 'error='.$result; exit;
				if ($result != 0){
					fcommit();
							
					$query   = " SELECT Sale_Reference, Costcenter_code, ifNull(Sale_Posted,0) FROM Retail WHERE Sale_id = '".$SRetId."' ";
					$result  = selectData($connection, $query);
					$vSaRef  = $result[0];
					$vCostCentCode = $result[1];
					$vSalePosted   = $result[2];
							
				
					
					if ($vSaRef == '') {
						if ($Module_ReferenceByCostcenter == 0) $vCostCentCode = '';
						
						fbegin();
						$vSaRef = get_nextsequence('retail_reference',$vCostCentCode,$connection);	
						fcommit();
								
						$query = " UPDATE retail SET ".
								 " Sale_Reference = $vSaRef ".
								 " WHERE Sale_id = '".$SRetId."' ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
							
					}

					 if ($CashRegister_AutoPost == 1 && $vSalePosted == 0)
						$message = RetailAutoPost($SRetId, $_SESSION['cashregister'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'], $Module_PostingByCashRegister); 	
					else if ($Module_PostRetailOneToOne == 1)
						$message = RetailPostPos($SRetId, $_SESSION['cashregister'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'], $Module_PostingByCashRegister); 
						
					if ($Module_Synchro == 1) {
						InsertSynchroLoc($connection,'I','RETAIL',$SRetId,'',$Setup_Branch);
					}	
			         if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SRetId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'retail', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
					//echo $message; exit; 
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempRetail Function'; 
					frollback();
				}
			}	
				
		} else{
			$message  = mysql_error($connection); 
			//frollback();
		}
	}// End if($ErrorExists == 0)
	
	if( $POS_RedeemPoints == 1 ){
		adjustCustomerAwardPoints($SRetId, $connection);
	
	} else {
			
			$query_prevPoint = "select customer_point from customer where customer_code = $vRetCustomerCode and Customer_special=1"; //echo $query_prevPoint; exit;
			$result_prevPoint = mysql_query($query_prevPoint, $connection);
			$row_prevPoint = mysql_fetch_row($result_prevPoint);
			if($row_prevPoint[0] !='') $prev_point = $row_prevPoint[0];
			else $prev_point = 0;
			
			if($Module_RewardPointPer == 1)
			$query_point = "select round(retail_pointPer*$vRetCashInB1/100)
							from retailpoint
							where amount <= $vRetCashInB1 and  $vRetCashInB1 <= toAmount ; "; 	
			else 
			$query_point = "select FLOOR($vRetCashInB1/amount)*retail_point from retailpoint";//echo $query_point; exit;
			$result_point = mysql_query($query_point, $connection); 
			$row_point = mysql_fetch_row($result_point);
			
			$customer_point = $prev_point+$row_point[0]; 
			if($customer_point>0) {
				$query_uppoint = "update customer set customer_point = $customer_point where customer_code = $vRetCustomerCode and Customer_special=1";// echo $query_uppoint; exit;
				$result_uppoint = mysql_query($query_uppoint, $connection);
			}
	}
	//exit;
	
	if ($newRetail == 1){
		$queryup .= "update retail set User_Account = '".$_SESSION['useraccount']."', CashRegister_Name = '".$_SESSION['cashregister']."' 
					WHERE Sale_ID = ".$SRetId; 
		$resup = mysql_query($queryup, $connection);			
	}
	//echo $queryup;exit;
}

else if ($mode == "checkpayment" && $SRetId != ''){
	$dueamnt 			= $_GET['dueamnt'];
	$creditamnt 		= $_GET['creditamnt'];
	$cashamnt1 			= $_GET['cashamnt1'];
	$cashamnt2 			= $_GET['cashamnt2'];
	$differamnt1 		= $_GET['differamnt1'];
	$differamnt2 		= $_GET['differamnt2'];
	$checkamnt 			= $_GET['checkamnt'];
	$tipsamnt 			= $_GET['tipsamnt'];
	$checkCur 			= $_GET['checkCur'];
	$CreditCur 			= $_GET['CreditCur'];
	$RetCustomerAmount 	= $_GET['RetCustomerAmount'];
	$RetCustomerAmount 	= $_GET['RetCustomerAmount'];
	$RetCouponAmt	 	= $_GET['RetCouponAmt'];
	$vSlipNo	 		= $_GET['SlipNo'];
	
	if ($creditamnt == '')			$creditamnt = 0;
	if ($cashamnt1 == '') 			$cashamnt1 = 0;
	if ($cashamnt2 == '') 			$cashamnt2 = 0;
	if ($differamnt1 == '') 		$differamnt1 = 0;
	if ($differamnt2 == '') 		$differamnt2 = 0;
	if ($checkamnt == '') 			$checkamnt = 0;
	if ($RetCustomerAmount == '') 	$RetCustomerAmount = 0;
	if ($RetCouponAmt == '') 		$RetCouponAmt = 0;
	
	 
	
	$querySlipRequired = "select ifnull(CashRegister_RestrictSlipNoOnPay,0) from cashregister";
	$resSlipRequired = mysql_query($querySlipRequired,$connection);
	$rowSlipRequired = mysql_fetch_array($resSlipRequired);
	if($rowSlipRequired[0] == 1 && $vSlipNo =='' && $creditcard != ''){
		$AmountDiffer = 2;
		 echo "[BRK]";
		 echo $AmountDiffer;
		 exit;
	}
	$queryDate = "select date_format(sale_date,'%Y-%m-%d') from temp_retail where sale_id = $SRetId ";
	$resDate = mysql_query($queryDate,$connection);
	$rowDate = mysql_fetch_row($resDate);
	$retailDate = $rowDate[0];
	
	$cashamnt2 = ConvertCurrency($base2, $base1, $retailDate, $cashamnt2, $connection); 
	$differamnt2 = ConvertCurrency($base2, $base1, $retailDate, $differamnt2, $connection);
	
	if ($cashregcurr == $base2)
	{
	$dueamnt =  ConvertCurrency($base2, $base1, $retailDate, $dueamnt, $connection);
	}

	if($checkCur != '')
	$checkamnt = ConvertCurrency($checkCur, $base1, $retailDate, $checkamnt, $connection);
	
	if($CreditCur != '')
	$creditamnt = ConvertCurrency($CreditCur, $base1, $retailDate, $creditamnt, $connection);
	
	$totalAmount = $creditamnt + $cashamnt1 + $cashamnt2 + $checkamnt + $RetCouponAmt + $tipsamnt + $RetCustomerAmount - $differamnt1 - $differamnt2;//+ $tipsamnt
	
	if ( (abs($dueamnt - $totalAmount) > $Setup_TipsMaxAmount) || ( $RetCouponAmt == 0 && $cashamnt1 == 0 && $cashamnt2 == 0 &&  $checkamnt == 0 && $RetCustomerAmount == 0 && abs($dueamnt-$creditamnt)> $Setup_TipsMaxAmount))
		$AmountDiffer = 1;
	else $AmountDiffer = 0;
	
	 echo "[BRK]";
	 echo $AmountDiffer;
	 
	 
	 //
	// echo "due ammount: $dueamnt total ammount $creditamnt ";
	 //
	exit;
}

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

	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];
	
	
	$queryRef  = "Select ifnull(sale_reference,'') from retail  WHERE Sale_id = '".$SRetId."'";
	$refRef    = selectData($connection, $queryRef);
	$vsaHasRef = $refRef[0];
	
	if($vsaHasRef == ''){
	$sub_query1 = " UPDATE temp_retaildt SET ".
				  " Sale_Date = '".insertMySQLDate($txtDate)."' ".
			      " WHERE Sale_id = '".$SRetId."' ";
			
			   
	if (!updateData($connection, $sub_query1, true))		 
		$message  = mysql_error(); }
				  
	
	$vTotalQty        = 0;
	$vTotalQtyReturn  = 0;

	$sub_query2 = " Select Sum(if(Journal_Type = 'RI', SaleDt_Quantity, 0)) As TotalQty,  Sum(if(Journal_Type = 'RR', SaleDt_Quantity, 0)) As TotalQtyReturn ".
				  " From Temp_RetailDt ".
				  " Where Sale_ID = '".$SRetId."'";
	//echo $sub_query2;
	$sub_result2  = selectData($connection, $sub_query2);
	$vTotalQty        = $sub_result2[0];
	$vTotalQtyReturn  = $sub_result2[1];
	
	if (empty($vTotalQty)) $vTotalQty = 0;
	if (empty($vTotalQtyReturn)) $vTotalQtyReturn = 0;
				
	 
			 		 
	fbegin();
	
	$query = " UPDATE temp_retail SET ";
	if($vsaHasRef == ''){ $query .= " Sale_Date = '".insertMySQLDate($txtDate)."', ";}
	$query .= " Sale_TotalQuantity = $vTotalQty, Sale_TotalQuantityRet = $vTotalQtyReturn ".
			 " WHERE Sale_id = '".$SRetId."' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
	 
		$result=mysql_query($query,$connection);
	
	
	
	if ($result){
					
		if ($mainmode == 'insert') $SMode = 'I';
		if ($mainmode == 'edit') $SMode = 'U';
			
			
				
		$query = "SELECT CopyData_TempRetail('".$SMode."', ".$SRetId.", '".$_SESSION['useraccount']."') FROM Dual ";
		$result = selectData($connection, $query);
		$result = $result[0];
		//echo $query; exit;
		//echo 'error='.$result; exit;
		if ($result != 0){
			fcommit();
					
			$query   = " SELECT Sale_Reference FROM Retail WHERE Sale_id = '".$SRetId."' ";
			$result  = selectData($connection, $query);
			$vSaRef  = $result[0];
					
			if ($vSaRef == '') {
				fbegin();
				$vSaRef = get_nextsequence('retail_reference','',$connection);	
				fcommit();
						
				$query = " UPDATE retail SET ".
						 " Sale_Reference = $vSaRef ".
						 " WHERE Sale_id = '".$SRetId."' ";
						
				if (!updateData($connection, $query, true)) 
					$message  = mysql_error();
					
			}	
				 
			//echo $message; exit; 
		} else{
			//$message  = mysql_error(); 
			$message  = 'Error In CopyData_TempRetail Function'; 
			frollback();
		}
			
			
	} else{
		$message  = mysql_error(); 
		frollback();
	}
		
}
else if($mode=='updateguests'){
$RetailId	 = $_GET['RetailId']; if ($RetailId == ""){$RetailId = $_POST["RetailId"];}
$TableGuests = $_GET['TableGuests']; if ($TableGuests == ""){$TableGuests = $_POST["TableGuests"];}

$query = "update temp_Retail set sale_numberofguests = $TableGuests ".
				" Where temp_Retail.Sale_ID = '".$RetailId."' ";
			   
$resultdt=mysql_query($query,$connection) or die(mysql_error());	

}
else if($mode=='printswap'){

	$RetailId 		= $_GET["RetailId"]; if ($RetailId == ""){$RetailId = $_POST["RetailId"];}   
	$ModuleRestaurantDelivery 		= $_GET["ModuleRestaurantDelivery"]; if ($ModuleRestaurantDelivery == ""){$ModuleRestaurantDelivery = $_POST["ModuleRestaurantDelivery"];}   
	$CashRegister_Printer 		= $_GET["CashRegister_Printer"]; if ($CashRegister_Printer == ""){$CashRegister_Printer = $_POST["CashRegister_Printer"];}   
	$CashRegister_SlipPrinter 		= $_GET["CashRegister_SlipPrinter"]; if ($CashRegister_SlipPrinter == ""){$CashRegister_SlipPrinter = $_POST["CashRegister_SlipPrinter"];}   

	//maroun 01.08.2014
	if($Module_RestaurantDelivery==1) {
		
		$querydt = " Select 1 ".
				   " From Temp_RetailDt as RetailDt ".
				   " Left Join Items on RetailDt.Item_code = Items.Item_code ".
				   " left join ".$_SESSION['dbLabel'].".printersubgroup on items.subgroup_code=printersubgroup.p_subgroup ".
				   " Where RetailDt.Sale_ID = '".$RetailId."' ".
				   " and saledt_printed = 0 ".
				   " and p_category <> '' ".
				   " Order By RetailDt.SaleDt_id  ";
		//echo $querydt;
		$result=mysql_query($querydt,$connection) or die(mysql_error());	
		$row=mysql_fetch_row($result);
		$ApplyClass = $row[0];
		if($ApplyClass=='')
			$ApplyClass = 0;
			
		if($ApplyClass==1)
			$querydt = " Select distinct p_category,p_name ".
				   " From Temp_RetailDt as RetailDt ".
				   " Left Join Items on RetailDt.Item_code = Items.Item_code ".
				   " left join ".$_SESSION['dbLabel'].".printersubgroup on items.subgroup_code=printersubgroup.p_subgroup ".
				   " Where RetailDt.Sale_ID = '".$RetailId."' ".
				   " and saledt_printed = 0 ".
				   " and p_name <> '' ".
				   " Order By RetailDt.SaleDt_id  ";
				   
			else $querydt = " Select distinct p_name ".
				   " From Temp_RetailDt as RetailDt ".
				   " Left Join Items on RetailDt.Item_code = Items.Item_code ".
				   " left join ".$_SESSION['dbLabel'].".printersubgroup on items.subgroup_code=printersubgroup.p_subgroup ".
				   " Where RetailDt.Sale_ID = '".$RetailId."' ".
				   " and saledt_printed = 0 ".
				   " Order By RetailDt.SaleDt_id  ";
		//echo $querydt;
		
		$result=mysql_query($querydt,$connection) or die(mysql_error());
		$i=0;
		
		while ($row=mysql_fetch_row($result)) {
		
		
		
		if ($CashRegister_SlipPrinter == 1) 
			{
				$ReportName = 'Form_RetailSlipSubGroup.php';
			}	
		else 
			exit;
		
		//if($i==0)
			//echo ' <script type="text/javascript" language="javascript"> ';
	 
		if ($CashRegister_Printer == 1) 
			{	
			//echo $Printername;
			$Classname = '';
			$Printername = '';
			
			if($ApplyClass==1){
				$Classname = $row[0];
				$Printername = $row[1];
				}
			else
				$Printername = $row[0];

			 
			
			Print_RetailSlipSubGroup($ReportName,$RetailId,'',$Printername,$DecimalBase,$Setup_VatPercentage,$connection,$Classname,$ApplyClass,$tablename,$guestnumber,$Module_GroupHoldFire);
			//echo " window.open(str, 'Form_RetailSlipSubGroup$i', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=500,top=100'); ";
			
			}
		
		$i+=1;
		}
	$qq = "update temp_RetailDt,items set saledt_printed = 1 ".
				" Where temp_RetailDt.Sale_ID = '".$RetailId."' ".
			   " and ifnull(saledt_printed,0) = 0 ".
			   " and items.item_code = temp_RetailDt.item_code";
	$resultdt=mysql_query($qq,$connection) or die(mysql_error());	
		
	}	

}

else if ($mode == "holdinvoice" && $SRetId != "" && $_GET['txtHoldRemark'] != ''){
	
	fbegin();
	$query = " UPDATE temp_retail SET Sale_Remark = '".$_GET['txtHoldRemark']."' Where Sale_ID = ".$SRetId;
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
			
	if ( $result ){ 
		$ErrorExists = 0;
		fcommit();
	}else{
		$ErrorExists = 1;
		$message  = mysql_error($connection); 
		frollback();
	}
}

else if (($mode == "modifiernote" || $mode == "modifiernote2") && $SRetId != "" && $SRetDtId != ""){
	
	fbegin();

	$query = " UPDATE temp_retaildt SET ". 
			 //" SalesDt_Remark = if(SalesDt_Remark != '', concat(SalesDt_Remark,'\r','".$_GET['txtModifierNote']."'), '".$_GET['txtModifierNote']."') ".
			 " SalesDt_Remark = '".urldecode($_GET['txtModifierNote'])."' ".
			 " WHERE SaleDt_ID = $SRetDtId";	
			 
	
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
			
	if ( $result ){ 
		$ErrorExists = 0;
		fcommit();
	}else{
		$ErrorExists = 1;
		$message  = mysql_error($connection); 
		frollback();
	}
}

else if ($mode == "getmodifiernote" && $SRetId != "" && $SRetDtId != ""){

	$sub_query = " Select SalesDt_Remark From Temp_RetailDt Where Sale_ID = '".$SRetId."' And SaleDt_ID = '".$SRetDtId."' ";
	$sub_result = selectData($connection, $sub_query);
	$ModifierNote = $sub_result[0];
		
	$row_array['ModifierNote'] = $ModifierNote;
}

else if ($mode == "updateuseraccess" && $SRetId != ""){
	
	$sub_query = " Select ifnull(Sale_BelongsToGroup,0) From Temp_Retail Where Sale_ID = '".$SRetId."'";
	$sub_result = selectData($connection, $sub_query);
	$SaleBelongsToGroup = $sub_result[0];
	
	$AccessDenied = 0;
	if ($SaleBelongsToGroup >= $FI_BelongsToGrp) {
		fbegin();
		$query = " UPDATE temp_retail SET ". 
				 " Sale_BelongsToGroup = if(ifnull(Sale_BelongsToGroup,0)>0, ifnull(Sale_BelongsToGroup,0) - 1, ifnull(Sale_BelongsToGroup,0)) ".
				 " WHERE Sale_ID = $SRetId";	
		
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
				
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	} else {
		$AccessDenied = 1;
	}

	$row_array['AccessDenied'] = $AccessDenied;
}

//($mode == "fire" && $SRetId != "" && $_GET['SelectedRec']!= "")
else if ((($mode == "gift" || $mode == "void" || $mode == "waste" || $mode == "hold" || $mode == "fire") && $SRetId != "" && ($SRetDtId != "" or $Module_GroupHoldFire == 1) ) || 
		 (($mainmode == "voidinvoice" || $mainmode == "wasteinvoice") && $SRetId != "")){
		 
	$ErrorExists = 0;
	$message = "";
	
	$vRetQty = 0;
	$vRetDtTotal = 0;
	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetVat = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	
	$vRetDtPriceTTC      = 0;
	$vRetDtPriceTTCBase1 = 0;
	$vRetDtPriceTTCBase2 = 0;					
	$vRetDtPrice         = 0;
	$vRetDtPriceBase1    = 0;
	$vRetDtPriceBase2    = 0;
	$vRetDtDiscAmt       = 0;
	$vRetDtDiscAmtBase1  = 0;
	$vRetDtDiscAmtBase2  = 0;
		
				
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	if ($mode == "gift") {
		fbegin();
		/*$query = " UPDATE temp_retaildt SET  ".
				 " SaleDt_Price = 0, SaleDt_PriceBase1 = 0, SaleDt_PriceBase2 = 0, ".
				 " SaleDt_PriceTTC = 0, SaleDt_PriceTTCBase1 = 0, SaleDt_PriceTTCBase2 = 0, ".
				 " SaleDt_PriceVat = 0, SaleDt_DiscountPer = 0 ".
				 " Where SaleDt_ID = ".$SRetDtId;*/
		$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 1,SaleDt_DiscountPer = 100 Where SaleDt_ID = ".$SRetDtId;
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	}	
	else if ($mode == "void") {
		fbegin();
		$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 2, SaleDt_ItemStatusRemark = '".$txtStatusRemark."',Saledt_Printed = 0  ".
				 " Where SaleDt_ID = ".$SRetDtId;
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	else if ($mode == "waste") {
		fbegin();
		$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 3, SaleDt_ItemStatusRemark = 'Waste' ".
				 " Where SaleDt_ID = ".$SRetDtId;
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	else if ($mode == "hold") {
		$sub_query  = "SELECT ifNull(SaleDt_ItemStatus,0) From temp_retaildt WHERE SaleDt_ID = '".$SRetDtId."'";
		$sub_result = selectData($connection, $sub_query);
		$IsHoldItem = $sub_result[0];
			
		fbegin();
		if ($IsHoldItem != 4) {
			$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 4, SaleDt_ItemStatusRemark = date_format(now(), '%h:%i %p') Where SaleDt_ID = ".$SRetDtId;
		} else {
			$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 0, SaleDt_ItemStatusRemark = Null Where SaleDt_ID = ".$SRetDtId;
		}
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
			
			$sub_query = "SELECT count(*) From temp_retaildt WHERE ifNull(SaleDt_ItemStatus,0) = 4 And Sale_ID = '".$SRetId."'";
			$sub_result = selectData($connection, $sub_query);
			$HoldItems = $sub_result[0];
			
			$row_array['HoldItems'] = $HoldItems;
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	else if ($mode == "fire") {
		fbegin();
		
		if($Module_GroupHoldFire == 1)
		$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 5, SaleDt_ItemStatusRemark = null,saledt_printed = 0 ".
				 " Where Sale_ID = '".$SRetId."' and SaleDt_ItemStatus = 4 ";
		else
		$query = " UPDATE temp_retaildt SET SaleDt_ItemStatus = 5, SaleDt_ItemStatusRemark = null,saledt_printed = 0 ".
				 " Where SaleDt_ID = ".$SRetDtId;
		//echo $query."<br>";exit;				
	
		$result=mysql_query($query,$connection) or die(mysql_error());
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
			
			$sub_query = "SELECT count(*) From temp_retaildt WHERE ifNull(SaleDt_ItemStatus,0) = 4 And Sale_ID = '".$SRetId."'";
			$sub_result = selectData($connection, $sub_query);
			$HoldItems = $sub_result[0];
			
			$row_array['HoldItems'] = $HoldItems;
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	else if ($mainmode == "voidinvoice") {
		fbegin();
		$query = " UPDATE retaildt SET SaleDt_ItemStatus = 2, SaleDt_ItemStatusRemark = 'Void Invoice' ".
				 " Where Sale_ID = ".$SRetId;
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
			
			$query = " UPDATE retail SET Sale_Status = 2 Where Sale_ID = ".$SRetId;
			$result=mysql_query($query,$connection);
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
					$query = " UPDATE retail SET ".
						 " Sale_Taxable = 0, Sale_TaxableBase1 = 0, Sale_TaxableBase2 = 0, ".
						 " Sale_NoneTaxable = 0, Sale_NoneTaxableBase1 = 0, Sale_NoneTaxableBase2 = 0, ".
						 " Sale_DiscountPer = 0, Sale_DiscountAmount = 0, Sale_DiscountBase1 =0, Sale_DiscountBase2 = 0, ".
						 " Sale_VAT = 0, Sale_VATBase1 = 0, Sale_VATBase2 = 0, ".
						 " Sale_Total = 0, Sale_TotalBase1 = 0, Sale_TotalBase2 = 0, ".
						 " Sale_NetTotal = 0, Sale_NetTotalBase1 = 0, Sale_NetTotalBase2 = 0, ".
						 " Sale_Tax1 = 0, Sale_Tax1Base1 = 0, Sale_Tax1Base2 = 0,  ".
						 " Sale_Tax2 = 0, Sale_Tax2Base1 = 0, Sale_Tax2Base2 = 0,  ".
						 " Sale_Tax3 = 0, Sale_Tax3Base1 = 0, Sale_Tax3Base2 = 0,  ".
						 " Sale_Tax4 = 0, Sale_Tax4Base1 = 0, Sale_Tax4Base2 = 0,  ".
						 " Sale_Tax5 = 0, Sale_Tax5Base1 = 0, Sale_Tax5Base2 = 0,  ".
						 " Sales_CashInBase1 = 0, Sales_CashOutBase1 = 0, Sales_CashInBase2 = 0 , Sales_CashOutBase2 = 0  ".
						 " WHERE Sale_ID = ".$SRetId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
				 
				$result=mysql_query($query,$connection);
	}
	else if ($mainmode == "wasteinvoice") {
		fbegin();
		$query = " UPDATE retaildt SET SaleDt_ItemStatus = 3, SaleDt_ItemStatusRemark = 'Waste Invoice' ".
				 " Where Sale_ID = ".$SRetId;
		$result=mysql_query($query,$connection);
			
		if ( $result ){ 
			$ErrorExists = 0;
			fcommit();
			
			$query = " UPDATE retail SET Sale_Status = 3 Where Sale_ID = ".$SRetId;
			$result=mysql_query($query,$connection);
		}else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}

	if ( $ErrorExists == 0 && $mode != "hold" && $mode != "fire" && $mainmode != "voidinvoice" && $mainmode != "wasteinvoice"){

		$vRetDiscountAmt = 0;
		$vRetTotal = 0;
		$vRetDtTotal = 0;
					
		//Distribute The Total Discount On Detail Table
		$sub_query1 = " Select Currency_code, Date_Format(Sale_Date,'%d/%m/%Y') As Sale_Date, ifNull(Sale_DiscountPer,0), ifNull(Sale_DiscountAmount,0) As Sale_DiscountAmount ".
					  " From Temp_Retail ".
					  " Where Sale_ID = '".$SRetId."' ";
		$sub_result1 = selectData($connection, $sub_query1);
		$vRetCurr        = $sub_result1[0];
		$vRetDate		 = $sub_result1[1];
		$vRetDiscount    = $sub_result1[2];
		$vRetDiscountAmt = $sub_result1[3];	
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
		$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 ($vRetDiscountAmt > 0) {
						
			$sub_query2 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt ".
						  " Where Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
			$sub_result2 = selectData($connection, $sub_query2);
			$vRetTotal   = $sub_result2[0];	
							
			$sub_query3 = " Select SaleDt_ID,  ".
						  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
						  " From Temp_RetailDt As RetailDt  ".
						  " Where RetailDt.Sale_ID = '".$SRetId."' ".
						  " And ifNull(Price_offer,0) = 0 ".
						  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
										  
									   
			//echo $sub_query3; 
			$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
			while($sub_rows3=mysql_fetch_array($sub_result3)){
							
				$vRetDtId      = $sub_rows3[0];
				$vRetDtTotal   = $sub_rows3[1];
								
								
				$vRetDtDiscAmt	    = 0;
				$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
				$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
				$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
								
						
				$sub_query4 =  " UPDATE temp_retaildt SET ".
							   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
							   " Where SaleDt_ID = '".$vRetDtId."' ";
											   
											 
				//echo $sub_query4; exit;
				if (!updateData($connection, $sub_query4, true))
					$error  = mysql_error(); 
								

			}
		}
			
		$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_RetailDt ".
				 " Where Sale_ID = ".$SRetId.
				 " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
										 
		//echo $query;
		$result=mysql_query($query,$connection) or die(mysql_error());
		while($rows=mysql_fetch_array($result)){

			$vRetDtTotal  = $rows[1];
			$vItemVat     = $rows[2];
			$vRetQty      = $vRetQty + $rows[3];
				
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ((insertDate($vRetDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
				$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
				
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $rows[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
				if ($vItemVat > 0 && $rows[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
				if ($vItemVat > 0 && $rows[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
				if ($vItemVat > 0 && $rows[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
				if ($vItemVat > 0 && $rows[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
			}
						
		}			
					
					
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
		// Calculation of Discount Amount	
		if ($vRetDiscount > 0)
			$vRetDiscountAmt = (($vRetGrossTotal * $vRetDiscount) / 100);
			
		if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
					
		$vRetNetTotal         = $vRetGrossTotal + $vRetVat - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVat*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVat*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_VAT = $vRetVat, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2  ".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
							 
					 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
				
		if ($result){
			fcommit();
		}else{
			$message  = mysql_error(); 
			frollback();
		}
		
	} // End If No Error Exists 		

}



else if(($mode=='savecashreg' && $txtCashRegisterName != '') || $mode=='savesetup'){

	$Currency_Code 			= $_POST["Currency_Code"]; 				if ($Currency_Code == ""){		$Currency_Code 		= $_GET["Currency_Code"];} 
	$CostCenter_Code 		= $_POST["CostCenter_Code"]; 			if ($CostCenter_Code == ""){	$CostCenter_Code 	= $_GET["CostCenter_Code"];} 
	$Project_Code 			= $_POST["Project_Code"]; 				if ($Project_Code == ""){		$Project_Code 		= $_GET["Project_Code"];} 
	$Warehouse_Code 		= $_POST["Warehouse_Code"]; 			if ($Warehouse_Code == ""){		$Warehouse_Code 	= $_GET["Warehouse_Code"];} 
	$Client_Account 		= $_POST["Client_Account"]; 			if ($Client_Account == ""){		$Client_Account 	= $_GET["Client_Account"];} 
	$Sales_Account	 		= $_POST["Sales_Account"]; 				if ($Sales_Account == ""){		$Sales_Account 		= $_GET["Sales_Account"];} 
	$Cash_Account 			= $_POST["Cash_Account"]; 				if ($Cash_Account == ""){		$Cash_Account	 	= $_GET["Cash_Account"];} 
	$Check_Account 			= $_POST["Check_Account"]; 				if ($Check_Account == ""){		$Check_Account		= $_GET["Check_Account"];} 
	$Tips_Account 			= $_POST["Tips_Account"]; 				if ($Tips_Account == ""){		$Tips_Account 		= $_GET["Tips_Account"];} 
	$Coupon_Account 		= $_POST["Coupon_Account"]; 			if ($Coupon_Account == ""){		$Coupon_Account 	= $_GET["Coupon_Account"];} 
	
	$chkRestaurant 			= $_POST["chkRestaurant"]; 				if ($chkRestaurant == ""){			$chkRestaurant 		= 0;} 
	$chkTables 				= $_POST["chkTables"]; 					if ($chkTables == ""){				$chkTables 			= 0;} 
	$chkFastItems 			= $_POST["chkFastItems"]; 				if ($chkFastItems == ""){			$chkFastItems 		= 0;} 
	$chkStandard 			= $_POST["chkStandard"]; 				if ($chkStandard == ""){			$chkStandard 		= 0;} 
	$chkBarcode 			= $_POST["chkBarcode"]; 				if ($chkBarcode == ""){				$chkBarcode 		= 0;} 
	$chkShowBarcode 		= $_POST["chkShowBarcode"]; 			if ($chkShowBarcode == ""){			$chkShowBarcode	 	= 0;} 
	$chkShowItemcode 		= $_POST["chkShowItemcode"];		 	if ($chkShowItemcode == ""){		$chkShowItemcode 	= 0;} 
	$chkShowDiscount 		= $_POST["chkShowDiscount"]; 			if ($chkShowDiscount == ""){		$chkShowDiscount 	= 0;} 
	$chkShowItemImage 		= $_POST["chkShowItemImage"]; 			if ($chkShowItemImage == ""){		$chkShowItemImage 	= 0;} 
	$chkShowItemLocation	= $_POST["chkShowItemLocation"];		if ($chkShowItemLocation == ""){	$chkShowItemLocation= 0;} 
	$chkshow_totalQty		= $_POST["chkshow_totalQty"];			if ($chkshow_totalQty == ""){		$chkshow_totalQty= 0;	} 
	$chkPrinter 			= $_POST["chkPrinter"]; 				if ($chkPrinter == ""){				$chkPrinter 		= 0;} 
	$chkPrinterbtn 			= $_POST["chkPrinterbtn"]; 				if ($chkPrinterbtn == ""){			$chkPrinterbtn 		= 0;} 
	$chkPrintonholdbtn 		= $_POST["chkPrintonholdbtn"]; 			if ($chkPrintonholdbtn == ""){		$chkPrintonholdbtn 	= 0;} 
	$chkSlip 				= $_POST["chkSlip"]; 					if ($chkSlip == ""){				$chkSlip 			= 0;} 
	$chkSlipKitchen 		= $_POST["chkSlipKitchen"]; 			if ($chkSlipKitchen == ""){			$chkSlipKitchen 	= 0;} 
	$CashRegister_SlipCopy  = $_POST["CashRegister_SlipCopy"]; 		if ($CashRegister_SlipCopy == ""){	$CashRegister_SlipCopy = 0;} 
	
	$chkDispLed 					= $_POST["chkDispLed"]; 				if ($chkDispLed == ""){						$chkDispLed				 	= 0;} 
	$chkDrawer 						= $_POST["chkDrawer"]; 					if ($chkDrawer == ""){						$chkDrawer 					= 0;} 
	$CashRegister_DispCOM 			= $_POST["CashRegister_DispCOM"]; 		if ($CashRegister_DispCOM == ""){			$CashRegister_DispCOM 		= $_GET["CashRegister_DispCOM"];} 
	$CashRegister_LedDescLength 	= $_POST["CashRegister_LedDescLength"]; if ($CashRegister_LedDescLength == ""){		$CashRegister_LedDescLength = $_GET["CashRegister_LedDescLength"];} 
	$CashReg_DispLedMsg 			= $_POST["CashReg_DispLedMsg"]; 		if ($CashReg_DispLedMsg == ""){				$CashReg_DispLedMsg 		= $_GET["CashReg_DispLedMsg"];} 
	$CashRegister_DrawerCOM 		= $_POST["CashRegister_DrawerCOM"]; 	if ($CashRegister_DrawerCOM == ""){			$CashRegister_DrawerCOM 	= $_GET["CashRegister_DrawerCOM"];} 
	$CashRegister_DrawerPrinter 	= $_POST["CashRegister_DrawerPrinter"];	if ($CashRegister_DrawerPrinter == ""){		$CashRegister_DrawerPrinter = $_GET["CashRegister_DrawerPrinter"];} 
	
	$chkScaleWeight 				= $_POST["chkScaleWeight"]; 			if ($chkScaleWeight == ""){					$chkScaleWeight 		= 0;} 
	$chkScalePrice 					= $_POST["chkScalePrice"]; 				if ($chkScalePrice == ""){					$chkScalePrice 			= 0;} 
	$CashReg_StartBarcode 			= $_POST["CashReg_StartBarcode"]; 		if ($CashReg_StartBarcode == ""){			$CashReg_StartBarcode 	= $_GET["CashReg_StartBarcode"];} 
	$CashReg_EndBarcode 			= $_POST["CashReg_EndBarcode"];		 	if ($CashReg_EndBarcode == ""){				$CashReg_EndBarcode 	= $_GET["CashReg_EndBarcode"];} 
	$CashReg_StartQty 				= $_POST["CashReg_StartQty"]; 			if ($CashReg_StartQty == ""){				$CashReg_StartQty 		= $_GET["CashReg_StartQty"];} 
	$CashReg_EndQty 				= $_POST["CashReg_EndQty"]; 			if ($CashReg_EndQty == ""){					$CashReg_EndQty 		= $_GET["CashReg_EndQty"];} 
	$CashReg_StartPrice 			= $_POST["CashReg_StartPrice"];			if ($CashReg_StartPrice == ""){				$CashReg_StartPrice 	= $_GET["CashReg_StartPrice"];} 
	$CashReg_EndPrice 				= $_POST["CashReg_EndPrice"]; 			if ($CashReg_EndPrice == ""){				$CashReg_EndPrice 		= $_GET["CashReg_EndPrice"];} 
	
	$chkCredit 						= $_POST["chkCredit"]; 					if ($chkCredit == ""){						$chkCredit 			= 0;} 
	$chkCheck 						= $_POST["chkCheck"]; 					if ($chkCheck == ""){						$chkCheck 			= 0;} 
	$chkShowBase2 					= $_POST["chkShowBase2"]; 				if ($chkShowBase2 == ""){					$chkShowBase2 		= 0;}
	$chkAutoPost 					= $_POST["chkAutoPost"]; 				if ($chkAutoPost == ""){					$chkAutoPost 		= 0;} 
	$chkPostOneToOne 				= $_POST["chkPostOneToOne"]; 			if ($chkPostOneToOne == ""){				$chkPostOneToOne 	= 0;} 
	$chkPostByCashReg 				= $_POST["chkPostByCashReg"]; 			if ($chkPostByCashReg == ""){				$chkPostByCashReg 	= 0;} 
	$chkDiscount 					= $_POST["chkDiscount"]; 				if ($chkDiscount == ""){					$chkDiscount 		= 0;} 
	$chkSerialNo 					= $_POST["chkSerialNo"]; 				if ($chkSerialNo == ""){					$chkSerialNo 		= 0;} 
	$chkRestSerial 					= $_POST["chkRestSerial"]; 				if ($chkRestSerial == ""){					$chkRestSerial 		= 0;} 
	$chkTTC 						= $_POST["chkTTC"]; 					if ($chkTTC == ""){							$chkTTC 			= 0;} 
	$chkVendor 						= $_POST["chkVendor"]; 					if ($chkVendor == ""){						$chkVendor 			= 0;} 
	$chkForceVendor 				= $_POST["chkForceVendor"]; 			if ($chkForceVendor == ""){					$chkForceVendor 	= 0;} 
	$chkTaxNonTax 					= $_POST["chkTaxNonTax"]; 				if ($chkTaxNonTax == ""){					$chkTaxNonTax 		= 0;} 
	$chkShowSlip				 	= $_POST["chkShowSlip"]; 				if ($chkShowSlip == ""){					$chkShowSlip 		= 0;} 
	$chkAutoItemsList 				= $_POST["chkAutoItemsList"]; 			if ($chkAutoItemsList == ""){				$chkAutoItemsList 	= 0;} 
	$chkItemSeperate 				= $_POST["chkItemSeperate"]; 			if ($chkItemSeperate == ""){				$chkItemSeperate 	= 0;} 
	$chkItemQtyInCode 				= $_POST["chkItemQtyInCode"]; 			if ($chkItemQtyInCode == ""){				$chkItemQtyInCode 	= 0;} 
	$chkAutoClosePrint 				= $_POST["chkAutoClosePrint"]; 			if ($chkAutoClosePrint == ""){				$chkAutoClosePrint 	= 0;} 
	
	
	$CashReg_RoundDivisor 			= $_POST["CashReg_RoundDivisor"]; 		if ($CashReg_RoundDivisor == ""){			$CashReg_RoundDivisor 		= $_GET["CashReg_RoundDivisor"];} 
	$Module_PriceOffer 				= $_POST["Module_PriceOffer"]; 			if ($Module_PriceOffer == ""){				$Module_PriceOffer 			= $_GET["Module_PriceOffer"];} 
	$CashReg_ColorTheme 			= $_POST["CashReg_ColorTheme"]; 		if ($CashReg_ColorTheme == ""){				$CashReg_ColorTheme 		= $_GET["CashReg_ColorTheme"];} 
	$CashReg_BgColorOffer 			= $_POST["CashReg_BgColorOffer"];	 	if ($CashReg_BgColorOffer == ""){			$CashReg_BgColorOffer 		= $_GET["CashReg_BgColorOffer"];} 
	$CashReg_BgColorQty 			= $_POST["CashReg_BgColorQty"]; 		if ($CashReg_BgColorQty == ""){				$CashReg_BgColorQty 		= $_GET["CashReg_BgColorQty"];} 
	$CashReg_BgColorOrderQty 		= $_POST["CashReg_BgColorOrderQty"]; 	if ($CashReg_BgColorOrderQty == ""){		$CashReg_BgColorOrderQty 	= $_GET["CashReg_BgColorOrderQty"];} 
	$chkApplyColorOffer 			= $_POST["chkApplyColorOffer"]; 		if ($chkApplyColorOffer == ""){				$chkApplyColorOffer 		= 0;} 
	$chkApplyColorQty 				= $_POST["chkApplyColorQty"]; 			if ($chkApplyColorQty == ""){				$chkApplyColorQty 			= 0;} 
	$chkApplyColorOrderQty 			= $_POST["chkApplyColorOrderQty"]; 		if ($chkApplyColorOrderQty == ""){			$chkApplyColorOrderQty 		= 0;} 
	$chkApplyColorZeroPrice 		= $_POST["chkApplyColorZeroPrice"]; 	if ($chkApplyColorZeroPrice == ""){			$chkApplyColorZeroPrice 	= 0;} 
	$chkApplyColorZeroQty 			= $_POST["chkApplyColorZeroQty"]; 		if ($chkApplyColorZeroQty == ""){			$chkApplyColorZeroQty 		= 0;} 
	$chkApplyColorHasDiscount 		= $_POST["chkApplyColorHasDiscount"]; 	if ($chkApplyColorHasDiscount == ""){		$chkApplyColorHasDiscount 	= 0;} 
	
	
	$Base1 							= $_POST["Base1"]; 						if ($Base1 == ""){							$Base1 						= $_GET["Base1"];} 
	$Base2 							= $_POST["Base2"]; 						if ($Base2 == ""){							$Base2 						= $_GET["Base2"];} 
	$Setup_VatNo 					= $_POST["Setup_VatNo"]; 				if ($Setup_VatNo == ""){					$Setup_VatNo 				= $_GET["Setup_VatNo"];} 
	$Setup_VatStartDate 			= $_POST["Setup_VatStartDate"];		 	if ($Setup_VatStartDate == ""){				$Setup_VatStartDate 		= $_GET["Setup_VatStartDate"];} 
	$Setup_VatPercentage		 	= $_POST["Setup_VatPercentage"]; 		if ($Setup_VatPercentage == ""){			$Setup_VatPercentage 		= $_GET["Setup_VatPercentage"];} 
	$Company_Name 					= $_POST["Company_Name"]; 				if ($Company_Name == ""){					$Company_Name 				= $_GET["Company_Name"];} 
	$Company_Memo 					= $_POST["Company_Memo"]; 				if ($Company_Memo == ""){					$Company_Memo 				= $_GET["Company_Memo"];} 
	
	$chkcashregister_logout		 	= $_POST["chkcashregister_logout"]; 	if ($chkcashregister_logout == ""){			$chkcashregister_logout 	= 0;} 
	$cashregister_retailtype 		= $_POST["cashregister_retailtype"]; 	if ($cashregister_retailtype == ""){		$cashregister_retailtype 	= 0;} 
	$editpriceup 					= $_POST["editpriceup"]; 				if ($editpriceup == ""){					$editpriceup 				= 0;} 
	$editpricedwn 					= $_POST["editpricedwn"]; 				if ($editpricedwn == ""){					$editpricedwn 				= 0;} 
	$editpricedwn 					= $_POST["editpricedwn"]; 				if ($editpricedwn == ""){					$editpricedwn 				= 0;} 
	
	$project_no					 	= $_POST["project_no"]; 
	if ($project_no == "") $project_no = "NULL";
	else 				$project_no = "'".$project_no."'";
	
	$costcent_no 					= $_POST["costcent_no"]; 
	if ($costcent_no == "") $costcent_no = "NULL";
	else $costcent_no = "'".$costcent_no."'";
	
	$RestrictZeroPrice  = $_POST["chkRestrictPrice"]; 	if ($chkRestrictPrice == ""){	$chkRestrictPrice 	= $_GET["chkRestrictPrice"];} 
	$chkRegService 		= $_POST["chkRegService"]; 		if ($chkRegService == ""){		$chkRegService 		= $_GET["chkRegService"];} 
	$servicePercentage 	= $_POST["servicePercentage"]; 	if ($servicePercentage == ""){	$servicePercentage 	= $_GET["servicePercentage"];} 
	$serviceaccount 	= $_POST["serviceaccount"]; 	if ($serviceaccount == ""){		$serviceaccount 	= $_GET["serviceaccount"];} 
	
	$chkRegTax 				= $_POST["chkRegTax"]; 				if ($chkRegTax == ""){				$chkRegTax 				= $_GET["chkRegTax"];} 
	$ShowTaxChkbox 			= $_POST["ShowTaxChkbox"]; 			if ($ShowTaxChkbox == ""){			$ShowTaxChkbox 			= $_GET["ShowTaxChkbox"];} 
	$TaxConspPercentage 	= $_POST["TaxConspPercentage"]; 	if ($TaxConspPercentage == ""){		$TaxConspPercentage 	= $_GET["TaxConspPercentage"];} 
	$chkRedeemPoints 		= $_POST["chkRedeemPoints"]; 		if ($chkRedeemPoints == ""){		$chkRedeemPoints 		= $_GET["chkRedeemPoints"];}
	$ShowCustomerInRetail 	= $_POST["ShowCustomerInRetail"]; 	if ($ShowCustomerInRetail == ""){	$ShowCustomerInRetail 	= $_GET["ShowCustomerInRetail"];}
	$RedeemPoints_Account 	= $_POST["RedeemPoints_Account"]; 	if ($RedeemPoints_Account == ""){	$RedeemPoints_Account 	= $_GET["RedeemPoints_Account"];}
	$chkRestrictSlipNoOnPay 	= $_POST["chkRestrictSlipNoOnPay"]; 	if ($chkRestrictSlipNoOnPay == ""){	$chkRestrictSlipNoOnPay 	= $_GET["RedeemPoints_Account"];}
	
	if ($RestrictZeroPrice == '') 	$RestrictZeroPrice = 0;
	if ($Retaildt_height == '') 	$Retaildt_height = 0;
	if ($shortcutgrid_height == '') $shortcutgrid_height = 0;
	if ($shortcutgrid_width == '') 	$shortcutgrid_width = 0;
	if ($chkRedeemPoints == '') 	$chkRedeemPoints = 0;
	
	if ($chkRegService == '') 		$chkRegService = 0; 
	if ($chkRestrictSlipNoOnPay == '') 		$chkRestrictSlipNoOnPay = 0; 
	if ($servicePercentage == '') 	$servicePercentage = 0;
	$service_account				 = $serviceaccount;
	if ($serviceaccount == '') 		$serviceaccount = "NULL";
	else				 			$serviceaccount = "'".$serviceaccount."'";
	if ($RedeemPoints_Account == '') $RedeemPoints_Account = "NULL";
	else				 			$RedeemPoints_Account = "'".$RedeemPoints_Account."'"; 
	
	if ($chkRegTax == '') 			$chkRegTax = 0; 
	if ($ShowTaxChkbox == '') 		$ShowTaxChkbox = 0; 
	if ($TaxConspPercentage == '') 	$TaxConspPercentage = 0;
	$TaxConsp_Account				 = $TaxConspAccount;
	if ($TaxConspAccount == '') 	$TaxConspAccount = "NULL";
	else				 			$TaxConspAccount = "'".$TaxConspAccount."'";
	
	if ($subgroupgrid_height == '') 	$subgroupgrid_height = 0;
	if ($subgroupgrid_width == '') 		$subgroupgrid_width = 0;
	if ($chkTabletScreen == '') 		$chkTabletScreen = 0;
	if ($ShowCustomerInRetail == '') 	$ShowCustomerInRetail = 0;
	
	
	$ErrorExists = 0;
	$message = '';
	
	if ($mode=='savecashreg') {
	
		if ($CostCenter_Code != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent Where Costcent_code = '".$CostCenter_Code."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Costcenter Code.';
			}
		}
		if ($Project_Code != '') {
			$sub_query = " Select Count(Project_Code) From Project Where Project_Code = '".$Project_Code."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Project Code.';
			}	
		}
		if ($Warehouse_Code != '') {
			$sub_query = " Select Count(Warehouse_Code) From Warehouse Where Warehouse_Code = '".$Warehouse_Code."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Warehouse Code.';
			}	
		}
		if ($Client_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Client_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Client Account.';
			}	
		}
		if ($Sales_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Sales_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Sales Account.';
			}	
		}
		if ($Cash_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Cash_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Cash Account.';
			}	
		}
		if ($Check_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Check_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Checks Account.';
			}	
		}
		if ($Tips_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Tips_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Tips Account.';
			}	
		}
		if ($Coupon_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$Coupon_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Coupon Account.';
			}	
		}
		
		if ($service_account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$service_account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Service Account.';
			}	
		}
		
		if ($TaxConsp_Account != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger Where Ledger_Number = '".$TaxConsp_Account."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Tax Consumption Account.';
			}	
		}
	
		if($Project_Code == '') $Project_Code = "NULL";
		else $Project_Code = "'".$Project_Code."'";
		
		if ($ErrorExists == 0) {
			$sub_query = " Select Count(*) From CashRegister Where Upper(CashRegister_Name) = Upper('".$txtCashRegisterName."') ";
			$sub_result = selectData($connection, $sub_query);
			$vCashregExists = $sub_result[0];
			
			if ($vCashregExists == 0) {
				fbegin();
				$query = " Insert Into CashRegister (CashRegister_Name, Currency_Code, CostCenter_Code, Project_Code, Warehouse_Code, Client_Account, Sales_Account, ".
						 " Cash_Account, Check_Account, Tips_Account, CashRegister_Account, Coupon_Account, CashRegister_Drawer, CashRegister_DrawerCOM, ".
						 " CashRegister_DisplayLed, CashRegister_DispCOM, CashRegister_LedDescLength, CashRegister_BarCode, CashRegister_PrintBarcode, ".
						 " CashRegister_SerialNo, CashRegister_RestSerialNo, CashRegister_Discount, CashRegister_SlipPrinter, CashRegister_Printer, CashRegisterTTC, ".
						 " CashRegister_Credit, CashRegister_Check, CashReg_Vendor, CashReg_ForcingVendor, Module_CashRegisterTable, Module_CashregisterStandardview, ".
						 " Module_CashRegisterFastItem, Module_RestaurantDelivery, Module_CashRegAutoItemsList, CashRegister_ShowTaxNonTax, CashRegister_AutoPost, ".
						 " CashRegister_SlipKitchen, CashRegister_SlipCopy, CashRegister_DrawerPrinter, CashRegister_AutoClosePrint, Cashregister_Logout, Cashregister_Retailtype, ".
						 " CashRegister_showitemcode, CashRegister_showdiscount, cashregister_service, cashregister_servicePercentage, service_account, ".
						 " cashregister_TaxConsumption, cashregister_TaxConsumptionpPer, TaxConsumption_Account, cashregister_ShowTaxConsumptionchkbox, Show_CustomerInRetail,".
						 " RedeemPoints_Account,CashRegister_showItemImage , CashRegister_showItemLocation, show_totalQty, CashRegister_Printerbtn,cashregister_printPending , CashRegister_RestrictSlipNoOnPay) ".
						 " Values ('".$txtCashRegisterName."', '".$Currency_Code."', '".$CostCenter_Code."', ".$Project_Code.", '".$Warehouse_Code."', '".$Client_Account."', ".
						 "		   '".$Sales_Account."', '".$Cash_Account."', '".$Check_Account."', '".$Tips_Account."', '".$Client_Account."', '".$Coupon_Account."', ".
						 "		   '".$chkDrawer."', '".$CashRegister_DrawerCOM."', '".$chkDispLed."', '".$CashRegister_DispCOM."', '".$CashRegister_LedDescLength."', ".
						 "         '".$chkBarcode."', '".$chkShowBarcode."', '".$chkSerialNo."', '".$chkRestSerial."', '".$chkDiscount."', '".$chkSlip."', '".$chkPrinter."', ".
						 "		   '".$chkTTC."', '".$chkCredit."', '".$chkCheck."', '".$chkVendor."', '".$chkForceVendor."', '".$chkTables."', '".$chkStandard."', ".
						 "         '".$chkFastItems."', '".$chkRestaurant."', '".$chkAutoItemsList."', '".$chkTaxNonTax."', '".$chkAutoPost."', '".$chkSlipKitchen."', ".
						 "         '".$CashRegister_SlipCopy."', '".$CashRegister_DrawerPrinter."', '".$chkAutoClosePrint."','".$chkcashregister_logout."','".$cashregister_retailtype."',".
						 " '$chkShowItemcode', '$chkShowDiscount', $chkRegService, $servicePercentage, $serviceaccount, ".
						 " $chkRegTax, $TaxConspPercentage, $TaxConspAccount, $ShowTaxChkbox, $ShowCustomerInRetail, ".$RedeemPoints_Account." , $chkShowItemImage, $chkShowItemLocation, $chkshow_totalQty , $chkPrinterbtn,$chkPrintonholdbtn , $chkRestrictSlipNoOnPay) ";
						 
				$result=mysql_query($query,$connection);
				//echo $query."<br>";exit;
						
				if ($result){
					fcommit();
					
					$query = " Update Setup Set ".
							 " CashReg_DispLedMsg = '".$CashReg_DispLedMsg."', CashReg_Weight = '".$chkScaleWeight."', CashReg_StartBarcode = '".$CashReg_StartBarcode."', ".
							 " CashReg_EndBarcode = '".$CashReg_EndBarcode."', CashReg_StartQty = '".$CashReg_StartQty."', CashReg_EndQty = '".$CashReg_EndQty."', ".
							 " CashReg_Price = '".$chkScalePrice."', CashReg_StartPrice = '".$CashReg_StartPrice."', CashReg_EndPrice = '".$CashReg_EndPrice."', ".
							 " ShowSlipNumber = '".$chkShowSlip."',Retaildt_height = $Retaildt_height, shortcutgrid_height = $shortcut_height, 
							shortcutgrid_width = $shortcut_width, subgroupgrid_height = $subgroup_height, subgroupgrid_width = $subgroupgrid_width, RestrictZeroPrice= $RestrictZeroPrice, ".
							" project_no=$project_no, costcent_no=$costcent_no, REMARKINV = '$REMARKINV',TabletScreenChecked = '$chkTabletScreen', POS_RedeemPoints = $chkRedeemPoints ";
					$result=mysql_query($query,$connection);
					
					$query = " Update Module Set ".
							 " Module_PostRetailOneToOne = '".$chkPostOneToOne."', Module_PostingByCashRegister = '".$chkPostByCashReg."', ".
							 " Module_CashRegItemQtyInCode = '".$chkItemQtyInCode."', Module_CashRegItemSeperate = '".$chkItemSeperate."', Module_CashRegisterBase2 = '".$chkShowBase2."' ";
					$result=mysql_query($query,$connection);
				}else{
					$message  = mysql_error($connection); 
					frollback();
				}
			} else {
				fbegin();
				$query = " Update CashRegister Set ".
						 " Currency_Code = '".$Currency_Code."', CostCenter_Code = '".$CostCenter_Code."', Project_Code = ".$Project_Code.", ".
						 " Warehouse_Code = '".$Warehouse_Code."', Client_Account = '".$Client_Account."', Sales_Account = '".$Sales_Account."', ".
						 " Cash_Account = '".$Cash_Account."', Check_Account = '".$Check_Account."', Tips_Account = '".$Tips_Account."', ".
						 " CashRegister_Account = '".$Client_Account."', Coupon_Account = '".$Coupon_Account."', CashRegister_Drawer = '".$chkDrawer."', ".
						 " CashRegister_DrawerCOM = '".$CashRegister_DrawerCOM."', CashRegister_DisplayLed = '".$chkDispLed."', ".
						 " CashRegister_DispCOM = '".$CashRegister_DispCOM."', CashRegister_LedDescLength = '".$CashRegister_LedDescLength."', ".
						 " CashRegister_BarCode = '".$chkBarcode."', CashRegister_PrintBarcode = '".$chkShowBarcode."', CashRegister_SerialNo = '".$chkSerialNo."', ".
						 " CashRegister_RestSerialNo = '".$chkRestSerial."', CashRegister_Discount = '".$chkDiscount."', CashRegister_SlipPrinter = '".$chkSlip."', ".
						 " CashRegister_Printer = '".$chkPrinter."', CashRegisterTTC = '".$chkTTC."', CashRegister_Credit = '".$chkCredit."', ".
						 " CashRegister_Check = '".$chkCheck."', CashReg_Vendor = '".$chkVendor."', CashReg_ForcingVendor = '".$chkForceVendor."', ".
						 " Module_CashRegisterTable = '".$chkTables."', Module_CashregisterStandardview = '".$chkStandard."', ".
						 " Module_CashRegisterFastItem = '".$chkFastItems."', Module_RestaurantDelivery = '".$chkRestaurant."', ".
						 " Module_CashRegAutoItemsList = '".$chkAutoItemsList."', CashRegister_ShowTaxNonTax = '".$chkTaxNonTax."', CashRegister_AutoPost = '".$chkAutoPost."', ".
						 " CashRegister_SlipKitchen = '".$chkSlipKitchen."', CashRegister_SlipCopy = '".$CashRegister_SlipCopy."', CashRegister_DrawerPrinter = '".$CashRegister_DrawerPrinter."', ".
						 " CashRegister_AutoClosePrint = '".$chkAutoClosePrint."',Cashregister_Logout = '".$chkcashregister_logout."',  ".
						 " Cashregister_Retailtype = '".$cashregister_retailtype."',CashRegister_showitemcode = '$chkShowItemcode',CashRegister_showdiscount = '$chkShowDiscount', ".
						 " cashregister_service = $chkRegService, cashregister_servicePercentage = $servicePercentage, service_account = $serviceaccount, ".
						 " cashregister_TaxConsumption = $chkRegTax, cashregister_TaxConsumptionpPer = $TaxConspPercentage, TaxConsumption_Account = $TaxConspAccount, ".
						 " cashregister_ShowTaxConsumptionchkbox = $ShowTaxChkbox, Show_CustomerInRetail = $ShowCustomerInRetail, RedeemPoints_Account = ".$RedeemPoints_Account. 
						 " ,CashRegister_showItemImage = $chkShowItemImage,CashRegister_showItemLocation = $chkShowItemLocation,show_totalQty = $chkshow_totalQty,CashRegister_Printerbtn = $chkPrinterbtn, cashregister_printPending=$chkPrintonholdbtn,".
						 " CashRegister_RestrictSlipNoOnPay = $chkRestrictSlipNoOnPay ".
						 " Where Upper(CashRegister_Name) = Upper('".$txtCashRegisterName."') ";
						 
				$result=mysql_query($query,$connection);
				//echo $query."<br>";exit;
				
				if ($result){
					fcommit();
					$query = " Update Setup Set ".
							 " CashReg_DispLedMsg = '".$CashReg_DispLedMsg."', CashReg_Weight = '".$chkScaleWeight."', CashReg_StartBarcode = '".$CashReg_StartBarcode."', ".
							 " CashReg_EndBarcode = '".$CashReg_EndBarcode."', CashReg_StartQty = '".$CashReg_StartQty."', CashReg_EndQty = '".$CashReg_EndQty."', ".
							 " CashReg_Price = '".$chkScalePrice."', CashReg_StartPrice = '".$CashReg_StartPrice."', CashReg_EndPrice = '".$CashReg_EndPrice."', ".
							 " ShowSlipNumber = '".$chkShowSlip."',Retaildt_height = $Retaildt_height, shortcutgrid_height = $shortcutgrid_height, 
							shortcutgrid_width = $shortcutgrid_width, subgroupgrid_height = $subgroupgrid_height, subgroupgrid_width = $subgroupgrid_width, RestrictZeroPrice= $RestrictZeroPrice,  ".
							"  project_no=$project_no, costcent_no=$costcent_no, REMARKINV = '$REMARKINV',TabletScreenChecked = '$chkTabletScreen', POS_RedeemPoints = $chkRedeemPoints ";
					//echo $query;exit;
					$result=mysql_query($query,$connection);
					
					$query = " Update Module Set ".
							 " Module_PostRetailOneToOne = '".$chkPostOneToOne."', Module_PostingByCashRegister = '".$chkPostByCashReg."', ".
							 " Module_CashRegItemQtyInCode = '".$chkItemQtyInCode."', Module_CashRegItemSeperate = '".$chkItemSeperate."', Module_CashRegisterBase2 = '".$chkShowBase2."' ";
					$result=mysql_query($query,$connection);
					
				}else{
					$message  = mysql_error($connection); 
					frollback();
				}

			}
		}
	} 
	else if ($mode=='savesetup') {
		if (empty($Setup_VatPercentage)) $Setup_VatPercentage = 0;
		
		if (isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) { 

			$image_name = addslashes($_FILES['photo']['name']);
			$image_size = getimagesize($_FILES['photo']['tmp_name']);
			$image_type =$_FILES['photo']['type'];
				
			if ($image_size == FALSE) {
				$message = "That's not an image.";
			
			}
			else {
				if ($_FILES['photo']['size'] > 204800) {
					$message = "Image is too large.";
				}
				else {
					$image = addslashes(file_get_contents($_FILES['photo']['tmp_name']));
				}
			}	
		}
		
		
		fbegin();
		$query = " Update Setup Set ".
				 " CashReg_RoundDivisor = '".$CashReg_RoundDivisor."', CashReg_ColorTheme = '".$CashReg_ColorTheme."', ".
				 " CashReg_BgColorOffer = '".$CashReg_BgColorOffer."', CashReg_BgColorQty = '".$CashReg_BgColorQty."', ".
				 " CashReg_BgColorOrderQty = '".$CashReg_BgColorOrderQty."', Company_Name = '".$Company_Name."', ".
				 " Company_Memo = '".$Company_Memo."', Base1 = '".$Base1."', Base2 = '".$Base2."', Setup_VatNo = '".$Setup_VatNo."', ".
				 " Setup_VatStartDate = '".insertMySQLDate($Setup_VatStartDate)."', Setup_VatPercentage = '".$Setup_VatPercentage."', ".
				 " CashReg_BgColorZeroPrice = '".$CashReg_BgColorZeroPrice."', CashReg_BgColorZeroQty = '".$CashReg_BgColorZeroQty."', ".
				 " CashReg_BgColorHasDiscount = '".$CashReg_BgColorHasDiscount."', CashReg_ApplyColorOffer = '".$chkApplyColorOffer."', ".
				 " CashReg_ApplyColorQty = '".$chkApplyColorQty."', CashReg_ApplyColorOrderQty = '".$chkApplyColorOrderQty."', ". 
				 " CashReg_ApplyColorZeroPrice = '".$chkApplyColorZeroPrice."', CashReg_ApplyColorZeroQty = '".$chkApplyColorZeroQty."', ".
				 " CashReg_ApplyColorHasDiscount = '".$chkApplyColorHasDiscount."',  project_no='$project_no', costcent_no='$costcent_no', REMARKINV = '$REMARKINV'  "; 
				
		if ($image != '') $query .= ", Company_Logo = '$image'";
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
				
		if ($result){
			fcommit();
			
			$query = " Update Module Set ".
					 " Module_PriceOffer = '".$Module_PriceOffer."' ";
			$result=mysql_query($query,$connection);
		}else{
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
}

else if($mode=='cashregtrans' && $TransType != '' && $CashReg != ''){
	$TotalCashAmount = 0;
	$ErrorExists = 0;
	
	if ($TransType == 'IN'){
		$query = " Insert Into cashregistertrans (cashregister_name, ctrans_timein, ctrans_timeout, currency_code, ctrans_totalcashstart, ctrans_totalcashclose) ".
				 " Values ('".$CashReg."', now(), null, '".$StpCurrCode."', 0, 0) ";
		$result = mysql_query($query,$connection) or die(mysql_error());
		$CashRegTransID = mysql_insert_id();
	}
	else if ($TransType == 'OUT'){
		$sub_query = " Select count(*) From temp_retail Where upper(cashregister_name) = upper('".$CashReg."')";
		$sub_result = selectData($connection, $sub_query);
		$OpenInvoiceExists = $sub_result[0];
		
		if ($OpenInvoiceExists > 0) {
			$ErrorExists = 1;
			$message = 'Unable to close cashregister, there are ('.$OpenInvoiceExists.') open invoices.';
		}
		
		if ($ErrorExists == 0) {
			$sub_query = " Select ctrans_id, ifnull(ctrans_totalcashstart,0) From cashregistertrans Where upper(cashregister_name) = upper('".$CashReg."') and ctrans_timeout is null ";
			$sub_result = selectData($connection, $sub_query);
			$CashRegTransID   = $sub_result[0];
			$CashRegStartCash = $sub_result[1];
			
			$query = " Update cashregistertrans Set ctrans_timeout = now() ".
					 " Where ctrans_id = '".$CashRegTransID."'";
			$result = mysql_query($query,$connection) or die(mysql_error());
			
			//Reopen Cashregister
			if($txtnewshiftopen == 1){
			$query = " Insert Into cashregistertrans (cashregister_name, ctrans_timein, ctrans_timeout, currency_code, ctrans_totalcashstart, ctrans_totalcashclose) ".
					 " Values ('".$CashReg."', now(), null, '".$StpCurrCode."', $CashRegStartCash, 0) ";
			$result = mysql_query($query,$connection) or die(mysql_error());
			}
		}	
	} 
		
	if ($ErrorExists == 0) {
		if ($TransType == 'IN'){
			$sub_query = " Select Cash_Id, Cash_Value From cashamounts order by Cash_Value desc ";
			//echo $sub_query;
			$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_rows=mysql_fetch_array($sub_result)){
				$CountUnit = $sub_rows[1];
				$CountQty = $_POST['txtCashQty'.$sub_rows[0]];
				
				if (empty($CountQty)) $CountQty = 0;
				$CountTotal = $CountUnit*$CountQty;
				
				$TotalCashAmount += $CountTotal;
				
				$query = " Insert Into cashregistercount (ctrans_id, ctrans_type, moneycount_unit, moneycount_qty, moneycount_total) ".
						 " Values ('".$CashRegTransID."', '".$TransType."', $CountUnit, $CountQty, $CountTotal) ";
				$result = mysql_query($query,$connection) or die(mysql_error());
			}
		
		
			$query = " Update cashregistertrans Set ctrans_totalcashstart = $TotalCashAmount ".
					 " Where ctrans_id = '".$CashRegTransID."'";
			$result = mysql_query($query,$connection) or die(mysql_error());
		}
		else if ($TransType == 'OUT'){
			$query = " Update cashregistertrans Set ctrans_totalcashclose = $CloseAmount ".
					 " Where ctrans_id = '".$CashRegTransID."'";
			$result = mysql_query($query,$connection) or die(mysql_error());
		}
	}
}

else if($mode=='cashtrans' && $TransType != '' && $txtCashAmount != ''){
	if (empty($txtCashAmount)) $txtCashAmount = 0;
	
	$txtCashAmountB1 = ConvertCurrency($txtCashCurr, $base1, insertMySQLDate(displayToday()), $txtCashAmount, $connection);
	$txtCashAmountB2 = ConvertCurrency($txtCashCurr, $base2, insertMySQLDate(displayToday()), $txtCashAmount, $connection);
	
	$sub_query = " Select ctrans_id From cashregistertrans Where upper(cashregister_name) = upper('".$_SESSION['cashregister']."') and ctrans_timeout is null ";
	$sub_result = selectData($connection, $sub_query);
	$CashRegTransID = $sub_result[0];
	
	if($usrac == '') $usrac = $_SESSION['useraccount'];
	
	if ($CashRegTransID != '') {
		$query = " Insert Into cashregistertransdt (ctrans_id, ctransdt_date, ctransdt_type, currency_code, ctransdt_amount, ctransdt_amountb1, ctransdt_amountb2, ctransdt_description,user_name) ".
				 " Values ('".$CashRegTransID."', now(), '".$TransType."', '".$txtCashCurr."', $txtCashAmount, $txtCashAmountB1, $txtCashAmountB2, '".$txtCashDesc."','".$_SESSION['useraccount']."') ";
		$result = mysql_query($query,$connection);
		//echo $query;exit;
		if (!$result) {
			$message = mysql_error($connection);
		} else{
			if($TransType == 'OUT'){
			$crtransdt_id = mysql_insert_id();
			$query = "select date_format(ctransdt_date,'%d-%m-%Y %H:%i:%s'),ctransdt_amount,currency_code, ctransdt_description,login.User_Name
						from cashregistertransdt
						left join ".$_SESSION['dbLabel'].".login as login on login.User_account = cashregistertransdt.user_name
						where Upper(Login_Schema) = '".$_SESSION['dbName']."'
						and  ctransdt_id=$crtransdt_id;";
			//echo  $query; exit;			
			$res = mysql_query($query,$connection);	 $company_email;	
			$rw = mysql_fetch_row($res);
			$Subject="Cash Out by ".$rw[4];
			$Body="<table><tr><td>Cash Out by ".$rw[4]." </td></tr>\n";
			$Body=$Body."<tr><td>Date : ".$rw[0]."</td></tr>\n";
			$Body=$Body."<tr><td>Amount : ".$rw[1]." ".$rw[2]."</td></tr>\n";	
			$Body=$Body."<tr><td>Description : ".$rw[3]."</td></tr>\n";				
			$Body=$Body." </table> \n";
			
			$mail=sendmail1($Subject,$Body,$connection);	
			}
			
		}
	} else {
		$message = 'Save not allowed. No open cashregister.';
	}	
}

else if($mode=='checkitemmodifiers' && $txtItemCode != ''){
	$sub_query = " Select count(*) From itembuttons ".
				 " Inner Join items on items.Item_Code = itembuttons.ItemButton_RelatedItem ".
			     " Where ((upper(Item_Code) = upper('".$txtItemCode."')) or (upper(Item_Barcode) = upper('".$txtItemCode."')) or  ".
				 "  	  (upper(Item_Barcode2) = upper('".$txtItemCode."')) or (upper(Item_Barcode3) = upper('".$txtItemCode."'))) ".
				 " and ItemButton_Type != 'NOTES' ";
	$sub_result = selectData($connection, $sub_query);
	
	$ItemHasModifiers = 0;
	if($sub_result[0] > 0) $ItemHasModifiers = 1; 
	

	$row_array['hasmodifier'] = $ItemHasModifiers;
}
else if($mainmode=='emptydrivercode'){
	$saleid = $_GET["saleid"];
	if($saleid!=''){
	$query = "update temp_retail set driver_Code = '' where sale_id = $saleid ;";
	//echo $query;
	$result = mysql_query($query,$connection);
	}

}
else if($mainmode=='checktel'){

	$vtel = $_GET["vtel"];
	$saleid = $_GET["saleid"];

	$query = " select Customer_Code, Concat(Customer_Name, if(ifnull(Customer_Telephone1,'') != '', concat('\rTel#: ', Customer_Telephone1), ''), if(ifnull(Customer_Address,'') != '', concat('\rAddress: ', Customer_Address), '')) from customer where Customer_Telephone1 = '$vtel' or Customer_Telephone2 = '$vtel' ";
	//echo $query;
	$result = mysql_query($query,$connection) or die(mysql_error());
	$cust = mysql_fetch_row($result);

	if($saleid!='' and $cust[0]!=''){
		$query = "update temp_retail set customer_code = '$cust[0]',sale_type='delivery' where sale_id = $saleid ;";
		$result = mysql_query($query,$connection);
	}
	
	echo $cust[0]."[BRK]".$cust[1]."[BRK]";

}
else if($mainmode=='showcallerid'){


ShowCallingRecords($connection,$arrayparams);
exit;
}

else if($mainmode=='getphone'){

echo "[BRKCALLERID]";

$query = "select callerid_number,callerid_id from callerid where callerid_id = $callerid";
//echo $query;
$result = mysql_query($query,$connection) or die(mysql_error());
$rows=mysql_fetch_array($result);
$callerid_id=$rows[1];

//echo "Asd".$rows[0];
if($rows[0]!=''){

$query= " Select Customer.Customer_Code As Ledger_Number, Customer.Customer_Name As Ledger_Name, ".
			" Concat(Customer_Name, ' Tel#: ', Customer_Telephone1) As CustomerRemark, Customer.Customer_Telephone1, ".
			" Concat(Customer_Name, if(ifnull(Customer_Telephone1,'') != '', concat('\nTel#: ', Customer_Telephone1), ''), if(ifnull(Customer_Address,'') != '', concat('\nAddress: ', Customer_Address), '')) As CustomerRemark2 
			from customer where customer_telephone1 = '$rows[0]' or customer_telephone2 = '$rows[0]' ";
//echo $query;			
$result = mysql_query($query,$connection) or die(mysql_error());
$row=mysql_fetch_array($result);

	
echo $rows[0];
echo "[BRKCALLERID]";

if($row[0]!='')
echo $row[0];
else 
echo '';
echo "[BRKCALLERID]";
echo $row[1];
echo "[BRKCALLERID]";
echo $row[4];

if($callerid_id!='') {
$query = "update callerid set caller_id_status = 1 where callerid_id=$callerid_id ";
$result = mysql_query($query,$connection);
}

}
echo "[BRKCALLERID]";
exit;
}
else if($mainmode=='checkphone'){
echo "[BRKCALLERID]";

$query = "select callerid_number,callerid_id from callerid where caller_id_status = 0";
$result = mysql_query($query,$connection);
$rows=mysql_fetch_array($result);
$callerid_id=$rows[1];

if($rows[0]!=''){

$query= " Select Customer.Customer_Code As Ledger_Number, Customer.Customer_Name As Ledger_Name, ".
			" Concat(Customer_Name, ' Tel#: ', Customer_Telephone1) As CustomerRemark, Customer.Customer_Telephone1, ".
			" Concat(Customer_Name, if(ifnull(Customer_Telephone1,'') != '', concat('\nTel#: ', Customer_Telephone1), ''), if(ifnull(Customer_Address,'') != '', concat('\nAddress: ', Customer_Address), '')) As CustomerRemark2 
			from customer where customer_telephone1 = '$rows[0]' or customer_telephone2 = '$rows[0]' ";
$result = mysql_query($query,$connection);
$row=mysql_fetch_array($result);

	
echo $rows[0];
echo "[BRKCALLERID]";

if($row[0]!='')
echo $row[0];
else 
echo '';
echo "[BRKCALLERID]";
echo $row[1];
echo "[BRKCALLERID]";
echo $row[4];

if($callerid_id!='') {
$query = "update callerid set caller_id_status = 1 where callerid_id=$callerid_id ";
$result = mysql_query($query,$connection);
}

}
echo "[BRKCALLERID]";
}
if($mode=='getItemImg'){

	$vitemCode = $_GET["ITMCode"];
	 

	$query = " select concat('uploads/',REPLACE(ifnull(Items.Item_Picture,''), 'items_photos','items_photos2')) as Item_Picture,concat('uploads/',ifnull(Items.Item_Picture,'')) as Item_PictureOrg from items
	where item_code = '$vitemCode' or Item_Barcode = '$vitemCode' or Item_Barcode2 = '$vitemCode' or Item_Barcode3 = '$vitemCode'  ";
	//echo $query;
	$result = mysql_query($query,$connection) or die(mysql_error());
	$cust = mysql_fetch_row($result);
 
	
	echo "[BRK]".$cust[0]."[BRK]".$cust[1]."[BRK]";

}
else if($mode == 'addCustomerDiscount' && $SRetId != "" ){
	$Customer_code = $_GET['txtRetCustomerCode'];
	$vRetDiscountPer = $_GET['txtRetCustomerDisc'];
	$vRetCustomerPt = $_GET['txtRetCustomerPt'];
	
	$query = "update temp_retail set Customer_code = '".$Customer_code."' where sale_id='$SRetId' ";
	$result = mysql_query($query,$connection);
	
	addDiscount ($SRetId,$vRetDiscountPer,$base1,$base2,$CashRegisterTTC,$Setup_VatPercentage, $Customer_code, $connection);
	
}

else if($actionmode == 'calcCustomerDisc'){
	$SRetId = $_GET['RetailId'];
	$Customer_code = $_GET['RetCustomerCode'];
	$queryCustomer = "select ifnull(Customer_DiscountPer,0)
					from customer
					where ifnull(Customer_special,0) = 1 and Customer_Code = '$Customer_code' ";
	$resCustomer = mysql_query($queryCustomer,$connection);
	$numCustomer = mysql_num_rows($resCustomer);
	$rowCustomer = mysql_fetch_row($resCustomer);
	$vRetDiscountPer = $rowCustomer[0];
	
	if($numCustomer > 0 && $vRetDiscountPer > 0)
	addDiscount ($SRetId,$vRetDiscountPer,$base1,$base2,$CashRegisterTTC,$Setup_VatPercentage, $Customer_code, $connection);
	
	exit;
}

$message = ereg_replace(' ','%20',$message);
$string  = ereg_replace(' ','%20',$string);
//echo $mode.$message; exit;
$txtLedgerClientCard = $_GET['txtLedgerClientCard'];
if($actionmode == 'checkcustomer'){
	$query = "select Customer_Code from customer where customer_card='$txtLedgerClientCard'";
	$res = mysql_query($query,$connection);
	$rw = mysql_fetch_row($res);
	if($rw[0] != '') echo $rw[0];
	else echo 0;
	exit;
}

if($SRetId != '' && $POS_RedeemPoints == 1){
	$query = "select sale_customerAwardPt from temp_retail where sale_id = $SRetId";
	$result = mysql_query($query,$connection);
	$row = mysql_fetch_row($result);
	$txtRetCustomerPt = $row[0];
}

if($mode == "post") 
	header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrRetId=".$SRetId."&PrRetRef=".$vSaRef."&string=".$string);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_RetailSearch.php?PMode=$AllowEdit&message=".$message);	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_RetailSearch.php?message=".$message);
else if ($mode == "" && ($mainmode == "voidinvoice" || $mainmode == "wasteinvoice"))	
	header ("Location: ./Form_RetailSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_RetailSearchPending.php?message=".$message);
else if ($mode == "deletedt" )		
	header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&txtId=".$SRetId."&txtSlipNo=".$txtSlipNo."&txtVendorCode=".$txtVendorCode."&string=".$string."&message=".$message);	
else if ($mode == "refunddt" )		
	header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&txtId=".$SRetId."&txtSlipNo=".$txtSlipNo."&txtVendorCode=".$txtVendorCode."&string=".$string."&message=".$message);	else 
if ($mode == "refunddtall" )		
	header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&txtId=".$SRetId."&txtSlipNo=".$txtSlipNo."&txtVendorCode=".$txtVendorCode."&string=".$string."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_RetailDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PRetId=".$SRetId."&PRetDate=".$PRetDate."&PRetDtId=".$SRetDtId);	
else if ($mode == "adddiscount" ) {
	if ($DiscNotAllowed == 1)
		header ("Location: ./Form_RetailDiscount.php?actionmode=adddiscount&mainaction=".$mainmode."&message=".$message."&PRetId=".$SRetId);
	else
		header ("Location: ./Form_RetailDiscount.php?actionmode=discountadded&mainaction=".$mainmode."&message=".$message."&PRetId=".$SRetId);
}	
else if ($mode == "payment" ) {		
	if ($ErrorExists == 1)
		header ("Location: ./Form_RetailPayment.php?actionmode=".$mode."&mainaction=".$mainmode."&noprint=".$noprint."&PRetId=".$SRetId."&message=".$message);			
	else
		header ("Location: ./Form_RetailPayment.php?actionmode=payed&mainaction=".$mainmode."&noprint=".$noprint."&PRetId=".$SRetId."&message=".$message);			
}	
else if ($mode == "postretails" )		
	//header ("Location: ./Form_Retail.php?message=".$message."&string=".$string);
	header ("Location: ./Form_Retail_PostOptions.php?message=".$message."&string=".$string);
else if ($mode == "closingcashreg" )		
	header ("Location: ./Form_Retail_Closing.php?print=1&txtDateFrom=".$txtDateFrom."&message=".$message);
else if ($mode == "savecashreg" || $mode == "savesetup")		
	header ("Location: ./Form_RetailSetup.php?CashRegister_Name=".$txtCashRegisterName."&message=".$message);
else if ($mode == "cashregtrans")
	header ("Location: ./Form_RetailTrans.php?TransType=".$TransType."&message=".$message);
else if ($mode == "cashtrans"){
	if($TransType == 'OUT') header ("Location: ./Form_RetailCashTrans.php?TransType=".$TransType."&usrac=$usrac&message=".$message);
	else header ("Location: ./Form_RetailCashTrans.php?TransType=".$TransType."&message=".$message);
}
else if ($mode == "submitrecord")	{
    header ("Location: ./Form_RetailDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PRetId=".$SRetId.	
			"&PRetDate=".$PRetDate."&PRetClientCode=".$PRetClientCode.'&PRetCashRegister='.$PRetCashRegister.
			"&PRetCurr=".$PRetCurr."&PRetProjectCode=".$PRetProjectCode."&PRetCostCentCode=".$PRetCostCentCode.
			"&txtRetDtSlip=".$txtRetDtSlip."&txtRetDtVendor=".$txtRetDtVendor."&txtWarehouseCode=".$txtWarehouseCode.
			"&message=".$message."&string=".$string );
}
/*else if ($mode == "submitrecord1" || $mode == "submitrecord2") {	
	if ($VendorNotFound == 1 || $ItemNotFound == 1 || $ErrorExists == 1) 
		header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&txtId=".$SRetId."&txtItemOption=".$SItemOption."&txtSlipNo=".$txtSlipNo."&txtVendorCode=".$txtVendorCode."&txtItemBarcode=".rawurlencode($txtItemBarcode)."&txtItemQty=".$txtItemQty."&openwin=1&message=".$message."&string=".$string);
	else
		header ("Location: ./Form_Retail.php?actionmode=".$mode."&mainaction=".$mainmode."&txtId=".$SRetId."&txtItemOption=".$SItemOption."&txtSlipNo=".$txtSlipNo."&txtVendorCode=".$txtVendorCode."&message=".$message."&string=".$string);
}	*/

$return_arr = array();

$row_array['message'] = $message;
$row_array['message1'] = $message1;
$row_array['sub_query'] = $exists;
$row_array['enterPrice'] = $enterPrice;
$row_array['txtId'] = $SRetId;
$row_array['txtSubGroup'] = $vSubGroup;
$row_array['txtRetCustomerPt'] = $txtRetCustomerPt;



		
array_push($return_arr,$row_array);
echo json_encode($return_arr);









function Print_RetailSlipSubGroup($ReportName,$RetailId,$subgroupcode,$printername,$DecimalBase,$Setup_VatPercentage,$connection,$Classname,$ApplyClass,$tablename,$guestnumber,$Module_GroupHoldFire){


$queryusers=" Select User_Name As User_FullName ".
			" From ".$_SESSION['dbLabel'].".users where user_account='".$_SESSION['useraccount']."' ";
$resultusers=mysql_query($queryusers,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultusers)){
	extract($rows);
}


//Read From Setup Table							
$querysetup= " Select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Company_Name As CompanyName, Company_Memo As CompanyMemo, Company_City As CompanyCity, ".
			 " Company_Telephone As CompanyTelephone, Company_Fax As CompanyFax, ".
			 " Setup_VatNo, Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


//Read From CashRegister Table
$queryCashRegister=" Select ifNull(CashRegisterTTC,0) As CashRegisterTTC,ifNull(CashRegister_DrawerCOM,0) As CashRegister_DrawerCOM ,Currency_Code as cashregcurr".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}

 
if($RetailId != '')
{
			 
	$query = " Select Sale_ID, Sale_Reference,date_format(retail.Sale_Date,'%d/%m/%Y') as datetime ,Retail.User_account as useraccount, Date_Format(Sale_Date,'%d/%m/%Y') As Sale_Date, Retail.Currency_code As CurrCode, ".
			 " Retail.Client_code As ClientCode, Clients.Ledger_name As ClientName, CashRegister_Name, Sale_Remark, ".
			 " if(Sale_Information='' or Sale_Information is null, Clients.Ledger_name, Sale_Information) As Sale_Information, ".
			 " Round(ifNull(Sale_Taxable,0), ".$DecimalBase.") As SaleTaxable, Round(ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As SaleNoneTaxable, ".
			 " Round(ifNull(Sale_Taxable,0) + ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As GrossTotal, ".
			 " Round(ifNull(Sale_DiscountPer,0), ".$DecimalBase."), Round(ifNull(Sale_DiscountAmount,0), ".$DecimalBase.") As Sale_DiscountAmount,  ".
			 " Round(ifNull(Sale_VAT,0), ".$DecimalBase.") As Sale_VAT, ".
			 " Round((ifNull(Sale_Taxable,0) + ifNull(Sale_NoneTaxable,0) + IfNull(Sale_VAT,0) - IfNull(Sale_DiscountAmount,0) + (ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0))), ".$DecimalBase.") As Sale_NetTotal1,  ".
			 " Round((ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Round(ifNull(Sale_NetTotal,0), ".$DecimalBase.") As  Sale_NetTotal, ".
			 " ifNull(Sales_CashInBase1,0) As CashInBase1, ifNull(Sales_CashInBase2,0) As CashInBase2, ".
			 " ifNull(Sales_CashOutBase1,0) As CashOutBase1, ifNull(Sales_CashOutBase2,0) As CashOutBase2,  ".
			 " Retail.Coupon_Id, Coupon_Reference As CouponReference, Coupon_Name As CouponName, ifNull(Retail.Coupon_Amount,0) As CouponAmount,Users.User_Name as UserName, ".
			 " ifNull(Retail.Coupon_Amount,0) - ifNull(convertcurfunc(Coupon.Currency_Code, Retail.Currency_code, Coupon_Date, 0, 0, '', '', ifNull(Coupon.Coupon_AmountConsum,0)),0) As CouponRemAmount, ".
			 " Sale_CashCur As CashCur, ifNull(Sale_Cash,0) As SaleCash, Sale_CheckNo As CheckNo, Date_Format(Sale_CheckDate,'%d/%m/%Y') As CheckDate, Sale_Bank As BankName, Sale_BankBranch As BankBranch, ".
			 " Sales_CreditAccCur As CreditAccCur, ifNull(Sales_CreditAmount,0) As CreditAmount, Sales_CreditAcc As CreditAcc, Ledger.Ledger_Name As CreditName,  ".
			 " ifNull(Sales_TipsBase1,0) As SalesTipsBase1, ".
			 " Round((ifNull(Sale_Taxable,0)*(1+$Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As GrossTotalTTC, ".
			 " Round((((ifNull(Sale_Taxable,0)*(1+$Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0))*(ifNull(Sale_DiscountPer,0)/100)), ".$DecimalBase.") As Sale_DiscountAmountTTC, ".
			 " Round((ifNull(Sale_Taxable,0)*(1+$Setup_VatPercentage/100)), ".$DecimalBase.") As SaleTaxableTTC, ".
			 " Date_Format(Sale_Date,'%h:%i %p') As Sale_Time ".
			 " ,Date_Format(now(),'%h:%i %p') As Now_Time ".
			 " From Temp_Retail as Retail ".
			 " Left Join Clients on Retail.Client_code = Clients.Ledger_Number ".
			 " Left Join Coupon on Retail.Coupon_Id =  Coupon.Coupon_Id ".
			 " Left Join Ledger on Retail.Sales_CreditAcc =  Ledger.Ledger_Number ".
			 " Left Join ".$_SESSION['dbLabel'].".users on users.User_account =  Retail.User_account ".
	         " Where Sale_ID = '".$RetailId."'";		 
			 
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){
		extract($rows);
	}
	
	$queryfound = " select * from temp_retaildt,items 
		Where Sale_ID = '".$RetailId."' and saledt_printed = 0
		and items.item_code =  temp_retaildt.item_code
		and (
						(
							ifnull(items.subgroup_code,-1) in (select p_subgroup from ".$_SESSION['dbLabel'].".printersubgroup where p_category = '$Classname' )  
							and $ApplyClass = 1
						 )
						 or 
						 (
							ifnull(items.subgroup_code,-1) in (select p_subgroup from ".$_SESSION['dbLabel'].".printersubgroup where p_name = '$Printername' )  
							and $ApplyClass = 0
						 )
						)
		";	
	$resultfound=mysql_query($queryfound,$connection) or die(mysql_error());
	$countfound = mysql_num_rows($resultfound);
	
	if($countfound==0 or $countfound == '')
		exit;
//$printer = "Custom KUBE 80mm (200dpi)";
$printer = $printername;


$handle = printer_open($printer);
printer_start_doc($handle, "My Document");
printer_start_page($handle);
   //$content= $data1;
	
   // Set print mode to RAW and send PDF to printer
   printer_set_option($handle, PRINTER_MODE, "RAW");
   //printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
   /*printer_write($handle, $CompanyName);
   printer_write($handle, "\n");
   printer_write($handle, "TEL: $CompanyTelephone");
   printer_write($handle, "Vat# $Setup_VatNo"."\n");
  
	 
	printer_write($handle, "    $CompanyFax"."\n");
	printer_write($handle, "\n");
	printer_write($handle, "\n");
	
	printer_write($handle, "Inv.    ");
	printer_write($handle, "$Sale_Reference");
	printer_write($handle, "    Date    ");
	printer_write($handle, "$Sale_Date"."\n");
	
	
	printer_write($handle, "        ");
	printer_write($handle, "     ");
	printer_write($handle, "    Time    ");
	printer_write($handle, "$Sale_Time"."\n");
	
	 
	printer_write($handle, "  Reg      ");
	printer_write($handle,  $_SESSION['cashregister']);
	printer_write($handle, "\n");
	*/
	/* $font=printer_create_font("Arial",148,76,PRINTER_FW_BOLD,false,false,false,-50);
     printer_select_font($handle,$font);*/	   
	$querydt = " Select RetailDt.SaleDt_id, RetailDt.Item_CodePacked, Substr(RetailDt.Item_code,1,11) As ItemCode, Substr(Item_Description,1,22) As ItemDescription, ".
			   " if(ifNull(Items.Item_Vat,0) > 0, '*', ' ') As ItemVat, Sum(ifNull(SaleDt_Quantity,0)) as SaleDt_Quantity, Round(SaleDt_Price, ".$DecimalBase.") As SaleDtPrice, SaleDt_PriceBase1, SaleDt_PriceBase2, ".
			   " Round(SaleDt_DiscountPer, ".$DecimalBase.") As SaleDtDiscountPer,  ".
			   " Round(Sum((SaleDt_Quantity*SaleDt_Price)-((SaleDt_Quantity*SaleDt_Price*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As SaleDtTotal, ".
			   " Round(SaleDt_PriceTTC, ".$DecimalBase.") As SaleDtPriceTTC, ".
			   " Round(Sum((SaleDt_Quantity*SaleDt_PriceTTC)-((SaleDt_Quantity*SaleDt_PriceTTC*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As SaleDtTotalTTC 
			   ,RetailDt.salesdt_remark as salesdt_remark,saleDt_ItemStatus, RetailDt.RelatedDt_Id as RelatedDtId, if(Q1.CountItemModifiers > 0, 1, 0) as ItemHasModifiers 
			   ".
			   " From temp_RetailDt  as RetailDt Left Join Items on RetailDt.Item_code = Items.Item_code ".
			   " Left Join ( Select RetailDt1.RelatedDt_Id, count(*) as CountItemModifiers ".
			   " 			 From Temp_RetailDt as RetailDt1 ".
			   " 			 Where RetailDt1.Sale_ID = '".$RetailId."' ".
			   " 			 Group By RetailDt1.RelatedDt_Id) as Q1 on Q1.RelatedDt_Id = RetailDt.SaleDt_Id ".
			   " Where RetailDt.Sale_ID = '".$RetailId."' ".
			   " and ifnull(saledt_printed,0) = 0 ".
			   " and (
						(
							ifnull(items.subgroup_code,-1) in (select p_subgroup from ".$_SESSION['dbLabel'].".printersubgroup where p_category = '$Classname' )  
							and $ApplyClass = 1
						 )
						 or 
						 (
							ifnull(items.subgroup_code,-1) in (select p_subgroup from ".$_SESSION['dbLabel'].".printersubgroup where p_name = '$Printername' )  
							and $ApplyClass = 0
						 )
						)";
						
			 //  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ".
			 
	$querydt1 = $querydt." And IfNull(SaleDt_ItemStatus,0) Not In (4,5) ".
						 " Group By RetailDt.Item_CodePacked, RetailDt.Item_code, RetailDt.SalesDt_Remark, ItemHasModifiers ".
						 " Order By ifNull(RetailDt.RelatedDt_Id, RetailDt.SaleDt_ID)   ";
							 
	$querydt2 = $querydt." And IfNull(SaleDt_ItemStatus,0) = 4 ".
						 " Group By RetailDt.Item_CodePacked, RetailDt.Item_code, RetailDt.SalesDt_Remark, ItemHasModifiers ".
						 " Order By ifNull(RetailDt.RelatedDt_Id, RetailDt.SaleDt_ID)   ";
		
	$querydt3 = $querydt." And IfNull(SaleDt_ItemStatus,0) = 5 ".
						 " Group By RetailDt.Item_CodePacked, RetailDt.Item_code, RetailDt.SalesDt_Remark, ItemHasModifiers ".
						 " Order By ifNull(RetailDt.RelatedDt_Id, RetailDt.SaleDt_ID)   ";
	
			 // " Group By RetailDt.Item_CodePacked, RetailDt.Item_code, RetailDt.SalesDt_Remark, ItemHasModifiers ".
			  //" Order By RetailDt.SaleDt_id  ";
			  // " Order By RetailDt.Item_CodePacked, RetailDt.Item_code  ";
			  //echo $querydt; 
			//	exit;	   
	//$data .=  $querydt;
		//printer_write($handle, " $sale_type ");
	/*	printer_write($handle, "\n");	  */
	
	$font = printer_create_font("Arial",18,18,400,false,false,false,0);
	//$font1 = printer_create_font("Arial",14,14,700,false,false,false,0);
	printer_select_font($handle, $font);

	$x=1;
	$y=15;	
		printer_draw_text($handle, $datetime."        ".$Now_Time, $x, $y);
		$y+=12;
		
		//printer_write($handle, "\n");
		$y+=12;
		printer_draw_text($handle, $UserName, $x, $y);
		$y+=12;	
		$y+=12;
		printer_draw_text($handle, "Table  : ".$tablename, $x, $y);
		$y+=18;
		printer_draw_text($handle, "Guests#  : ".$guestnumber, $x, $y);
		$y+=18;
	
		  

 
		//printer_write($handle, "Desc.              Qty.");
		//printer_write($handle, "     Qty.");
		
		//printer_write($handle, "\n");	  
		printer_draw_text($handle, "____________________________________", $x, $y);
		$y+=12;
		$y+=12;
		//printer_write($handle, "\n");	  
	
	$resultdt=mysql_query($querydt1,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultdt)){
		extract($rows);
		
		$TotalQty = $TotalQty + $SaleDt_Quantity;
		
		printer_draw_text($handle, $SaleDt_Quantity."   ".$ItemDescription , $x, $y);
		$y+=12;
		$itemstatus='';
		
		if(strtoupper($saleDt_ItemStatus)==1)
			$itemstatus = 'Gift';
		else if(strtoupper($saleDt_ItemStatus)==2)
			$itemstatus = 'Void';	
		else if(strtoupper($saleDt_ItemStatus)==3)
			$itemstatus = 'Waste';	
		else if(strtoupper($saleDt_ItemStatus)==4)
			$itemstatus = 'Hold';	
		else if(strtoupper($saleDt_ItemStatus)==5)
			$itemstatus = 'Fire';			
		
	
		if($itemstatus!=''){
			printer_draw_text($handle, "( ".$itemstatus." )", $x, $y);
			$y+=12;
		}
		$y+=12;
		//printer_write($handle, "\n");		
		if($salesdt_remark!='') {
			printer_draw_text($handle, "     ".$salesdt_remark, $x, $y);		
			$y+=12;
			}
		//printer_write($handle, "  $SaleDt_Quantity    ");
		if($salesdt_remark!='') {
			//printer_draw_text($handle, "\n");
			$y+=12;
		}			
		//printer_write($handle, "\n"); 
		$y+=12;
	}
	
	// Print Hold Items 
	$resultdt2=mysql_query($querydt2,$connection) or die(mysql_error());
	$countdt2 = mysql_num_rows($resultdt2);
		
	if ($countdt2 > 0) {
     	printer_draw_text($handle, "____________________________________", $x, $y);
		$y+=12;
		//printer_write($handle, "\n");
		$y+=12;	
		printer_set_option($handle, PRINTER_TEXT_COLOR,"005533");		
		printer_draw_text($handle, "Hold", $x, $y);
		printer_set_option($handle, PRINTER_TEXT_COLOR,"000000");
		$y+=24;
	}
		
	while($rows2=mysql_fetch_array($resultdt2)){
		extract($rows2);
		
		$TotalQty = $TotalQty + $SaleDt_Quantity;
		
		printer_draw_text($handle, $SaleDt_Quantity."   ".$ItemDescription , $x, $y);
		$y+=12;		
		if($salesdt_remark!='') {
			printer_draw_text($handle, "  ".$salesdt_remark."\n", $x, $y);	
			$y+=12;
			}
			$y+=12;
			$y+=12;
		//printer_write($handle, "\n");
	    //printer_write($handle, "\n");		
		
	}
	
	// Print Fire Items 
	$resultdt3=mysql_query($querydt3,$connection) or die(mysql_error());
	$countdt3 = mysql_num_rows($resultdt3);
		
	if ($countdt3 > 0) {
		printer_set_option($handle, PRINTER_TEXT_COLOR,"005533");
		printer_draw_text($handle, "Fire", $x, $y);
		printer_set_option($handle, PRINTER_TEXT_COLOR,"000000");
		$y+=12;	
	
 if($Module_GroupHoldFire==0){
	while($rows3=mysql_fetch_array($resultdt3)){
		extract($rows3);
		
		$TotalQty = $TotalQty + $SaleDt_Quantity;
		
		printer_draw_text($handle, $SaleDt_Quantity."   ".$ItemDescription , $x, $y);
			$y+=12;
			
		if($salesdt_remark!='') {
			printer_draw_text($handle, "  ".$salesdt_remark."\n", $x, $y);	
			$y+=12;
		}
		//printer_write($handle, "\n"); 
		$y+=12;
	} 
	}
	}
	
	$qq = "select 1 from temp_RetailDt ".
				" where temp_RetailDt.Sale_ID = '".$RetailId."' ".
			   " and ifnull(saleDt_ItemStatus,0) = 10";
    $resultdt=mysql_query($qq,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($resultdt);
	$isexists = $rows[0];


}
	    $y+=12;
		//printer_write($handle, "\n");	  
		printer_draw_text($handle, "____________________________________", $x, $y);
		$y+=12;
		/*printer_write($handle, "\n");	 
		printer_write($handle, "\n");	
		printer_write($handle, "\n");	
		printer_write($handle, "\n");	
		printer_write($handle, "\n");	
		printer_write($handle, "\n");*/
		$y+=60;
		
		//printer_draw_text($handle, chr(29).chr(86).chr(0), $x, $y);
		$y+=12;
		
		printer_delete_font($font);
		printer_end_page($handle);
		printer_end_doc($handle);
		printer_close($handle);

		
}

	  	  
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 formatDateClosing($data){
	return substr($data, 0, 4) ."-". substr($data, 5, 2) . "-". substr($data, 8, 2) . substr($data, 10, 9);
}

function RetailAutoPost($PRetId, $PCashReg, $DbName, $DbLabel, $UserAccount, $UserName, $PPostByCashReg) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");
	
	//fbegin();
	$resultvars = mysql_query("set @Result := 0, @JvResult := 0, @SaleId :=0, @SaleRef := 0, @SaleDtId := 0 ", $conn);

	$sub_query = " call Posting_RetailOneToOne('".$PCashReg."', ".$PRetId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', ".$PPostByCashReg.", @Result, @JvResult) ";
					 
	//echo $sub_query; exit;
	$sub_result = mysql_query($sub_query,$conn);
    $error = mysql_error();
	
	
	$sub_query1 = " select @Result, @JvResult from dual ";
	$sub_result1 = mysql_query($sub_query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($sub_result1);
	
	
	
	
	
    if ($cur1[0] == -5) {
	   $message = 'Error In Procedure Posting_RetailOneToOne: '.$error;
	   //frollback();
	}   
	else if ($cur1[0] == -2) {
	   $message = 'Error In Procedure Create_DeliveryAutoJv/Create_SaleAutoJv: '.$error;
	   //frollback();
	}   
	else if ($cur1[1] == -3) {
	   $message = 'Error In Procedure Create_RetailOneToOneAutoJv: '.$error;   
	  //frollback();
	}   
	else if  ($cur1[0] == -1)  {
	   $message = 'Error In Procedure Create_Jv: '.$error;   
	   //frollback();
	}   
	else if ($cur1[0] >= 0 && $cur1[1] >= 0) {
		$message = 'Posting done successfully. ';	
		//fcommit();
	}	

	return $message;
}

function RetailPostPos($PRetId, $PCashReg, $DbName, $DbLabel, $UserAccount, $UserName, $PPostByCashReg) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");
	
	fbegin();
	$resultvars = mysql_query("set @Result := 0, @JvResult := 0, @SaleId :=0, @SaleRef := 0, @SaleDtId := 0 ", $conn);

	$sub_query = " call Posting_RetailPOS(".$PRetId.", '". $PCashReg."', 0, '". $DbName."', '". $DbLabel."', '".$UserAccount."', '". $UserName."', ".$PPostByCashReg.", @Result, @JvResult) ";
					 
	//echo $sub_query; exit;
	$sub_result = mysql_query($sub_query,$conn);
    $error = mysql_error();
	
	
	$sub_query1 = " select @Result, @JvResult from dual ";
	$sub_result1 = mysql_query($sub_query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($sub_result1);
	
	
	
	
	
    if ($cur1[0] == -5) {
	   $message = 'Error In Procedure Posting_RetailPOS: '.$error;
	   frollback();
	}   
	else if ($cur1[0] == -2) {
	   $message = 'Error In Procedure Create_DeliveryAutoJv/Create_SaleAutoJv: '.$error;
	   frollback();
	}   
	else if ($cur1[1] == -3) {
	   $message = 'Error In Procedure Create_RetailAutoJv: '.$error;   
	   frollback();
	}   
	else if  ($cur1[0] == -1)  {
	   $message = 'Error In Procedure Create_Jv: '.$error;   
	   frollback();
	}   
	else if ($cur1[0] >= 0 && $cur1[1] >= 0) {
		//$message = 'Posting done successfully. ';	
		fcommit();
	}	

	return $message;
}

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

HERE;*/

function add_discount($SRetId,$txtRetCurr,$base1,$base2,$CashRegisterTTC,$txtRetDiscountAmt,$vRetAllowDisc,$txtRetDriverCode,$connection){

	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetDiscountPer = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	
	$vRetCurr         = $txtRetCurr;
	//$vRetDiscountAmt  = $txtRetDiscountAmt;
	//$vRetDiscountPer  = $txtRetDiscountPer;
	//$vRetVatAmt      = $txtRetVatAmt;
	//$vRetNetTotal    = $txtRetNetTotal;
	
	if(empty($txtAllowDisc)) $txtAllowDisc = 0;
	$vRetAllowDisc = $txtAllowDisc;
	
	
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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];
		
	
	$DiscNotAllowed = 0;
	if ($CashRegisterTTC == 1) {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		
		$sub_query = " Select ifNull(Sale_Total,0) As GrossTotal, ((ifNull(Sale_Taxable,0)* (1 + $Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0)) As GrossTotalTTC ".
					 " From Temp_Retail ".
					 " Where Sale_ID = '".$SRetId."' ";
		$sub_result = selectData($connection, $sub_query);
		$vRetGrossTotal    = $sub_result[0];	
		$vRetGrossTotalTTC = $sub_result[1];	
		
		$vRetDiscountPer  = (($txtRetDiscountAmt/$vRetGrossTotalTTC)*100);
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotal)/100);
		
	} else {
		$vRetDiscountAmt  = $txtRetDiscountAmt;
		$vRetDiscountPer  = $txtRetDiscountPer;
	}
	
	
	//Distribute The Total Discount On Detail Table
	$sub_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
				  " Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
				  " From Temp_RetailDt ".
				  " Where Sale_ID = '".$SRetId."' ".
				  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
	if ($vRetAllowDisc != 1) $sub_query3 = $sub_query3." And ifNull(Price_offer,0) = 0 ";			  
				  
	$sub_result3 = selectData($connection, $sub_query3);
	$vRetTotal   = $sub_result3[0];	
	
	if ($vRetAllowDisc == 0) {
		if ($vRetTotal == 0 || $vRetTotal == ''){
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, all items are offer.';
		}
		else if (Round(abs($vRetDiscountAmt),2) > Round(abs($vRetTotal),2)) {
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, discount amount should be less than total items amount.';
		}
	}
	
	if ( $DiscNotAllowed == 0 ){ 
		$sub_query1 = " Select SaleDt_ID,  ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_RetailDt As RetailDt  ".
					  " Where RetailDt.Sale_ID = '".$SRetId."' ".
					  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
					  
		if ($vRetAllowDisc != 1) $sub_query1 = $sub_query1." And ifNull(Price_offer,0) = 0 ";
					  
				   
		//echo $sub_query1; exit;
		$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
		while($sub_rows1=mysql_fetch_array($sub_result1)){
		
			$vRetDtId      = $sub_rows1[0];
			$vRetDtTotal   = $sub_rows1[1];
			
			
			$vRetDtDiscAmt	    = 0;
			$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
			$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
			$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
			
	
			$sub_query2 =  " UPDATE temp_retaildt SET ".
						   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
						   " Where SaleDt_ID = '".$vRetDtId."' ";
						   
						 
			//echo $sub_query2; exit;
			if (!updateData($connection, $sub_query2, true))
				$error  = mysql_error(); 
			

		}
		
			
		$sub_query3 = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
					  " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					  //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
		//echo $sub_query3;
		$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
		while($sub_rows3=mysql_fetch_array($sub_result3)){

			$vRetDtTotal  = $sub_rows3[1];
			$vItemVat     = $sub_rows3[2];
						
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ($vItemVat > 0)
				$vRetVatAmt = $vRetVatAmt + (($vRetDtTotal - $sub_rows3[4])*$vItemVat/100);
						
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $sub_rows3[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[5]/100);
				if ($vItemVat > 0 && $sub_rows3[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[6]/100);
				if ($vItemVat > 0 && $sub_rows3[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[7]/100);
				if ($vItemVat > 0 && $sub_rows3[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[8]/100);
				if ($vItemVat > 0 && $sub_rows3[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[9]/100);	
			}
						
		}			
					
					
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
					
		$vRetNetTotal         = $vRetGrossTotal + $vRetVatAmt - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;			
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVatAmt*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVatAmt*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_DiscountPer = $vRetDiscountPer, Sale_VAT = $vRetVatAmt, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2  ".
				 " ,Driver_Code = '".$txtRetDriverCode."'".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
				 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;
				
		if ( $result ){ 
					
			fcommit();
		} else
		{
		   $message  = mysql_error(); 
		   frollback();
		} 
	} 
	}
function sendmail1($Subject,$Body,$connection){

//echo 'fady'  ;exit;
 $recipients="";
	error_reporting(E_ALL);
	error_reporting(E_ALL);

	require 'PHPMailer-master/class.phpmailer.php';
	//echo 'fady1'  ;exit;
	//// Configuration
	$query_mailsetup="select hostname,mailagent,port,SenderEmail,ReceiverEmail,password from configurationemail";
	
	  //echo $query_mailsetup; exit;
	$result_mailsetup = mysql_query($query_mailsetup, $connection);
	$row_setup=mysql_fetch_row($result_mailsetup); 
		$hostname=$row_setup[0];
	
	$sender=$row_setup[3];
	$pswd = $row_setup[5];
	
	$mail = new PHPMailer;
	$mail->IsSMTP();                                      // Set mailer to use SMTP
	$mail->Host = $hostname; //'smtp.gmail.com';  // Specify main and backup server
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = $sender;                            // SMTP username
	$mail->Password = $pswd;                           // SMTP password
	$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
	$mail->From = $sender;
	$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
	$mail->Body    =  $Body;
	$mail->IsHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	$mail->SMTPDebug = 1;
	$mail->Port = $row_setup[2]; 
	
		
		
		$mail->AddAddress($recver, '');  // Add a recipient
		//$recver = $recver." $emailtech,";
			
		
	
	if(!$mail->Send()) { 
	  $error = $mail->ErrorInfo;
		//return false;	
      	 
	}

	
	return true;
}	

function calculatebases($sale_id, $base1, $base2, $Module_AdditionalTaxes, $Setup_VatStartDate, $cashregister_TaxConsumption, $cashregister_TaxConsumptionpPer, $cashregister_service, $cashregister_servicePercentage, $connection){
			 
	$query = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
			" SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ".
			" date_format(Temp_RetailDt.Sale_Date,'%Y%m%d'), Temp_RetailDt.Sale_Date, sale_serviceChecked, ifNull(Sale_DiscountPer,0), ifnull(sale_TaxConsumptionChecked,0)	 ".
			" From Temp_RetailDt ".
			" inner join temp_retail on temp_retail.sale_id = temp_retaildt.sale_id ".
			" Where Temp_RetailDt.Sale_ID = ".$sale_id.
			" And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
			
									 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){

		$vRetDtTotal  		= $rows[1];
		$vItemVat     		= $rows[2];
		$vRetQty     		= $vRetQty + $rows[3];
		$vRetDate 	  		= $rows[10];
		$vRetDate1 	  		= $rows[11]; 
		$serviceChecked 	= $rows[12]; 
		$vRetDiscount		= $rows[13]; 
		$taxConsumptionChk	= $rows[14]; 
		
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
			
				
		$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
		$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
			
			
		// Calculation of Vat Amount
		
		if (($vRetDate > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))
			$vRetVat = $vRetVat + (($vRetDtTotal - $rows[4])*$vItemVat/100);
		
							
		if ($Module_AdditionalTaxes == 1) {
			if ($vItemVat > 0 && $rows[5] != 0)
				$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $rows[4])*$rows[5]/100);
			if ($vItemVat > 0 && $rows[6] != 0)
				$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $rows[4])*$rows[6]/100);
			if ($vItemVat > 0 && $rows[7] != 0)
				$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $rows[4])*$rows[7]/100);
			if ($vItemVat > 0 && $rows[8] != 0)
				$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $rows[4])*$rows[8]/100);
			if ($vItemVat > 0 && $rows[9] != 0)
				$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $rows[4])*$rows[9]/100);	
		}
			
	}			
					
	if ($vRetTax1 == '') $vRetTax1 = 0;
	if ($vRetTax2 == '') $vRetTax2 = 0;
	if ($vRetTax3 == '') $vRetTax3 = 0;
	if ($vRetTax4 == '') $vRetTax4 = 0;
	if ($vRetTax5 == '') $vRetTax5 = 0;
	$vRetService = 0;
	$vRetTaxConsp = 0;
	$vRetDiscountAmt = 0;
	
	$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
	// Calculation of Discount Amount	
	if ($vRetDiscount > 0)
		$vRetDiscountAmt = (($vRetGrossTotal * $vRetDiscount) / 100);
		
	if (empty($vRetDiscountAmt)) $vRetDiscountAmt = 0;
	
	if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
		$vRetTaxConsp = (($vRetGrossTotal-$vRetDiscountAmt)*$cashregister_TaxConsumptionpPer/100);
	}		
	if ($cashregister_service == 1 && $serviceChecked == 1){
		$vRetService = (($vRetGrossTotal-$vRetDiscountAmt)*$cashregister_servicePercentage/100);
	}
	
	$vRetNetTotal   = $vRetGrossTotal + $vRetVat + $vRetTaxConsp + $vRetService - $vRetDiscountAmt + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;
	//echo $vRetGrossTotal ."+". $vRetVat ."+". $vRetTaxConsp ."+". $vRetService ."-". $vRetDiscountAmt."+". $vRetTax1 ."+".$vRetTax2 ."+". $vRetTax3 ."+". $vRetTax4 ."+". $vRetTax5;exit;
	
		
	$querytot = " UPDATE temp_retail SET ".
			 " Sale_Taxable = $vRetTaxable, Sale_NoneTaxable = $vRetNoneTaxable, Sale_DiscountAmount = $vRetDiscountAmt, Sale_VAT = $vRetVat, ".
			 " Sale_Total = $vRetGrossTotal, Sale_NetTotal = $vRetNetTotal, Sale_Tax1 = $vRetTax1, Sale_Tax2 = $vRetTax2, Sale_Tax3 = $vRetTax3,  ".
			 " Sale_Tax4 = $vRetTax4, Sale_Tax5 = $vRetTax5, sale_service = $vRetService, sale_TaxConsumption = $vRetTaxConsp ".
			 " WHERE Sale_ID = ".$sale_id;
	//echo $querytot;exit;	 
	$result=mysql_query($querytot,$connection);
				
	$query = "select Sale_Date,Currency_Code,sale_discountamount, sale_total, Sale_CashCur, sale_cash, sales_cashinbase1, sales_cashoutbase1,sale_vat, sale_taxable, 
			sale_nonetaxable, coupon_amount, sale_nettotal, Sales_creditacccur, sales_creditamount, sale_taxconsumption, sale_service, Sale_Tax1, Sale_Tax2,
			Sale_Tax3, Sale_Tax4, Sale_Tax5
			from temp_retail where sale_id = $sale_id "; //echo $query;exit;
	$result = mysql_query($query, $connection);
	$row = mysql_fetch_row($result);
	
	$saledisountb1 = ConvertCurrency($row[1], $base1, $row[0], $row[2], $connection);
	$saledisountb2 = ConvertCurrency($row[1], $base2, $row[0], $row[2], $connection);
	
	$saletotalb1 = ConvertCurrency($row[1], $base1, $row[0], $row[3], $connection);
	$saletotalb2 = ConvertCurrency($row[1], $base2, $row[0], $row[3], $connection);
	
	$salecashb1 = ConvertCurrency($row[4], $base1, $row[0], $row[5], $connection);
	$salecashb2 = ConvertCurrency($row[4], $base2, $row[0], $row[5], $connection);
	
	$salecashinb2 = ConvertCurrency($base1, $base2, $row[0], $row[6], $connection);
	$salecashoutb2 = ConvertCurrency($base1, $base2, $row[0], $row[7], $connection);
	
	$salevatb1 = ConvertCurrency($row[1], $base1, $row[0], $row[8], $connection);
	$salevatb2 = ConvertCurrency($row[1], $base2, $row[0], $row[8], $connection);
	
	$saletaxb1 = ConvertCurrency($row[1], $base1, $row[0], $row[9], $connection);
	$saletaxb2 = ConvertCurrency($row[1], $base2, $row[0], $row[9], $connection);
	
	$salenontaxb1 = ConvertCurrency($row[1], $base1, $row[0], $row[10], $connection);
	$salenontaxb2 = ConvertCurrency($row[1], $base2, $row[0], $row[10], $connection);
	
	$salecouponb1 = ConvertCurrency($row[1], $base1, $row[0], $row[11], $connection);
	$salecouponb2 = ConvertCurrency($row[1], $base2, $row[0], $row[11], $connection);
	
	$salenetb1 = ConvertCurrency($row[1], $base1, $row[0], $row[12], $connection);
	$salenetb2 = ConvertCurrency($row[1], $base2, $row[0], $row[12], $connection);
	
	$salecreditb1 = ConvertCurrency($row[13], $base1, $row[0], $row[14], $connection);
	$salecreditb2 = ConvertCurrency($row[13], $base2, $row[0], $row[14], $connection);
	
	$saleconsumpb1 = ConvertCurrency($row[1], $base1, $row[0], $row[15], $connection);
	$saleconsumpb2 = ConvertCurrency($row[1], $base2, $row[0], $row[15], $connection);
	
	$saleserviceb1 = ConvertCurrency($row[1], $base1, $row[0], $row[16], $connection);
	$saleserviceb2 = ConvertCurrency($row[1], $base2, $row[0], $row[16], $connection);
	
	$vRetTax1B1  = ConvertCurrency($row[1], $base1, $row[0], $row[17], $connection);
	$vRetTax1B2  = ConvertCurrency($row[1], $base2, $row[0], $row[17], $connection);
	$vRetTax2B1  = ConvertCurrency($row[1], $base1, $row[0], $row[18], $connection);
	$vRetTax2B2  = ConvertCurrency($row[1], $base2, $row[0], $row[18], $connection);
	$vRetTax3B1  = ConvertCurrency($row[1], $base1, $row[0], $row[19], $connection);
	$vRetTax3B2  = ConvertCurrency($row[1], $base2, $row[0], $row[19], $connection);
	$vRetTax4B1  = ConvertCurrency($row[1], $base1, $row[0], $row[20], $connection);
	$vRetTax4B2  = ConvertCurrency($row[1], $base2, $row[0], $row[20], $connection);
	$vRetTax5B1  = ConvertCurrency($row[1], $base1, $row[0], $row[21], $connection);
	$vRetTax5B2  = ConvertCurrency($row[1], $base2, $row[0], $row[21], $connection);
	
	$update = "update temp_retail set Sale_DiscountBase1 = $saledisountb1, Sale_DiscountBase2 = $saledisountb2,
				Sale_TotalBase1 = $saletotalb1, Sale_TotalBase2 = $saletotalb2,
				Sale_CashBase1 = $salecashb1, Sale_CashBase2 = $salecashb2,
				Sales_CashInBase2 = $salecashinb2, Sales_CashOutBase2 = $salecashoutb2,
				Sale_VATBase1 = $salevatb1, Sale_VATBase2 = $salevatb2,
				Sale_TaxableBase1 = $saletaxb1, Sale_TaxableBase2 = $saletaxb2,
				Sale_NoneTaxableBase1 = $salenontaxb1, Sale_NoneTaxableBase2 = $salenontaxb2,
				Coupon_amountbase1 = $salecouponb1, Coupon_amountbase2 = $salecouponb2,
				SALE_NETTOTALBASE1 = $salenetb1, SALE_NETTOTALBASE2 = $salenetb2,
				Sales_CreditAmountBase1 = $salecreditb1, Sales_CreditAmountBase2 = $salecreditb2,
				sale_TaxConsumptionB1 = $saleconsumpb1, sale_TaxConsumptionB2 = $saleconsumpb2,
				sale_serviceB1 = $saleserviceb1, sale_serviceB2 = $saleserviceb2
				Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  
				Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2, 
				Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  
				Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2, 
				Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2
			where sale_id = $sale_id ";
	$res = mysql_query($update,$connection);		
}

function addDiscount ($SRetId,$vRetDiscountPer,$base1,$base2,$CashRegisterTTC,$Setup_VatPercentage, $Customer_code, $connection){
	
	$vItemVat = 0;
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetVatAmt = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 0;
	$vRetNetTotal = 0;

	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	$vRetDtTax1 = 0;
	$vRetDtTax2 = 0;
	$vRetDtTax3 = 0;
	$vRetDtTax4 = 0;
	$vRetDtTax5 = 0;
		
	$vRetTax1 = 0;
	$vRetTax2 = 0;
	$vRetTax3 = 0;
	$vRetTax4 = 0;
	$vRetTax5 = 0;
	$vRetTax1B1 = 0;
	$vRetTax2B1 = 0;
	$vRetTax3B1 = 0;
	$vRetTax4B1 = 0;
	$vRetTax5B1 = 0;
	$vRetTax1B2 = 0;
	$vRetTax2B2 = 0;
	$vRetTax3B2 = 0;
	$vRetTax4B2 = 0;
	$vRetTax5B2 = 0;
	
	$vRetDtId    = '';
	$vRetDtTotal = 0;
	$vRetDtDiscAmt	    = 0;
	$vRetDtDiscAmtBase1 = 0;
	$vRetDtDiscAmtBase2 = 0;
	
	$vRetService 	  = 0;
	$vRetServiceBase1 = 0;
	$vRetServiceBase2 = 0;
	
	$vRetTaxConsp 		= 0;
	$vRetTaxConspBase1 	= 0;
	$vRetTaxConspBase2 	= 0;
	
	$query = "select ifnull(Customer_point,0), ifnull(customer_special,0) from customer where customer_code = '$Customer_code'";
	$result =mysql_query($query,$connection);
	$row = mysql_fetch_row($result);
	$Customer_point = $row[0];
	$customer_special = $row[1];
	if($Customer_point == '') $Customer_point = 0;
	if($customer_special == '') $customer_special = 0;
	if($customer_special == 0) $Customer_point = 0;
	
	$query = "select retail_salespoint from retailpoint limit 1; ";
	$result =mysql_query($query,$connection);
	$row = mysql_fetch_row($result);
	$retail_salespoint = $row[0];
	
	$query = "select Currency_code from temp_retail where sale_id = $SRetId ";
	$result =mysql_query($query,$connection);
	$row = mysql_fetch_row($result);
	$vRetCurr         = $row[0];
	//$vRetDiscountAmt  = $txtRetDiscountAmt;
	//$vRetDiscountPer  = $txtRetDiscountPer;
	//$vRetVatAmt      = $txtRetVatAmt;
	//$vRetNetTotal    = $txtRetNetTotal;
	
	if(empty($txtAllowDisc)) $txtAllowDisc = 0;
	$vRetAllowDisc = $txtAllowDisc;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRetCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRetCurr."' )";
	$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];
		
		
	$DiscNotAllowed = 0;
	
		
	$sub_query = " Select ifNull(Sale_Total,0) As GrossTotal, ((ifNull(Sale_Taxable,0)* (1 + $Setup_VatPercentage/100)) + ifNull(Sale_NoneTaxable,0)) As GrossTotalTTC ".
				 " From Temp_Retail ".
				 " Where Sale_ID = '".$SRetId."' ";
	$sub_result = selectData($connection, $sub_query);
	$vRetGrossTotal    = $sub_result[0];	
	$vRetGrossTotalTTC = $sub_result[1];	
		
	if ($CashRegisterTTC == 1){
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotalTTC)/100);	
		$vRetDiscountPer  = (($vRetDiscountAmt/$vRetGrossTotalTTC)*100);
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotal)/100);
	}
	else 
		$vRetDiscountAmt = (($vRetDiscountPer*$vRetGrossTotal)/100);	
	
	//Distribute The Total Discount On Detail Table
	$sub_query3 = " Select Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
				  " Sum((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
				  " From Temp_RetailDt ".
				  " Where Sale_ID = '".$SRetId."' ".
				  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
	if ($vRetAllowDisc != 1) $sub_query3 = $sub_query3." And ifNull(Price_offer,0) = 0 ";			  
				 
	$sub_result3 = selectData($connection, $sub_query3);
	$vRetTotal   = $sub_result3[0];	
	
	if ($vRetAllowDisc == 0) {
		if ($vRetTotal == 0 || $vRetTotal == ''){
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, all items are offer.';
		}
		else if (Round(abs($vRetDiscountAmt),2) > Round(abs($vRetTotal),2)) {
			$DiscNotAllowed = 1;
			$message = 'Discount not allowed, discount amount should be less than total items amount.';
		}
	}
	
	if ( $DiscNotAllowed == 0 ){ 
		$sub_query1 = " Select SaleDt_ID,  ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ".
					  " ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_PriceTTC,0)*ifNull(SaleDt_DiscountPer,0))/100)) As TotalTTC ".
					  " From Temp_RetailDt As RetailDt  ".
					  " Where RetailDt.Sale_ID = '".$SRetId."' ".
					  " And IfNull(RetailDt.SaleDt_ItemStatus,0) Not In (2,3) ";
					  
		if ($vRetAllowDisc != 1) $sub_query1 = $sub_query1." And ifNull(Price_offer,0) = 0 ";
					  
		$totalPt = $Customer_point;		   
		
		$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
		while($sub_rows1=mysql_fetch_array($sub_result1)){
		
			$vRetDtId      = $sub_rows1[0];
			
			if($customer_special == 1){
				if($CashRegisterTTC == 1){
					$totalPt += ($retail_salespoint*$sub_rows1[2]);
				}
				else {
					$totalPt += ($retail_salespoint*$sub_rows1[1]);
				}
			}
			$vRetDtTotal   = $sub_rows1[1];
			
			
			$vRetDtDiscAmt	    = 0;
			$vRetDtDiscAmt 	    = ($vRetDtTotal/$vRetTotal)*$vRetDiscountAmt;
			$vRetDtDiscAmtBase1 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt1;
			$vRetDtDiscAmtBase2 = ($vRetDtDiscAmt*$rate_dt)/$rate_dt2;
			
	
			$sub_query2 =  " UPDATE temp_retaildt SET ".
						   " SaleDt_DiscountAmount = $vRetDtDiscAmt, SaleDt_DiscountBase1 = $vRetDtDiscAmtBase1, SaleDt_DiscountBase2 = $vRetDtDiscAmtBase2  ".
						   " Where SaleDt_ID = '".$vRetDtId."' ";
						   
						 
			//echo $sub_query2; exit;
			if (!updateData($connection, $sub_query2, true))
				$error  = mysql_error(); 
			

		}
		//exit;
			
		$sub_query3 = " Select Item_Code, ((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0))-((ifNull(SaleDt_Quantity,0)*ifNull(SaleDt_Price,0)*ifNull(SaleDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
					  " SaleDt_Quantity, ifNull(SaleDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
					  " From Temp_RetailDt ".
					  " Where Sale_ID = '".$SRetId."' ".
					  " And IfNull(SaleDt_ItemStatus,0) Not In (2,3) ";
					  //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
		//echo $sub_query3;
		$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error());
		while($sub_rows3=mysql_fetch_array($sub_result3)){

			$vRetDtTotal  = $sub_rows3[1];
			$vItemVat     = $sub_rows3[2];
			//echo $vRetDtTotal;exit;			
			$tax_flag = 0;
			$notax_flag = 1;
			if ($vItemVat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
						
							
			$vRetTaxable     = $vRetTaxable     + ($vRetDtTotal*$tax_flag);
			$vRetNoneTaxable = $vRetNoneTaxable + ($vRetDtTotal*$notax_flag);
						
						
			// Calculation of Vat Amount
			if ($vItemVat > 0)
				$vRetVatAmt = $vRetVatAmt + (($vRetDtTotal - $sub_rows3[4])*$vItemVat/100);
						
			if ($Module_AdditionalTaxes == 1) {
				if ($vItemVat > 0 && $sub_rows3[5] != 0)
					$vRetTax1 = $vRetTax1 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[5]/100);
				if ($vItemVat > 0 && $sub_rows3[6] != 0)
					$vRetTax2 = $vRetTax2 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[6]/100);
				if ($vItemVat > 0 && $sub_rows3[7] != 0)
					$vRetTax3 = $vRetTax3 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[7]/100);
				if ($vItemVat > 0 && $sub_rows3[8] != 0)
					$vRetTax4 = $vRetTax4 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[8]/100);
				if ($vItemVat > 0 && $sub_rows3[9] != 0)
					$vRetTax5 = $vRetTax5 + (($vRetDtTotal - $sub_rows3[4])*$sub_rows3[9]/100);	
			}
						
		}		
		
		$queryChk = "select ifnull(sale_serviceChecked,0), ifnull(sale_TaxConsumptionChecked,0) from temp_retail where Sale_ID = $SRetId "; 
		$resChk = mysql_query($queryChk, $connection);
		$rowChk = mysql_fetch_row($resChk);
		$serviceChecked = $rowChk[0];
		$taxConsumptionChk = $rowChk[1];
		 
		$vRetGrossTotal = $vRetTaxable + $vRetNoneTaxable;
		
		if ($cashregister_service == 1 && $serviceChecked == 1){
			$vRetService = ((($vRetGrossTotal)-$vRetDiscountAmt)*$cashregister_servicePercentage/100);
			$vRetServiceBase1 = ($vRetService*$rate_dt)/$rate_dt1;
			$vRetServiceBase2 = ($vRetService*$rate_dt)/$rate_dt2;
		}	
		if ($cashregister_TaxConsumption == 1 && $taxConsumptionChk == 1){
			//fady stop vat
			//$vRetTaxConsp = ((($vRetGrossTotal+$vRetVatAmt)-$vRetDiscountAmt)*$cashregister_TaxConsumptionpPer/100);
			$vRetTaxConsp = ((($vRetGrossTotal)-$vRetDiscountAmt)*$cashregister_TaxConsumptionpPer/100);
			$vRetTaxConspBase1 = ($vRetTaxConsp*$rate_dt)/$rate_dt1;
			$vRetTaxConspBase2 = ($vRetTaxConsp*$rate_dt)/$rate_dt2;
		}
		
		$vRetNetTotal         = $vRetGrossTotal + $vRetVatAmt + $vRetService + $vRetTaxConsp-$vRetDiscountAmt  + $vRetTax1 + $vRetTax2 + $vRetTax3 + $vRetTax4 + $vRetTax5;			
		$vRetNetTotalBase1    = ($vRetNetTotal*$rate_dt)/$rate_dt1;
		$vRetNetTotalBase2    = ($vRetNetTotal*$rate_dt)/$rate_dt2;
		$vRetTaxableBase1     = ($vRetTaxable*$rate_dt)/$rate_dt1;
		$vRetTaxableBase2     = ($vRetTaxable*$rate_dt)/$rate_dt2;
		$vRetNoneTaxableBase1 = ($vRetNoneTaxable*$rate_dt)/$rate_dt1;
		$vRetNoneTaxableBase2 = ($vRetNoneTaxable*$rate_dt)/$rate_dt2;
		$vRetDiscountAmtBase1 = ($vRetDiscountAmt*$rate_dt)/$rate_dt1;
		$vRetDiscountAmtBase2 = ($vRetDiscountAmt*$rate_dt)/$rate_dt2;
		$vRetGrossTotalBase1  = ($vRetGrossTotal*$rate_dt)/$rate_dt1;
		$vRetGrossTotalBase2  = ($vRetGrossTotal*$rate_dt)/$rate_dt2;
		$vRetVatBase1         = ($vRetVatAmt*$rate_dt)/$rate_dt1;
		$vRetVatBase2         = ($vRetVatAmt*$rate_dt)/$rate_dt2;
				

		$vRetTax1B1  = ($vRetTax1*$rate_dt)/$rate_dt1;
		$vRetTax1B2  = ($vRetTax1*$rate_dt)/$rate_dt2;		
		$vRetTax2B1  = ($vRetTax2*$rate_dt)/$rate_dt1;
		$vRetTax2B2  = ($vRetTax2*$rate_dt)/$rate_dt2;		
		$vRetTax3B1  = ($vRetTax3*$rate_dt)/$rate_dt1;
		$vRetTax3B2  = ($vRetTax3*$rate_dt)/$rate_dt2;		
		$vRetTax4B1  = ($vRetTax4*$rate_dt)/$rate_dt1;
		$vRetTax4B2  = ($vRetTax4*$rate_dt)/$rate_dt2;		
		$vRetTax5B1  = ($vRetTax5*$rate_dt)/$rate_dt1;
		$vRetTax5B2  = ($vRetTax5*$rate_dt)/$rate_dt2;	
					
					 
		fbegin();			 
		$query = " UPDATE temp_retail SET ".
				 " Sale_Taxable = $vRetTaxable, Sale_TaxableBase1 = $vRetTaxableBase1, Sale_TaxableBase2 = $vRetTaxableBase2, ".
				 " Sale_NoneTaxable = $vRetNoneTaxable, Sale_NoneTaxableBase1 = $vRetNoneTaxableBase1, Sale_NoneTaxableBase2 = $vRetNoneTaxableBase2, ".
				 " Sale_DiscountAmount = $vRetDiscountAmt, Sale_DiscountBase1 = $vRetDiscountAmtBase1, Sale_DiscountBase2 = $vRetDiscountAmtBase2, ".
				 " Sale_DiscountPer = $vRetDiscountPer, Sale_VAT = $vRetVatAmt, Sale_VATBase1 = $vRetVatBase1, Sale_VATBase2 = $vRetVatBase2, ".
				 " Sale_Total = $vRetGrossTotal, Sale_TotalBase1 = $vRetGrossTotalBase1, Sale_TotalBase2 = $vRetGrossTotalBase2, ".
				 " Sale_NetTotal = $vRetNetTotal, Sale_NetTotalBase1 = $vRetNetTotalBase1, Sale_NetTotalBase2 = $vRetNetTotalBase2, ".
				 " Sale_Tax1 = $vRetTax1, Sale_Tax1Base1 = $vRetTax1B1, Sale_Tax1Base2 = $vRetTax1B2,  ".
				 " Sale_Tax2 = $vRetTax2, Sale_Tax2Base1 = $vRetTax2B1, Sale_Tax2Base2 = $vRetTax2B2,  ".
				 " Sale_Tax3 = $vRetTax3, Sale_Tax3Base1 = $vRetTax3B1, Sale_Tax3Base2 = $vRetTax3B2,  ".
				 " Sale_Tax4 = $vRetTax4, Sale_Tax4Base1 = $vRetTax4B1, Sale_Tax4Base2 = $vRetTax4B2,  ".
				 " Sale_Tax5 = $vRetTax5, Sale_Tax5Base1 = $vRetTax5B1, Sale_Tax5Base2 = $vRetTax5B2,  ".
				 " Driver_Code = '".$txtRetDriverCode."',Discount_user = '".$discount_user."', ".
				 " sale_service = $vRetService, sale_serviceB1 = $vRetServiceBase1, sale_serviceB2 = $vRetServiceBase2, sale_serviceChecked = $serviceChecked, ".
				 " sale_TaxConsumption = $vRetTaxConsp, sale_TaxConsumptionB1 = $vRetTaxConspBase1, sale_TaxConsumptionB2 = $vRetTaxConspBase2, ".
				 " sale_TaxConsumptionChecked = $taxConsumptionChk, sale_customerAwardPt = round($totalPt), sale_customerDiscount = $vRetDiscountPer ".
				 " WHERE Sale_ID = ".$SRetId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		//echo $query."<br>";exit;			 
				 
		$result=mysql_query($query,$connection);
		
				
		if ( $result ){ 
					
			fcommit();
		} else
		{
		   $message  = mysql_error(); 
		   frollback();
		} 
	} 	
}

function adjustCustomerAwardPoints($SRetId, $connection){
	$queryCust = "select customer_code, ifnull(collected_points,0) from redeemPoints where retail_id = '$SRetId'";
	$resCust = mysql_query($queryCust, $connection);
	$numCust = mysql_num_rows($resCust);
	$rowCust = mysql_fetch_row($resCust);
	$preCustomer = $rowCust[0];
	$preAwardPts = $rowCust[1];
	
	$queryRetail = "select retail.customer_code, Sale_Date, ifnull(sale_customerAwardPt,0) as collectedPts, ifnull(sale_customerRedeemedPt,0) as redeemedPts
					from retail
					inner join customer on customer.customer_code = retail.customer_code
					where sale_id = '$SRetId' and ifnull(customer_special,0) = 1 ";
	$resRetail = mysql_query($queryRetail, $connection);
	$numRetail = mysql_num_rows($resRetail);
	$rowRetail = mysql_fetch_row($resRetail);
	$current_customer = $rowRetail[0];
	$Sale_Date = $rowRetail[1];
	$collectedPts = $rowRetail[2];
	$redeemedPts = $rowRetail[3];
	
	
	if( $numCust == 0 && $numRetail > 0 ){
		$queryins = "insert into redeemPoints (customer_code, redeem_date, collected_points, redeemed_points, retail_id) values 
					('".$current_customer."', '".$Sale_Date."', ".$collectedPts.", ".$redeemedPts.", ".$SRetId." );";
		$resins = mysql_query($queryins, $connection);
	}
	
	if( $numCust > 0 && $numRetail > 0 ){
		$queryup = "update redeemPoints set customer_code = '".$current_customer."', redeem_date = '".$Sale_Date."',
					collected_points = ".$collectedPts.", redeemed_points = ".$redeemedPts."
					where retail_id = ".$SRetId." ";
		$resup = mysql_query($queryup,$connection);	
		if($preCustomer != $current_customer){
			$upcustomer = "update customer set Customer_point = '$preAwardPts' where customer_code = '".$preCustomer."' ";
			$rescustomer = mysql_query($upcustomer,$connection);
		}		
	}
	
	if( $numRetail > 0 ){
		$customerPt = $collectedPts - $redeemedPts;
		$upcustomer = "update customer set Customer_point = '$customerPt' where customer_code = '".$current_customer."' ";
		$rescustomer = mysql_query($upcustomer,$connection);
	}
		
	
	
}

?>