<?php

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


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

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

//User Access
$querylog=" select ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(login_belongstogrp,0) As FI_BelongsToGrp ".
          " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
							

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

//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_PriceOffer,0) As Module_PriceOffer  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, ".
                   " CashRegister_SerialNo, CashRegister_Discount, CashRegisterTTC, Client_Account As StpClientAccount, Warehouse_Code As StpWarehouseCode, ifNull(CashReg_Vendor,0) As CashReg_Vendor,  ".
				   " ifNull(CashRegister_RestSerialNo,0) As CashRegister_RestSerialNo ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}


$Mode		  = $_GET['Mode']; if ($Mode == ""){$Mode = $_POST["Mode"];}
$PerPage 	  = $_GET['PerPage'];if ($PerPage == ""){$PerPage = $_POST["PerPage"];}
$SerialId 	  = $_GET['SerialId'];if ($SerialId == ""){$SerialId = $_POST["SerialId"];}
$ItemReturn   = $_GET['ItemReturn'];if ($ItemReturn == ""){$ItemReturn = $_POST["ItemReturn"];}
$ItemSerialNo = $_GET['ItemSerialNo'];if ($ItemSerialNo == ""){$ItemSerialNo = $_POST["ItemSerialNo"];}

$PRetId 	= $_GET["PRetId"]; if ($PRetId == ""){$PRetId = $_POST["PRetId"];}   
$PRetDate 	= $_GET["PRetDate"]; if ($PRetDate == ""){$PRetDate = $_POST["PRetDate"];}   
$PRetCurr 	= $_GET["PRetCurr"]; if ($PRetCurr == ""){$PRetCurr = $_POST["PRetCurr"];}   
$PRetCashRegister 	= $_GET["PRetCashRegister"]; if ($PRetCashRegister == ""){$PRetCashRegister = $_POST["PRetCashRegister"];}   
$PRetClientCode 	= $_GET["PRetClientCode"]; if ($PRetClientCode == ""){$PRetClientCode = $_POST["PRetClientCode"];}   
$PRetProjectCode 	= $_GET["PRetProjectCode"]; if ($PRetProjectCode == ""){$PRetProjectCode = $_POST["PRetProjectCode"];}   
$PRetCostCentCode 	= $_GET["PRetCostCentCode"]; if ($PRetCostCentCode == ""){$PRetCostCentCode = $_POST["PRetCostCentCode"];}   

$txtVendorCode = $_GET["txtVendorCode"]; if ($txtVendorCode == ""){$txtVendorCode = $_POST["txtVendorCode"];}   
$txtSlipNo 	   = $_GET["txtSlipNo"]; if ($txtSlipNo == ""){$txtSlipNo = $_POST["txtSlipNo"];}   

	
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='additemserials' method='post' action=''>
<input type='hidden' name='ItemSerialNo' id='ItemSerialNo' value='$ItemSerialNo' size='10' maxlength='40'/>
<input type='hidden' name='ItemReturn' id='ItemReturn' value='$ItemReturn' size='10' maxlength='40'/>
<input type='hidden' name='SerialId' id='SerialId' value='$SerialId' size='10' maxlength='40'/>
<input type='hidden' name='RetId' id='RetId' value='$RetId' size='10' maxlength='40'/>
<input type='hidden' name='PerPage' id='PerPage' value='$PerPage' size='10' maxlength='40'/>
<input type='hidden' name='Mode' id='Mode' value='$Mode' size='10' maxlength='40'/>		    
HERE;

$vRetId   = $RetId;
$vRetDate = $PRetDate;
$vRetCurr = $PRetCurr;
$vRetCostCentCode = $PRetCostCentCode;
$vRetProjectCode  = $PRetProjectCode;
$vRetCashRegister = $PRetCashRegister;
$vRetClientCode   = $PRetClientCode;
		
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."'";   
	
$vWarehouseCode = $StpWarehouseCode;
		
