<?php

session_start();



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

include("config.inc.php");
include("Functions_Retail.php");
include("function.inc.php");
include("Functions_Synchro.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");


//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 ".
			 " 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 ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
             " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, 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);
}

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

	
//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 ".
			 " 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(Module_RestaurantDelivery,0) As Module_RestaurantDelivery".
				   " 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 ".
          " 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);
}
//echo $querylog;

$mode		 = $_GET['mode']; if ($mode == ""){$mode = $_POST["mode"];}
$mainmode 	 = $_GET['mainmode'];if ($mainmode == ""){$mainmode = $_POST["mainmode"];}
$SRetId 	 = $_GET['SRetId'];if ($SRetId == ""){$SRetId = $_POST["SRetId"];}
$projectdtid 	 = $_GET['projectdtid'];if ($projectdtid == ""){$projectdtid = $_POST["projectdtid"];}
$selecteddt 	 = $_GET['selecteddt'];if ($selecteddt == ""){$selecteddt = $_POST["selecteddt"];}





if($mode=='combine'){

ShowOrders($SRetId,$connection);

}
if($mode=='split'){

ShowOrders_Split($SRetId,$connection);

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


if($SToRetId == '') {
	if ((empty($txtProjectCode)) && $Module_Project == 1)
		$txtProjectCode = $StpProjectCode;
	if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)	
		$txtCostCentCode = $StpCostCentCode;	
	if (empty($txtCurr))
		$txtCurr = $StpCurrCode;
	if (empty($txtDate))	
		$txtDate = displayToday();
	if (empty($txtCashRegister))	
		$txtCashRegister = $CashRegister_Name;
	if (empty($txtClientCode))	
		$txtClientCode = $StpClientAccount;	

	
	    $vRetDate = displayToday();
		$vRetCurr = $txtCurr;
		$vRetCostCentCode = $txtCostCentCode;
		$vRetProjectCode  = $txtProjectCode;
		$vRetCashRegister = $txtCashRegister;
		$vRetClientCode   = $txtClientCode;
		$vRetOrderId = '';
	
	
	if (!isset($vRetCurr))	   $vRetCurr = $StpCurrCode;
	if (!isset($vRetCurr))	   $vRetCurr = $base1;   
	   
	if (empty($vRetCostCentCode) && $vRetCostCentCode != 0)
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$vRetCostCentCode."'";
			
	if (empty($vRetProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$vRetProjectCode."'";   

	echo"<BR>".$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
	 
	
			
		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 = 'Null';
		if (empty($vRetDriverCode))   $vRetDriverCode = 'Null';
		if (empty($ProjectDtId))   	  $ProjectDtId = 'Null';
		
		$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($vRetCustomerDisc == '') $vRetCustomerDisc = 0;
    	if($vRetCustomerPt == '') $vRetCustomerPt = 0;	
		

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

		
		if($FI_BelongsToGrp == '' ) $FI_BelongsToGrp = 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_BelongsToGroup, sale_serviceChecked, sale_service, sale_serviceB1, sale_serviceB2, sale_TaxConsumption, sale_TaxConsumptionB1, sale_TaxConsumptionB2, ".
				 " sale_TaxConsumptionChecked, sale_customerDiscount, sale_customerAwardPt) ".
				 " VALUES ( ".$vRetId.", Null, now(), '".ereg_replace("'", "\'", trim($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, $vRetDriverCode, '".$Acc_Result1[5]."', Null, Null, $vRetOrderId, $vRetOrderRef, $vRetCustomerCode, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".$Setup_Branch."' , ".$toprojectdtid."," .
				 "$FI_BelongsToGrp, $serviceChecked, 0, 0, 0, 0, 0, 0, $taxConsumptionChk, $vRetCustomerDisc, $vRetCustomerPt )";
			 
		$result=mysql_query($query,$connection)  or die(mysql_error());
		//echo $query."<br>";
		// exit;	
		$inserted =1;
		
		$SToRetId = $vRetId;	
		
		CalculateMasterAmountRetail($SToRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);

}

if($inserted!=1)
	fbegin();
	
if($SToRetId !=''){
//select currency from temp_retail
	if (empty($txtCurr))
		$txtCurr = $StpCurrCode;

	if (!isset($vRetCurr))	   $vRetCurr = $StpCurrCode;
	if (!isset($vRetCurr))	   $vRetCurr = $base1;   
	   

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

$query = "update temp_retaildt set Sale_id = ".$SToRetId." where sale_id = ".$SRetId;
//echo $query;
$result = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

$query = "	update temp_retail set projectdt_id = null ,Sale_DiscountAmount = 0 , Sale_DiscountBase1 = 0 , Sale_DiscountBase2 = 0 , Sale_Total = 0 
			, Sale_TotalBase1 = 0 , Sale_TotalBase2 = 0,	Sale_CashBase1 = 0 , Sale_CashBase2 = 0 , Sales_CashInBase1 = 0 
				, Sales_CashOutBase1 = 0 , Sales_CashInBase2 = 0 , Sales_CashOutBase2 = 0 , Sales_TipsBase1 = 0 
				, Sale_VATBase1 = 0 , Sale_VATBase2 = 0 , Sale_Taxable = 0 , Sale_TaxableBase1 = 0 , Sale_TaxableBase2 = 0 , Sale_NoneTaxable = 0 
				, Sale_NoneTaxableBase1 = 0 , Sale_NoneTaxableBase2 = 0 , Coupon_amount = 0 , Coupon_amountbase1 = 0 , Coupon_amountbase2 = 0 
				, Coupon_id = 0 , SALE_NETTOTAL = 0 , SALE_NETTOTALBASE1 = 0 , SALE_NETTOTALBASE2 = 0 , Sale_CreditAccountVat = 0 
				, Sales_CreditAmount = 0 , Sales_CreditAmountBase1 = 0 , Sales_CreditAmountBase2 = 0 , Sale_Tax1 = 0 
				, Sale_Tax2 = 0 , Sale_Tax3 = 0 , Sale_Tax4 = 0 , Sale_Tax5 = 0 , Sale_Tax1Base1 = 0 , Sale_Tax2Base1 = 0 , Sale_Tax3Base1 = 0 
				, Sale_Tax4Base1 = 0 , Sale_Tax5Base1 = 0 , Sale_Tax1Base2 = 0 , Sale_Tax2Base2 = 0 , Sale_Tax3Base2 = 0 , Sale_Tax4Base2 = 0 
				, Sale_Tax5Base2 = 0 , Sale_Acctax1 = 0 , Sale_Acctax2 = 0 , Sale_Acctax3 = 0 , Sale_Acctax4 = 0 , Sale_Acctax5 = 0
				,Sale_TotalQuantity = 0,Sale_TotalQuantityRet = 0,Sale_Vat = 0,Sale_DiscountPer = 0,Sale_BelongsToGroup=0, sale_serviceChecked=1,
				sale_service=0, sale_serviceB1=0, sale_serviceB2=0
				,sale_TaxConsumption=0, sale_TaxConsumptionB1=0, sale_TaxConsumptionB2=0,  sale_TaxConsumptionChecked=1
				where temp_retail.sale_id = ".$SRetId;
			 
$result1 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 


$query = "	update projectdt set projectdt_reserved = 0 where projectdt_id = ".$projectdtid;
$result2 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

$query = "	delete from temp_retail where sale_id  = ".$SRetId;
$result3 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

CalculateMasterAmountRetail($SRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);
CalculateMasterAmountRetail($SToRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);


if ($result and $result1 and $result2 and $result3){
			fcommit();
		}else{
			frollback();
		}
}



		echo $message;
}
else if($mode=='splitorder'){

//echo "<br>".$SRetId;
//echo "<br>".$SToRetId;
//echo "<br>".$selecteddt;

if($SToRetId != '') {

$selecteddt = str_replace('[','',$selecteddt);
$selecteddt = str_replace(']','',$selecteddt);

$query = "update temp_retaildt set Sale_id = ".$SToRetId." where sale_id = ".$SRetId." and SaleDt_id in (".$selecteddt.")";
//echo $query;
$result = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

CalculateMasterAmountRetail($SRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);
CalculateMasterAmountRetail($SToRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);


}
else {


	if ((empty($txtProjectCode)) && $Module_Project == 1)
		$txtProjectCode = $StpProjectCode;
	if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)	
		$txtCostCentCode = $StpCostCentCode;	
	if (empty($txtCurr))
		$txtCurr = $StpCurrCode;
	if (empty($txtDate))	
		$txtDate = displayToday();
	if (empty($txtCashRegister))	
		$txtCashRegister = $CashRegister_Name;
	if (empty($txtClientCode))	
		$txtClientCode = $StpClientAccount;	

	
	    $vRetDate = displayToday();
		$vRetCurr = $txtCurr;
		$vRetCostCentCode = $txtCostCentCode;
		$vRetProjectCode  = $txtProjectCode;
		$vRetCashRegister = $txtCashRegister;
		$vRetClientCode   = $txtClientCode;
		$vRetOrderId = '';
	
	
	if (!isset($vRetCurr))	   $vRetCurr = $StpCurrCode;
	if (!isset($vRetCurr))	   $vRetCurr = $base1;   
	   
	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];
	
	$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
	{
	
			
		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 = 'Null';
		if (empty($vRetDriverCode))   $vRetDriverCode = 'Null';
		if (empty($ProjectDtId))   	  $ProjectDtId = 'Null';
		

		$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($vRetCustomerDisc == '') $vRetCustomerDisc = 0;
    	if($vRetCustomerPt == '') $vRetCustomerPt = 0;	
		

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

		
		if($FI_BelongsToGrp == '' ) $FI_BelongsToGrp = 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_BelongsToGroup, sale_serviceChecked, sale_service, sale_serviceB1, sale_serviceB2, sale_TaxConsumption, sale_TaxConsumptionB1, sale_TaxConsumptionB2, ".
				 " sale_TaxConsumptionChecked, sale_customerDiscount, sale_customerAwardPt) ".
				 " VALUES ( ".$vRetId.", Null, now(), '".ereg_replace("'", "\'", trim($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, $vRetDriverCode, '".$Acc_Result1[5]."', Null, Null, $vRetOrderId, $vRetOrderRef, $vRetCustomerCode, ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".$Setup_Branch."' , ".$toprojectdtid."," .
				 "$FI_BelongsToGrp, $serviceChecked, 0, 0, 0, 0, 0, 0, $taxConsumptionChk, $vRetCustomerDisc, $vRetCustomerPt )";
			 
			 
		$result=mysql_query($query,$connection)  or die(mysql_error());
		// echo $query."<br>";// exit;	
		
		
		$SToRetId = $vRetId;	
		
	
	}

	
	
$selecteddt = str_replace('[','',$selecteddt);
$selecteddt = str_replace(']','',$selecteddt);

$query = "update temp_retaildt set Sale_id = ".$SToRetId." where sale_id = ".$SRetId." and SaleDt_id in (".$selecteddt.")";
 
$result10 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

$query = "	update projectdt set projectdt_reserved = 1 where projectdt_id = ".$toprojectdtid;

$result100 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error();

if ($result and $result10 and $result100){
			fcommit();
		}else{
			$SToRetId = "";
			$message  = mysql_error(); 
			frollback();
		}

		
CalculateMasterAmountRetail($SRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);
CalculateMasterAmountRetail($SToRetId,$Setup_VatStartDate,$Module_AdditionalTaxes,$rate_dt,$rate_dt1,$rate_dt2,$connection);



}

/*
fbegin();

$query = "update temp_retaildt set Sale_id = ".$SToRetId." where sale_id = ".$SRetId;
//echo $query;
$result = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

$query = "	update temp_retail set projectdt_id = null ,Sale_DiscountAmount = 0 , Sale_DiscountBase1 = 0 , Sale_DiscountBase2 = 0 , Sale_Total = 0 
			, Sale_TotalBase1 = 0 , Sale_TotalBase2 = 0,	Sale_CashBase1 = 0 , Sale_CashBase2 = 0 , Sales_CashInBase1 = 0 
				, Sales_CashOutBase1 = 0 , Sales_CashInBase2 = 0 , Sales_CashOutBase2 = 0 , Sales_TipsBase1 = 0 
				, Sale_VATBase1 = 0 , Sale_VATBase2 = 0 , Sale_Taxable = 0 , Sale_TaxableBase1 = 0 , Sale_TaxableBase2 = 0 , Sale_NoneTaxable = 0 
				, Sale_NoneTaxableBase1 = 0 , Sale_NoneTaxableBase2 = 0 , Coupon_amount = 0 , Coupon_amountbase1 = 0 , Coupon_amountbase2 = 0 
				, Coupon_id = 0 , SALE_NETTOTAL = 0 , SALE_NETTOTALBASE1 = 0 , SALE_NETTOTALBASE2 = 0 , Sale_CreditAccountVat = 0 
				, Sales_CreditAmount = 0 , Sales_CreditAmountBase1 = 0 , Sales_CreditAmountBase2 = 0 , Sale_Tax1 = 0 
				, Sale_Tax2 = 0 , Sale_Tax3 = 0 , Sale_Tax4 = 0 , Sale_Tax5 = 0 , Sale_Tax1Base1 = 0 , Sale_Tax2Base1 = 0 , Sale_Tax3Base1 = 0 
				, Sale_Tax4Base1 = 0 , Sale_Tax5Base1 = 0 , Sale_Tax1Base2 = 0 , Sale_Tax2Base2 = 0 , Sale_Tax3Base2 = 0 , Sale_Tax4Base2 = 0 
				, Sale_Tax5Base2 = 0 , Sale_Acctax1 = 0 , Sale_Acctax2 = 0 , Sale_Acctax3 = 0 , Sale_Acctax4 = 0 , Sale_Acctax5 = 0
				,Sale_TotalQuantity = 0,Sale_TotalQuantityRet = 0,Sale_Vat = 0,Sale_DiscountPer = 0
				where temp_retail.sale_id = ".$SRetId;
			 
$result1 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 


$query = "	update projectdt set projectdt_reserved = 0 where projectdt_id = ".$projectdtid;
$result2 = mysql_query($query,$connection) or die(mysql_error());
$message  = mysql_error(); 

if ($result and $result1 and $result2){
			fcommit();
		}else{
			frollback();
		}

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

}
function displayToday(){
	return strftime("%d")."/".strftime("%m")."/".strftime("%Y");
}
?>