
<?php
//-- Start Configs


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($config['dbName'],$connection) or die("Could not find DB");
 
 
 //Read From CashRegister Table
$queryCashRegister=" Select Currency_Code as cashregcurr ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$config['POS']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}


 
//from date = min date unposted
$queryfromdate = "select date_format( if(datediff (max(sale_date) , min(sale_date)) < 5 ,min(sale_date), DATE_SUB(max(sale_date),INTERVAL 5 DAY)), '%d/%m/%Y') from retail where Sale_Posted = 0";
$resultfrmdt=mysql_query($queryfromdate,$connection) or die(mysql_error());
$rowfrmdt=mysql_fetch_array($resultfrmdt);
$txtDateFrom = $rowfrmdt[0];




// todate = max date unposted
$queryTodate = "select date_format(max(sale_date), '%d/%m/%Y') from retail where Sale_Posted = 0";
$resulttodt=mysql_query($queryTodate,$connection) or die(mysql_error());
$rowtodt=mysql_fetch_array($resulttodt);
$txtDateTo = $rowtodt[0];



//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 = '".$config['POS']."' ";
$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 ".
          " from ".$config['dbName_log'].".login where user_account='".$config['DAP_user']."' and Upper(Login_Schema) = Upper('".$config['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  ".$config['dbName_log'].".ListUserDir ".
				" where Usercode = '".$config['DAP_user']."' and upper(concat(CompanyName,'_',Diryear)) = Upper('".$config['dbName']."') ";
$resultListDir=mysql_query($queryListDir) or die(mysql_error());
while($rows=mysql_fetch_array($resultListDir)){
	extract($rows);
}



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



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] = $config['POS'];
	
	
	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 = '".$config['DAP_user']."' )) ".
			 " AND Journal_Type In ('DI','DR') ";
			 //" And Logged_Code = '".$config['DAP_user']."' ";
				 
		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 = '".$config['DAP_user']."' )";
			 //" And Logged_Code = '".$config['DAP_user']."' ";
			 
		if (updateData($connection, $query, true)) {
		// Delete From TempRetail For Selected Record
			$query = " DELETE FROM Temp_Retail ".
				 " WHERE User_Account = '".$config['DAP_user']."' ";
				 //" And Logged_Code = '".$config['DAP_user']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		}
	}
	
	foreach($cashregisters as $cashregister){	
		// to create the Adjustment before posting
		$sub_queryX = " select create_adjustmentPOS('". $cashregister."',  '".insertMySQLDate($txtDateFrom)."', '".insertMySQLDate($txtDateTo)."' ); ";
		// echo $sub_queryX;exit;
		$sub_resultX = mysql_query($sub_queryX,$connection);
		$error = mysql_error();
	}
	$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($config['dbName'], $conn) or die("Could not find DB");
	
	if($negativeQty == 0){
		foreach($cashregisters as $cashregister){
			
			
			
			$resultvars = mysql_query("set @Result := 0, @JvResult := 0, @SaleId :=0, @SaleRef := 0, @SaleDtId := 0 ", $conn);
			 
				$sub_query = " call Posting_Retail('". $cashregister."', 0, '". $config['dbName']."', '". $config['dbName_log']."', ".
							 "                     '". $config['DAP_user']."', '". $config['DAP_username']."', $Module_PostingByCashRegister, ".
							 "                     '".insertMySQLDate($txtDateFrom)."', '".insertMySQLDate($txtDateTo)."', @Result, @JvResult) ";
							 
			$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

?>