$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 == 'insert' && $ItemSerialNo != '') {
	
	if ($CashRegister_RestSerialNo == 1) { 

		if ($ItemReturn == 0) {
			$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
					" From purchasesserialno ".
					" where SerialNo_Code =  '".$ItemSerialNo."' ".
					" And Journal_Type in ('PI','DR','TR','AI','PD')";
		} else {			
			$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
					" From purchasesserialno ".
					" where SerialNo_Code =  '".$ItemSerialNo."' ".
					" And Journal_Type in ('PI','DR','TR','AI','PD') ".
					" And Warehouse_Code =  '".$vWarehouseCode."' ".
					" And ifNull(SerialNo_Used,0) = 0 ";
		}		
		//echo $query; exit;		  
		$result = selectData($connection, $query);
		$SerialNoExists = $result[0];
		
		$IsAvailable = 1;
		$ErrorExists = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		$SelectedItemCode      = '';
		
		if ($ItemReturn == 0 && $SerialNoExists != '') {
			if ($vWarehouseCode != '' && isset($vWarehouseCode)) {
			
				$sub_query= " Select SerialNo_Code  ".
							" From temp_purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$vWarehouseCode."' ".
							" And Journal_Type in ('DI') ".
							" And ifNull(flagunique, 0) = 0  ".
							" Union ".
							" Select SerialNo_Code  ".
							" From Purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" 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 =  '".$ItemSerialNo."' ".
								" 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 =  '".$ItemSerialNo."' ".
								" 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 (".$ItemSerialNo.") 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 =  '".$ItemSerialNo."' ".
										" 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 (".$ItemSerialNo.") 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 if ($ItemReturn == 1 && $SerialNoExists == ''){
			$sub_query= " Select *  ".
						" From temp_purchasesserialno ".
						" where SerialNo_Code =  '".$ItemSerialNo."' ".
						" And Warehouse_Code =  '".$vWarehouseCode."' ".
						" And Journal_Type in ('DR')";
			//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 Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0), Item_Code  ".
							" From purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$vWarehouseCode."' ".
							" And ifNull(SerialNo_Used,0) = 0 ".
							" And Journal_Type in ('PR','DI','TR','AR','PDT')";
				$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 (".$ItemSerialNo.") 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 {
				$IsAvailable = 0;
				$message  = "Insert not allowed, serial no. is invoiced. "; 
			}
			
		}
		else if ($ItemReturn == 1 && $SerialNoExists != ''){
			$IsAvailable = 0;
			$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") already exists in the warehouse (".$vWarehouseCode."). "; 
		}
		else if ($ItemReturn == 0 && $SerialNoExists == ''){
			$IsAvailable = 0;
			$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available. "; 
		}
	
	} else {
		$IsAvailable = 1;
		$SelectedSerialID 	   = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
	
		$sub_query= " Select Item_Code  ".
					" From purchasesserialno ".
					" where SerialNo_Code =  '".$ItemSerialNo."' ";
		$sub_result = selectData($connection, $sub_query);
		$SelectedItemCode = $sub_result[0];								
	
	}

	if ($IsAvailable == 1)
	{
		
	
		$vRetDtQty = 0;
		$vRetDtTotal = 0;
		$vItemVat = 0;
		$vItemPrice = 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;
		
		$ItemNotFound = 0;
		$QtyExistExceeded  = 0;
		
				
		//Insert Master Table
		if ($vRetId == ""){
		
			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);
			
				 
			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, User_Account, Logged_Code ) ".
					 " VALUES ( ".$vRetId.", Null, '".insertMySQLDate($vRetDate)."', '".$Ledger_Result[0]."', '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetCurr."', $ProjectCode, $CostCentCode, '".$vRetCashRegister."', ".
					 "          0, 0, 0, 0, 0, 0, 0, 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, '".$Acc_Result1[6]."', '".$Acc_Result1[5]."', Null, Null, '".$_SESSION['useraccount']."', ".
					 "          '".$_SESSION['useraccount']."' )";
						 
				 
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
			
			if ($result){
				fcommit();
			}else{
				$vRetId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
			
	
		
		}
		
		if ($vRetId != "" )
		{
			if (empty($txtVendorCode))
			   $txtVendorCode = '';    
			if (empty($txtSlipNo))
			   $txtSlipNo = ''; 
			   
			if ($ItemReturn == 0) $vRetDtType = 'RI';
			else $vRetDtType = 'RR';
				
			$sub_query = " Select SaleDt_ID, Item_Code, ifNull(SaleDt_Quantity,0) ".
						 " From Temp_RetailDt ".
						 " Where Item_Code = '".$SelectedItemCode."' ".
						 " And Journal_Type = '".$vRetDtType."' ".
						 " And Sale_ID = '".$vRetId."'";
			$sub_result = selectData($connection, $sub_query);
				
			$vRetDtId = $sub_result[0];
				
			if ($vRetDtId == "" )
			{
				$vRetDtItemCode = $SelectedItemCode;
				$vRetDtQty      = $SelectedSerialQty;
				$vWarehouseCode = $StpWarehouseCode;
				
				if ($ItemReturn == 1) $vRetDtQty = (-1)*$vRetDtQty;
				
				$sub_query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$vRetClientCode."'";
				//echo "<br><br>".$sub_query;exit;
				$sub_result = selectData($connection, $sub_query);
				$c_sp = $sub_result[0];
					
				$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_Pack, 0), ".
							 " ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice2,0), ifNull(Item_SellingPrice3,0), ifNull(Item_SellingPrice4,0), ifNull(Item_SellingPrice5,0), ifNull(Item_SellingPrice6,0), ".
							 " Item_Code, Item_Barcode, Currency_Code ".
							 " FROM Items WHERE Item_Code = '".$vRetDtItemCode."'";
				
				$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];
				$ItemSellPrice = $sub_result[7];
				$ItemCurr      = $sub_result[15];
				$ItemBarcode   = $sub_result[14];
				
				if (empty($sub_result))
					$ItemNotFound = 1;
					
				
				$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);
				
				switch ($c_sp){
					case "II":
						$ItemSellPrice = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $sub_result[8], $connection); break;
					case "III":
						$ItemSellPrice = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $sub_result[9], $connection); break;
					case "IV":
						$ItemSellPrice = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $sub_result[10], $connection); break;
					case "V":
						$ItemSellPrice = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $sub_result[11], $connection); break;
					case "VI":
						$ItemSellPrice = ConvertCurrency($ItemCurr, $vRetCurr, insertMySQLDate($vRetDate), $sub_result[12], $connection); break;
				}
		
				
				if ($Module_PriceOffer == 0) {
					$vRetDtPriceOffer = 0;	
					$vItemPrice = $ItemSellPrice;
					
				} else {
					if ($Module_PriceOffer == 1) {
						// Item Selling Price 1
						if ($sub_result[7] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[7];
						}
					}	
					else if ($Module_PriceOffer == 2) {
						// Item Selling Price 2
						if ($sub_result[8] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[8];
						}
					}
					else if ($Module_PriceOffer == 3) {
						// Item Selling Price 3
						if ($sub_result[9] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[9];
						}
					}
					else if ($Module_PriceOffer == 4) {
						// Item Selling Price 4
						if ($sub_result[10] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[10];
						}
					}
					else if ($Module_PriceOffer == 5) {
						// Item Selling Price 5
						if ($sub_result[11] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[11];
						}
					}
					else if ($Module_PriceOffer == 6) {
						// Item Selling Price 6
						if ($sub_result[12] == 0) { 
							$vRetDtPriceOffer = 0; 
							if($vItemPrice == 0) $vItemPrice = $ItemSellPrice;
						} else {
							$vRetDtPriceOffer = 1; 
							$vItemPrice = $sub_result[12];
						}
					}
				}
					
					

				if ($ItemNotFound == 0) {		
		
					// Case Not Pack Item
					if ($ItemPack == 0) {
					
						$sub_query1  = " Select QtyExistsWSorder_Temp('".$vRetDtItemCode."', '".$vWarehouseCode."', '".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 = '".$vRetDtItemCode."'  And  Warehouse_code = '".$vWarehouseCode."' And Sale_ID = $vRetId And SaleDt_ID != ifNull('".$vRetDtId."',0) ";	
						$sub_result2 = selectData($connection, $sub_query2);
						$min_available_qty = $min_available_qty - $sub_result2[0];
						
						if ($vRetDtQty > $min_available_qty && $vRetDtQty > 0)
							$QtyExistExceeded = 1;
						
						if ($QtyExistExceeded == 0 || ($QtyExistExceeded == 1 && $Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
											
							if ($CashRegisterTTC == 1) {
								$vRetDtPriceTTC      = $vItemPrice;
								$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      = $vItemPrice;
								$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
								$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
									
								$vRetDtPriceTTC      = 0;
								$vRetDtPriceTTCBase1 = 0;
								$vRetDtPriceTTCBase2 = 0;
											
							}	
									
							
							

							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 = '".$vRetDtItemCode."'";
														 
								$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 Temp_RetailDt ".
										  " WHERE Item_code = '".$vRetDtItemCode."'  ".
										  " And Journal_Type = '".$vRetDtType."' ".
										  " And SaleDt_Price = $vRetDtPrice ".
										  " And Sale_ID = $vRetId  ";	
							$sub_result3 = selectData($connection, $sub_query3);
							$ItemExists = $sub_result3[0];
							if (empty($ItemExists)) $ItemExists = 0;
							
							if ($ItemExists == 0) {
								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, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Vendor_Code, Slip_number, Price_offer, SerialNo_Code, Logged_Code ) ".
										 " VALUES ( ".$vRetDtId.", ".$vRetId.", '".$vRetCurr."', '".insertMySQLDate($vRetDate)."', '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetDtType."', $ProjectCode, $CostCentCode, '".$vWarehouseCode."', ".
										 "          '".$vRetDtItemCode."', '".$ItemBarcode."', Null, $ItemVat, $vRetDtQty, $vRetDtPrice, $vRetDtPriceBase1, $vRetDtPriceBase2, 0, 0, 0, 0, $vRetDtPriceTTC, ".
										 "          $vRetDtPriceTTC, $vRetDtPriceTTCBase1, $vRetDtPriceTTCBase2, Null, 0, '".$vRetDtDirectStkDbt."', '".$vRetDtDirectStkCrd."', '".$vRetDtDirectStkCur."', '".$vRetDtDiscAcc."', ".
										 "          '".$vRetDtItemAcc."', '".$vRetDtPromoAcc."', $vRetDtTax1, $vRetDtTax2, $vRetDtTax3, $vRetDtTax4, $vRetDtTax5, '".$txtVendorCode."', '".$txtSlipNo."', $vRetDtPriceOffer,  ".
										 "          '".$ItemSerialNo."', '".$_SESSION['useraccount']."' ) ";
							} else {
								$query = " UPDATE temp_retaildt SET ". 
										 " SaleDt_Quantity = ifNull(SaleDt_Quantity,0) + $vRetDtQty, ".
										 " Vendor_Code = '".$txtVendorCode."', Slip_number = '".$txtSlipNo."' ".
										 " WHERE Item_code = '".$vRetDtItemCode."'  And SaleDt_Price = $vRetDtPrice And Sale_ID = $vRetId  And Journal_Type = '".$vRetDtType."' ";

							}	
							//echo $query."<br>";exit;				
							$result=mysql_query($query,$connection);
							
							

									
							if ($result){
								fbegin();
								$vSerId = get_nextsequence('Serial_Id','',$connection);	
								fcommit();
								
								if ($vRetDtType == 'RI') $vSerType = 'DI';
								else if ($vRetDtType == 'RR') $vSerType = 'DR';
					
								$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, '".$vRetDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$vWarehouseCode."', '".$_SESSION['useraccount']."' ) ";
		
								$result=mysql_query($query,$connection);
												
								if ($result){
									$ErrorExists = 0;
									
									$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
									fcommit();
								} else {
									$ErrorExists = 1;
									$message  = mysql_error(); 
									frollback();
								}
								
							}else{
								$ErrorExists = 1;
								$vRetDtId = "";
								$message  = mysql_error(); 
								frollback();
							}	
						} else {
							$ErrorExists = 1;
							$vRetDtId = "";
							$message  = "Qty[$vRetDtQty] exceeds Existing Qty[$min_available_qty] for Item (".$vRetDtItemCode.")"; 
						}	
						
						
					}	// 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 = '".$vRetDtItemCode."'  ";
											   
						$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 = '".$vItemCodePacked."' ".
												 " 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] + $vRetDtQty*$vPackDtQty)){
										$promo_exhausted = 1;
									}
								}else{
									$promo_exhausted = 1;
								}
							
							}
							
							$sub_query1  = " Select QtyExistsWSorder_Temp('".$vItemCode."', '".$vWarehouseCode."', '".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 = '".$vWarehouseCode."' And Sale_ID = $vRetId And SaleDt_ID != ifNull('".$vRetDtId."',0) ";	
							$sub_result2 = selectData($connection, $sub_query2);
							$min_available_qty = $min_available_qty - $sub_result2[0];
								
							if ($vRetDtQty*$vPackDtQty > $min_available_qty && $vRetDtQty > 0) {
								$QtyExistExceeded = 1;
								$message  = "Qty[$vRetDtQty*$vPackDtQty] exceeds Existing Qty[$min_available_qty] for Item (".$vItemCode.")"; 
							}	
							
							if ($promo_exhausted == 1) break;
							if ($QtyExistExceeded == 1) break;
						}		
						
						fbegin();
						if ($promo_exhausted == 0 && ($QtyExistExceeded == 0  || ($QtyExistExceeded == 1 && $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 = '".$vRetDtItemCode."'  ";
											   
							$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();

								$vRetDtQty1 = $vRetDtQty*$vPackDtQty;
									
									
										
								$query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), Item_Barcode ".
										 " 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];
								
								$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;

									
								if ($CashRegisterTTC == 1) {
									$vRetDtPriceTTC      = (($vItemPrice*$vPackDtCostPer/100)/$vPackDtQty);
									$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      = (($vItemPrice*$vPackDtCostPer/100)/$vPackDtQty);
									$vRetDtPriceBase1 = ($vRetDtPrice*$rate_dt)/$rate_dt1;
									$vRetDtPriceBase2 = ($vRetDtPrice*$rate_dt)/$rate_dt2;
												
									$vRetDtPriceTTC      = 0;
									$vRetDtPriceTTCBase1 = 0;
									$vRetDtPriceTTCBase2 = 0;
												
								}
											
										

								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;	
								}
									
						
						 
								$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, Logged_Code ) ".
										 " VALUES ( ".$vRetDtId.", ".$vRetId.", '".$vRetCurr."', '".insertMySQLDate($vRetDate)."', '".ereg_replace("'", "\'", trim($vRetClientCode))."', '".$vRetDtType."', $ProjectCode, $CostCentCode, '".$vWarehouseCode."', ".
										 "          '".$vItemCode."', '".$ItemBarcode."', '".$vItemCodePacked."', $ItemVat, $vRetDtQty1, $vRetDtPrice, $vRetDtPriceBase1, $vRetDtPriceBase2, 0, 0, 0, 0, $vRetDtPriceTTC, ".
										 "          $vRetDtPriceTTC, $vRetDtPriceTTCBase1, $vRetDtPriceTTCBase2, Null, 0, '".$vRetDtDirectStkDbt."', '".$vRetDtDirectStkCrd."', '".$vRetDtDirectStkCur."', '".$vRetDtDiscAcc."', ".
										 "          '".$vRetDtItemAcc."', '".$vRetDtPromoAcc."', $vRetDtTax1, $vRetDtTax2, $vRetDtTax3, $vRetDtTax4, $vRetDtTax5, '".$txtVendorCode."', '".$txtSlipNo."', $vRetDtPriceOffer,  ".
										 "          '".$_SESSION['useraccount']."' ) ";
						
						
								$result=mysql_query($query,$connection);
												
								//echo $query;
								
							} // End Loop Of Packdt
							

											
							if ($result){
								$ErrorExists = 0;
								fcommit();
							}else{
								$ErrorExists = 1;
								$vRetDtId = "";
								$message  = mysql_error(); 
								frollback();
							}	
						} else{
							$ErrorExists = 1;
							$vRetDtId = "";
							
							if ($promo_exhausted == 1)  
								$message = $message . "<br>Item ".$vRetDtItemCode." COULD NOT be Added. Promo Qty / Period Exhausted";
							if ($QtyExistExceeded == 1)
								$message = $message;
							
							frollback();
						}
						
					} // End CasePack Item
					
					
	
				} else {
					$message  = 'Item Not Found.'; 
				
				}	
				
			} 
			else { //Case Item Exists
			
				$vRetDtItemCode = $sub_result[1];
				$vRetDtQty      = $sub_result[2];
				$vWarehouseCode = $StpWarehouseCode;
				
				if ($ItemReturn == 0) $vRetDtQty = $vRetDtQty + 1; 
				else $vRetDtQty = $vRetDtQty - 1;
	
	
				fbegin();
				$query = " UPDATE temp_retaildt SET ". 
						 " SaleDt_Quantity = $vRetDtQty, ".
						 " Vendor_Code = '".$txtVendorCode."', Slip_number = '".$txtSlipNo."' ".
						 " WHERE SaleDt_Id = '".$vRetDtId."' ";
										 
				//echo $query."<br>";exit;				
				$result=mysql_query($query,$connection);
						
				if ($result){
					fbegin();
					$vSerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
				
					if ($vRetDtType == 'RI') $vSerType = 'DI';
					else if ($vRetDtType == 'RR') $vSerType = 'DR';
					
					$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, '".$vRetDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$vWarehouseCode."', '".$_SESSION['useraccount']."' ) ";
										 
					$result=mysql_query($query,$connection);
											
					if ($result){
						$ErrorExists = 0;
						
						$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
						fcommit();
					} else {
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}
							
				} else {
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
					
			} //End Case Item Exists
			
			
			

		
			
		} //End if ($RetId != "" )
		
		
	} //End Case IsAvailable = True
} //End Case Insert

if ($Mode == 'delete' && $SerialId != '') {
	
	$ErrorExists = 0;
	$IsAvailable = 1;
	
	$query = " SELECT SerialNo_Code, ifNull(SerialNo_Used, 0) As SerialNo_Used, ifNull(PurchaseDt_ID, RetailDt_ID) ".
			 " From temp_purchasesserialno ".
	         " WHERE Serial_ID = ".$SerialId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	$result = selectData($connection, $query);
	$SerialNoCode      = $result[0];
	$SerialNoUsed      = $result[1];
	$SerialRetailDt_Id = $result[2];
	
	if ($SerialNoUsed == 0) {
		fbegin();
		
		$query = " DELETE from temp_purchasesserialno ".
				 " WHERE Serial_ID = ".$SerialId.
				 //" AND Logged_Code = '".$_SESSION['useraccount']."' ".
				 " AND ifNull(SerialNo_Used, 0) = 0  ";
		
		$result=mysql_query($query,$connection);
			
		if ($result){
			$message = "Delete serial no (".$SerialNoCode.") done successfully.";
			
			if ($ItemReturn == 0) {
				$query = " UPDATE temp_retaildt SET ". 
						 " SaleDt_Quantity = (ifNull(SaleDt_Quantity,0) - 1), ".
						 " SerialNo_Code = Null ".
						 " WHERE SaleDt_Id = '".$SerialRetailDt_Id."' ";
			} else	{
				$query = " UPDATE temp_retaildt SET ". 
						 " SaleDt_Quantity = (ifNull(SaleDt_Quantity,0) + 1), ".
						 " SerialNo_Code = Null ".
						 " WHERE SaleDt_Id = '".$SerialRetailDt_Id."' ";
			}
					 
			//echo $query."<br>";exit;				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	
			
			$query = " Select ifNull(SaleDt_Quantity,0) From temp_retaildt ".
					 " WHERE SaleDt_Id = '".$SerialRetailDt_Id."' ";
			$result = selectData($connection, $query);
			$ItemQtyRem = $result[0];
			
			if (empty($ItemQtyRem)) $ItemQtyRem = 0;
			if ($ItemQtyRem == 0) {
			    $query = " DELETE FROM Temp_RetailDt ".
						 " WHERE SaleDt_id = '".$SerialRetailDt_Id."'";
			
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
			}


			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}			
	} 
	else {	
		$ErrorExists = 1;
		$message  = "Delete not allowed, Serial No ".$SerialNoCode." is used. "; 
	}	
}

// Update Amount Columns In Retail Table
if ($ErrorExists == 0 && $IsAvailable == 1 && $vRetId != '') {
	
	$vRetTaxable = 0;
	$vRetNoneTaxable = 0;
	$vRetGrossTotal = 0;
	$vRetDiscountAmt = 0;
	$vRetVat = 0;
	$vRetVatBase1 = 0;
	$vRetVatBase2 = 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;
		
	$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 = '".$vRetId."' ";
	$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 = '".$vRetId."' ".
					  " And ifNull(Price_offer,0) = 0 ";
		$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 = '".$vRetId."' ".
					  " And ifNull(Price_offer,0) = 0 ";

		//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 = ".$vRetId;
			 //" 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;
					
	$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 = ".$vRetId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
							 
					 
	$result=mysql_query($query,$connection);
	//echo $query."<br>";exit;
				
	if ($result){
		fcommit();
	}else{
		$message  = mysql_error(); 
		frollback();
	}	
				
}

$message = ereg_replace(' ','%20',$message);

header ( "Location: ./Form_RetailAddSerial.php?PRetId=".$vRetId."&PRetDate=".$vRetDate."&PRetCurr=".$vRetCurr.	
		 "&PRetCashRegister=".$vRetCashRegister."&PRetClientCode=".$vRetClientCode."&PSaSalesmanCode=".$PSaSalesmanCode.
		 "&PRetProjectCode=".$vRetProjectCode."&PRetCostCentCode=".$vRetCostCentCode."&txtSlipNo=".$txtSlipNo.
		 "&txtVendorCode=".$txtVendorCode."&txtItemReturn=".$ItemReturn."&perpage=".$PerPage."&message=".$message );

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

}


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

HERE;

?>