<?php
header("Content-type: text/html; charset=utf-8");
 
session_start();

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

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

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


//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, ".
             " 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);
}

$querylog=" select FI_PurchasesVATMod, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(Login_Purchase_Pending,0) As Login_Purchase_Pending, ifNull(Login_location,0) As Login_location  ".
		  " 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 SalesSetup Table
$querySalesSetup="Select SalesTTC, TransportAccount, CashAccount, CheckAccount 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 ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ifNull(module_delivery,0) As module_delivery, ".
			 " ifNull(Module_DirectStockAI,0) As Module_DirectStockAI, ifNull(Module_AdditionalTaxes,0) as Module_AdditionalTaxes, ".
			 " ifNull(module_newproduction,0) as module_newproduction,  ifNull(Module_DirectStockPD,0) As Module_DirectStockPD, ".
			 " ifNull(Module_GenerateSorderJV,0) As Module_GenerateSorderJV ".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

set_time_limit(0);

$message='';

if (!function_exists('GetSQLValueString')) {
	function GetSQLValueString($theValue, $theType) 
	{
	  $theValue = trim($theValue);	
	  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

	  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

	  switch ($theType) {
		case "text":
		  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
		  break;    
		case "long":
		case "int":
		  $theValue = ($theValue != "") ? $theValue : "Null";
		  break;
		case "double":
		  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
		  break;
		case "date":
		  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
		  break;
	  }
	  return $theValue;
	}
}

function formatdates($date)
{

	$trim = explode('/',$date);
	$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
	return $trim;
}


$transtype  = $_POST["transtype"]; if ($transtype == ""){$transtype = $_GET["transtype"];}   
$adjustcost = $_POST["adjustcost"]; if ($adjustcost == ""){$adjustcost = $_GET["adjustcost"];}   
$fromdate 	= $_POST["fromdate"]; if ($fromdate == ""){$fromdate = $_GET["fromdate"];}   
$todate 	= $_POST["todate"]; if ($todate == ""){$todate = $_GET["todate"];}   
$fromref   	= $_POST["fromref"]; if ($fromref == ""){$fromref = $_GET["fromref"];}   
$toref  	= $_POST["toref"]; if ($toref == ""){$toref = $_GET["toref"];}   

if (!empty($fromdate)) $PFromDate = formatdates($fromdate);
if (!empty($todate))   $PToDate = formatdates($todate);  


$querydate = " Select Date_Format(StartFinancialDate,'%Y-%m-%d') As StartFinancialDate, Date_Format(EndFinancialDate,'%Y-%m-%d') As EndFinancialDate ".
			 " From ".$_SESSION['dbLabel'].".Directories ". 
			 " Where Upper(Concat(CompanyName, '_', DirYear)) = Upper('".$_SESSION['dbName']."') ";
$resultdate=mysql_query($querydate,$connection) or die(mysql_error());
$rowdate=mysql_fetch_row($resultdate);

$DirFromDate = $rowdate[0];
$DirToDate   = $rowdate[1];
		
//Repost Deliveries
if ( $transtype == 'DI') {

	$message = '';
	$ErrorExists = 0;
	 
	$sub_query = " Select Delivery_ID, Delivery_Date, Client_Code, Salesman_Code, Currency_Code, ifNull(Delivery_VatChkbx,0) as Delivery_VatChkbx, Delivery_DiscountPer, Delivery_DiscountAmount, 
				Delivery_transportAmount, Delivery_BonusAmount, Date_format(Deliveries.Delivery_Date,'%Y%m%d') as DeliveryDate ".
				 " From Deliveries ".
				 " Where Deliveries.Journal_Type = 'DI' ".
				 " And ifNull(Deliveries.Delivery_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Deliveries.Delivery_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Deliveries.Delivery_Reference, -1)) ".
				 " And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) ".
				 " And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$txtClientCode = $sub_rows['Client_Code'];
		$PSaVatChkbx = $sub_rows['Delivery_VatChkbx'];
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$sub_rows['Currency_Code']."') As CreditCur, ".
					 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount, BonusAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$sub_rows['Client_Code']."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
		
		$query = " Update Deliveries SET ".
				 " Delivery_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Delivery_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", ".
				 " Delivery_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", Delivery_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", ".
				 " Delivery_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Delivery_CreditCur = ".GetSQLValueString($Acc_Result[5],'text').", ".
				 " Delivery_CreditAccount = ".GetSQLValueString($Acc_Result[6],'text').", Delivery_TipsAccount = ".GetSQLValueString($Acc_Result[7],'text').", ".
				 " Delivery_VatAccount = ".GetSQLValueString($vSaVatAcc,'text').", Delivery_CreditAccountVat = ".GetSQLValueString($Acc_Result[9],'text').", ".
				 " Delivery_PromotionAcc = ".GetSQLValueString($Acc_Result[10],'text').", Delivery_TransportAccount = ".GetSQLValueString($Acc_Result[11],'text').", ".
				 " Delivery_CREDITACCcur = ".GetSQLValueString($Acc_Result[5],'text').", Delivery_CREDITACC = ".GetSQLValueString($Acc_Result[6],'text').", ".
				 " Delivery_BonusAccount = ".GetSQLValueString($Acc_Result[12],'text')." ".
				 " Where Delivery_ID = ".GetSQLValueString($sub_rows['Delivery_ID'],'double');
		
		$result=mysql_query($query,$connection);
		if (!$result){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
		
		
		if ($ErrorExists == 0) {
			$sub_query1 = " Select DeliveryDt_ID, DeliveryDt.Item_Code as Item_Code,  ifNull(Item_Pack, 0) as Item_Pack, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
						  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Item_Promotion, 0) as Item_Promotion,  ifNull(Items.Item_NonStock,0) as Item_NonStock ".
						  " From DeliveryDt ".
						  " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						  " Where DeliveryDt.Delivery_ID = ".GetSQLValueString($sub_rows['Delivery_ID'],'double');
						  
			$sub_result1 = mysql_query($sub_query1,$connection);
			while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
			$ItemPack = $sub_rows1['Item_Pack'];	
			$txtItemCode = $sub_rows1['Item_Code'];
			
		if ($ItemPack != 1) {
		
			$item_vat 	   = $sub_rows1['Item_Vat'];	
			$ItemGroupCode = $sub_rows1['Group_code'];	
			$ItemProd      = $sub_rows1['Item_Production'];	
			$ItemTTCInc    = $sub_rows1['Item_TTCInclude'];	
			$ItemPromo     = $sub_rows1['Item_Promotion'];	
			$ItemNonStock  = $sub_rows1['Item_NonStock'];	
			
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
			
			
			$vSaStpDirectStkDbt = '';
			$vSaStpDirectStkCrd = '';
			$vSaStpDirectStkCur = '';
			$vSaStpDiscAcc      = '';
			$vSaStpCreditVatAcc = '';
			$vSaStpCreditAcc    = '';
			$vSaStpPromoAcc     = '';
			$vSaStpTipsAcc      = '';
			
			$vSaStpCreditNonStockAcc    = '';
			$vSaStpCreditVatNonStockAcc = '';
			$vSaStpVatAcc 		  	  	= '';
			$vSaStpVatNonStockAcc 	  	= '';
			$vSaStpVatAccCash	  	  	= '';
			$vSaStpVatNonStockAccCash 	= '';
			$vSaStpCreditExportAcc		= '';
			$vTransStpExportAcc			= '';
			
			// Get DirectStock Accounts
			$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
					 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
					 " FROM salessetup ";
							 
			$resulttrans = selectData($connection, $querytrans);
						
			$vSaStpDirectStkDbt = $resulttrans[0];
			$vSaStpDirectStkCrd = $resulttrans[1];
			$vSaStpDirectStkCur = $resulttrans[2];	
			$vSaStpDiscAcc      = $resulttrans[3];	
			$vSaStpCreditVatAcc = $resulttrans[4];	
			$vSaStpCreditAcc    = $resulttrans[5];	
			$vSaStpPromoAcc     = $resulttrans[6];
			$vSaStpTipsAcc      = $resulttrans[7];
			
			$vSaStpCreditNonStockAcc    = $resulttrans[8];
			$vSaStpCreditVatNonStockAcc = $resulttrans[9];
			$vSaStpVatAcc 		  	  	= $resulttrans[10];
			$vSaStpVatNonStockAcc 	  	= $resulttrans[11];
			$vSaStpVatAccCash	  	  	= $resulttrans[12];
			$vSaStpVatNonStockAccCash 	= $resulttrans[13];
			$vSaStpCreditExportAcc	 	= $resulttrans[14];
			
			$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
			$resexp = mysql_query($queryexp,$connection);
			$rwexp = mysql_fetch_row($resexp);
			$clientexp = $rwexp[0];
				
		 
			$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export,
					  Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc, trans_IncomeAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'SI' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
							 
			$resulttrans = selectData($connection, $querytrans);
					
			$vTranStpDirectStkDbt = $resulttrans[0];
			$vTranStpDirectStkCrd = $resulttrans[1];
			$vTranStpDirectStkCur = $resulttrans[2];
			$vTranStpVatAcc       = $resulttrans[3];
			$vTranStpNonRmVatAcc  = $resulttrans[4];
			$vTranStpRmVatAcc     = $resulttrans[5];
			$vTranStpNonRmTTCIncAcc  = $resulttrans[6];
			$vTranStpRmTTCIncAcc     = $resulttrans[7];
			$vTranStpNonRmAcc        = $resulttrans[8];
			$vTranStpRmAcc           = $resulttrans[9];
			$vTranStpDiscAcc         = $resulttrans[10];
			$vTranStpPromoAcc        = $resulttrans[11]; 
			$vTranStpTipsAcc         = $resulttrans[12]; 
			$vTransStpExportAcc 	 = $resulttrans[13];
			$vSaDtWasteDbt 			= $resulttrans[14]; 
			$vSaDtWasteCrd 			= $resulttrans[15]; 
			$vSaDtExportAcc 		= $resulttrans[16];
			$vTransStpIncomeAcc		= $resulttrans[17];
			
			if ($Module_RawMaterial == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				$vSaDtTipsAcc      = $vTranStpTipsAcc;
						
				if ($item_vat > 0 && $PSaVatChkbx == 1) {
					if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
					}
					if ($vTransStpIncomeAcc != '') $vSaDtItemAcc = $vTransStpIncomeAcc;
				}
				if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 				
			} 
			else {
				$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
				$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
				//$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
				$vSaDtTipsAcc      = $vSaStpTipsAcc;
						
				if ($item_vat > 0 && $PSaVatChkbx == 1) {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
					else
						$vSaDtItemAcc = $vSaStpCreditVatAcc;
				} else {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
					else	
						$vSaDtItemAcc = $vSaStpCreditAcc;
				}

				
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
				if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc; 		
			}
				
			$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtDirectStkDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtDirectStkCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkCrd = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtWasteDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtWasteCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
			
			$querydt = " update deliverydt set Deliverydt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Deliverydt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
					 " Deliverydt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Deliverydt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", Deliverydt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').",".
					 " DeliveryDt_PromoAcc = ".GetSQLValueString($vSaDtPromoAcc,'text').", DeliveryDt_TipsAccount = ".GetSQLValueString($vSaDtTipsAcc,'text').", DeliveryDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')." ";					
			if ($adjustcost == 1) {    
				
				$query_cost = " select ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Delivery_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
						  " ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Delivery_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				$vSaDtCostBase1  = $result_cost[0]; 
				$vSaDtCostBase2  = $result_cost[1];
				$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_Code'], ($sub_rows['Delivery_Date']), $vSaDtCostBase1, $connection);
				
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				if (empty($vSaDtCost)) $vSaDtCost = 0;
				
				$querydt .= ", deliverydt_Cost = ".GetSQLValueString($vSaDtCost,'double').", deliverydt_Costbase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
						  ", deliverydt_Costbase2 = ".GetSQLValueString($vSaDtCostBase2,'double');
			}	
			$querydt .=" where DeliveryDt_id =  ".$sub_rows1['DeliveryDt_ID']." ; ";
			
			//echo $querydt;exit;
			
			$resultdt=mysql_query($querydt,$connection);
		}	// end Not Pack Item
		else {
			$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_CostPercentage, ifNull(PackDt_Promotion,0) ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
								   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtCostPer = $rowspackdt[2];
					$vPackDtPromo = $rowspackdt[3];
					
							
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock,0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$item_vat      = $result[0];
					$Item_MaxQty   = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd      = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemUnit      = $result[5];
					$ItemNonStock  = $result[6];
					
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}

					$vSaStpDirectStkDbt = '';
					$vSaStpDirectStkCrd = '';
					$vSaStpDirectStkCur = '';	
					$vSaStpDiscAcc      = '';
					$vSaStpCreditVatAcc = '';	
					$vSaStpCreditAcc    = '';	
					$vSaStpPromoAcc     = '';
					$vSaStpTipsAcc      = '';
					
					$vSaStpCreditNonStockAcc    = '';
					$vSaStpCreditVatNonStockAcc = '';
					$vSaStpVatAcc 		  	  	= '';
					$vSaStpVatNonStockAcc 	  	= '';
					$vSaStpVatAccCash	  	  	= '';
					$vSaStpVatNonStockAccCash 	= '';	
					$vSaStpCreditExportAcc		= '';
					$vTransStpExportAcc			= '';
					
					// Get DirectStock Accounts
					$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
							 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
							 " FROM salessetup ";
									 
					$resulttrans = selectData($connection, $querytrans);
								
					$vSaStpDirectStkDbt = $resulttrans[0];
					$vSaStpDirectStkCrd = $resulttrans[1];
					$vSaStpDirectStkCur = $resulttrans[2];	
					$vSaStpDiscAcc      = $resulttrans[3];	
					$vSaStpCreditVatAcc = $resulttrans[4];	
					$vSaStpCreditAcc    = $resulttrans[5];	
					$vSaStpPromoAcc     = $resulttrans[6];
					$vSaStpTipsAcc      = $resulttrans[7];
					
					$vSaStpCreditNonStockAcc    = $resulttrans[8];
					$vSaStpCreditVatNonStockAcc = $resulttrans[9];
					$vSaStpVatAcc 		  	  	= $resulttrans[10];
					$vSaStpVatNonStockAcc 	  	= $resulttrans[11];
					$vSaStpVatAccCash	  	  	= $resulttrans[12];
					$vSaStpVatNonStockAccCash 	= $resulttrans[13];
					$vSaStpCreditExportAcc	 	= $resulttrans[14];
					
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $rwexp[0];
	
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, ".
							 " trans_export, Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc, trans_IncomeAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'SI' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
											 
					$result = selectData($connection, $query);
								
					$vTranStpDirectStkDbt = $result[0];
					$vTranStpDirectStkCrd = $result[1];
					$vTranStpDirectStkCur = $result[2];
					$vTranStpVatAcc       = $result[3];
					$vTranStpNonRmVatAcc  = $result[4];
					$vTranStpRmVatAcc     = $result[5];
					$vTranStpNonRmTTCIncAcc  = $result[6];
					$vTranStpRmTTCIncAcc     = $result[7];
					$vTranStpNonRmAcc        = $result[8];
					$vTranStpRmAcc           = $result[9];
					$vTranStpDiscAcc         = $result[10];
					$vTranStpPromoAcc        = $result[11]; 
					$vTranStpTipsAcc         = $result[12];
					$vTransStpExportAcc 	 = $result[13];
					$vSaDtWasteDbt 			= $result[14]; 
					$vSaDtWasteCrd 			= $result[15]; 
					$vSaDtExportAcc 		= $result[16]; 
					$vTransStpIncomeAcc		= $result[17];
					
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
						$vSaDtPromoAcc     = $vTranStpPromoAcc;
						$vSaDtTipsAcc      = $vTranStpTipsAcc;
									
						if ($item_vat > 0 && $PSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
							if ($vTransStpIncomeAcc != '') $vSaDtItemAcc = $vTransStpIncomeAcc;
						}
						if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 						
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						//$vSaDtVatAcc       = $vSaStpVatAcc;
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
						$vSaDtPromoAcc     = $vSaStpPromoAcc;
						$vSaDtTipsAcc      = $vSaStpTipsAcc;
							
						if ($item_vat > 0 && $PSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}
							if ($ItemNonStock == 1)
								$vSaDtVatAcc = $vSaStpVatNonStockAcc;
							else	
								$vSaDtVatAcc = $vSaStpVatAcc;
							if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc; 
						}

						
						$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				 
						$querydt = " update deliverydt set Deliverydt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Deliverydt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
								   " Deliverydt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Deliverydt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", Deliverydt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').", ".
								   " DeliveryDt_PromoAcc = ".GetSQLValueString($vSaDtPromoAcc,'text').",  DeliveryDt_TipsAccount = ".GetSQLValueString($vSaDtTipsAcc,'text').", DeliveryDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')." ";
						
						
						if ($adjustcost == 1) {    
							
							$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".($sub_rows['Delivery_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$vItemCode."', '".($sub_rows['Delivery_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
							$result_cost = selectData($connection, $query_cost);
							
							$vSaDtCostBase1  = $result_cost[0]; 
							$vSaDtCostBase2  = $result_cost[1];
							$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_Code'], ($sub_rows['Delivery_Date']), $vSaDtCostBase1, $connection);
							
							if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
							if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
							if (empty($vSaDtCost)) $vSaDtCost = 0;
							
							$querydt .= ", SaleDt_Price = ".GetSQLValueString($vSaDtCost,'double').", SaleDt_PriceBase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
									  ", SaleDt_PriceBase2 = ".GetSQLValueString($vSaDtCostBase2,'double');
						}		
						$querydt .=" where DeliveryDt_id =  ".$sub_rows1['DeliveryDt_ID']." ; ";
					//	echo $query;exit; 
						$resultdt=mysql_query($querydt,$connection);
				}
		}
		
	} //end while deliverydt loop
			
	
		} //end if errorexists
			if ($ErrorExists == 0 && $Module_Delivery == 0) {
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' )";
				$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];
				
				$CalculateResult = Calculate_MasterAmountsdelivery($sub_rows['Delivery_ID'], $sub_rows['DeliveryDate'], $PSaVatChkbx,$sub_rows['Delivery_DiscountPer'], $sub_rows['Delivery_DiscountAmount'], $sub_rows['Delivery_transportAmount'], $sub_rows['Delivery_BonusAmount'], $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'U', $connection);
				$message  = $message . $CalculateResult;
			}
			if ($Module_PostToJournal == 1 && $ErrorExists == 0) {
				$message = Create_DeliveryJv($sub_rows['Delivery_ID'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
			}
		
	}	//end while delivery loop
				 
				 
		if ($message == "") {
			$message = 'Delivery Transactions Reposted Successfully.';
		}
		
	
}

else if ( $transtype == 'SI') {
	$message = '';
	$ErrorExists = 0;
	 
	$sub_query = " Select Sale_id, Sale_Date, sales.Client_code as Client_code, sales.Currency_code as Currency_code, ifNull(sale_chkvat,0) as sale_chkvat, sale_discountper, sale_discountamount, Sale_BonusAmount, 
					Sale_TransportAmount,Sale_WHTchecked, WHTPercentage, Date_format(sales.Sale_Date,'%Y%m%d')  as SaleDate".
				 " From sales ".
				 " inner join clients on clients.Ledger_number = sales.Client_code".
				 " Where sales.Journal_Type = 'SI' ".
				 " And ifNull(sales.Sale_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(sales.Sale_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(sales.Sale_Reference, -1)) ".
				 " And Date_format(sales.Sale_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) ".
				 " And Date_format(sales.Sale_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$txtClientCode = $sub_rows['Client_code'];
		$vSaVatChkbx = $sub_rows['sale_chkvat'];
		
		$query1 = "Select Client_VAT From clients Where ledger_number = '".$txtClientCode."'";
		
		$res1 = selectData($connection, $query1);
		$vClientVat = $res1[0];
			 
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, CreditCur, CreditAccount, TipsAccount, ".
					 " VatAccount, CreditAccountVAT, Sale_CLAAccount, Sale_DCTAccount, Sale_AWAccount, Sale_TRPAccount, PromotionAccount, ".
					 " TransportAccount, BonusAccount, CreditAccountNonStock, CreditAccountVatNonStock ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
	
		$update = " update sales set Sale_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Sale_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", Sale_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", ".
				  " Sale_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", Sale_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Sale_CreditCur = ".GetSQLValueString($Acc_Result[5],'text').", ".
				  " Sale_CreditAccount = ".GetSQLValueString($Acc_Result[6],'text').", Sale_TipsAccount = ".GetSQLValueString($Acc_Result[7],'text').", Sale_Vataccount = ".GetSQLValueString($Acc_Result[8],'text').", ".
				  " Sale_creditaccountvat = ".GetSQLValueString($Acc_Result[9],'text').", Sale_CreditCLA = ".GetSQLValueString($Acc_Result[10],'text').", Sale_CreditDCT =".GetSQLValueString($Acc_Result[11],'text').", ".
				  " Sale_CreditAW = ".GetSQLValueString($Acc_Result[12],'text').", Sale_CreditTRP = ".GetSQLValueString($Acc_Result[13],'text').", Sale_PromotionAcc = ".GetSQLValueString($Acc_Result[14],'text').",  ".
				  " Sale_TransportAccount = ".GetSQLValueString($Acc_Result[15],'text').", Sale_BonusAccount = ".GetSQLValueString($Acc_Result[16],'text')." ".
				  " where sale_id = ".$sub_rows['Sale_id']; 
		$resupdate = mysql_query($update,$connection);		  
		if (!$resupdate){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
			if ($ErrorExists == 0) {
				$sub_query1 = " Select SaleDt_id, salesdt.Item_code as Item_code,  ifNull(Item_Pack, 0) as Item_Pack, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
						  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Item_Promotion, 0) as Item_Promotion,  ifNull(Items.Item_NonStock,0) as Item_NonStock ".
						  " From salesdt ".
						  " Inner Join Items on salesdt.Item_code = Items.Item_Code ".
						  " Where salesdt.Sale_id = ".GetSQLValueString($sub_rows['Sale_id'],'double');
						  
				$sub_result1 = mysql_query($sub_query1,$connection);
				while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
					$item_vat 	   = $sub_rows1['Item_Vat'];
					$ItemGroupCode = $sub_rows1['Group_code'];
					$ItemProd      = $sub_rows1['Item_Production'];
					$ItemTTCInc    = $sub_rows1['Item_TTCInclude'];
					$ItemPromo     = $sub_rows1['Item_Promotion'];
					$ItemNonStock  = $sub_rows1['Item_NonStock'];
					$txtItemCode   = $sub_rows1['Item_code'];
					$txtsaledt_id   = $sub_rows1['SaleDt_id'];
					// Get DirectStock Accounts
					$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, ".
							 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
							 " FROM salessetup ";
									 
					$resulttrans = selectData($connection, $querytrans);
							
					$vSaStpDirectStkDbt = $resulttrans[0];
					$vSaStpDirectStkCrd = $resulttrans[1];
					$vSaStpDirectStkCur = $resulttrans[2];	
					$vSaStpDiscAcc      = $resulttrans[3];	
					$vSaStpCreditVatAcc = $resulttrans[4];	
					$vSaStpCreditAcc    = $resulttrans[5];	
					
					$vSaStpCreditNonStockAcc    = $resulttrans[6];
					$vSaStpCreditVatNonStockAcc = $resulttrans[7];
					$vSaStpVatAcc 		  	  	= $resulttrans[8];
					$vSaStpVatNonStockAcc 	  	= $resulttrans[9];
					$vSaStpVatAccCash	  	  	= $resulttrans[10];
					$vSaStpVatNonStockAccCash 	= $resulttrans[11];
							
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $rwexp[0];
					
					$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, trans_export ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
								 
					$resulttrans = selectData($connection, $querytrans);
							
					$vTranStpDirectStkDbt = $resulttrans[0];
					$vTranStpDirectStkCrd = $resulttrans[1];
					$vTranStpDirectStkCur = $resulttrans[2];
					$vTranStpVatAcc       = $resulttrans[3];
					$vTranStpNonRmVatAcc  = $resulttrans[4];
					$vTranStpRmVatAcc     = $resulttrans[5];
					$vTranStpNonRmTTCIncAcc  = $resulttrans[6];
					$vTranStpRmTTCIncAcc     = $resulttrans[7];
					$vTranStpNonRmAcc        = $resulttrans[8];
					$vTranStpRmAcc           = $resulttrans[9];
					$vTranStpDiscAcc         = $resulttrans[10];
					
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
								
						if ($item_vat > 0 && $vSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
						}	
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
								
						if ($item_vat > 0 && $vSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}

						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAcc;
						else	
							$vSaDtVatAcc = $vSaStpVatAcc;
					}
					
					if($clientexp == 1) $vSaDtItemAcc = $result[11]; 
				
					$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
					
					$querydt =  " update salesdt set Saledt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Saledt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
								" Saledt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Saledt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", Saledt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').", ".
								" SaleDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')."  ";
					/* if($adjustcost == 1){  
						
						$query_cost = " select ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Sale_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
								  " ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Sale_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
						$result_cost = selectData($connection, $query_cost);
						
						$vSaDtCostBase1  = $result_cost[0]; 
						$vSaDtCostBase2  = $result_cost[1];
						$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_code'], ($sub_rows['Sale_Date']), $vSaDtCostBase1, $connection);
						
						if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
						if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
						if (empty($vSaDtCost)) $vSaDtCost = 0;
						
						$querydt .= ", SaleDt_Price = ".GetSQLValueString($vSaDtCost,'double').", SaleDt_PriceBase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
								  ", SaleDt_PriceBase2 = ".GetSQLValueString($vSaDtCostBase2,'double');
					} */
					$querydt .= " where SaleDt_id = ".$sub_rows1['SaleDt_id'];			 
					//echo $querydt;exit;
					$resultdt=mysql_query($querydt,$connection);
					if (!$resultdt){
						$ErrorExists = 1;
						$message  = mysql_error($connection);
					}
				
				
			   	  $querycost= " select ifnull(deliverydt_Costbase1,0) as DeliveryCost1,ifnull(deliverydt_Costbase2,0) as DeliveryCost2
					              from deliverydt where deliverydt_id in (Select relateddt_id from salesdt
					              where SaleDt_id = $txtsaledt_id  )";	
								  
					//echo $querycost;exit;			  
					
					$resultcost=mysql_query($querycost,$connection) or die(mysql_error());
                    while($rowscost=mysql_fetch_array($resultcost)){
	                extract($rowscost);
                    }
					
					
					
					$querydt2 = " update salesdt set salesdt_CostBase1 =$DeliveryCost1 ,salesdt_CostBase2 =$DeliveryCost2  where SaleDt_id = $txtsaledt_id ";

                    $resultdt2=mysql_query($querydt2,$connection);
					if (!$resultdt2){
						$ErrorExists = 1;
						$message  = mysql_error($connection);
					}
				
				} // end while salesdt loop
				
				
				if($ErrorExists == 0){
					/* if($adjustcost == 1){  
						$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_code']."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_code']."' )";
						$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];
						
						$CalculateResult = Calculate_salesMasterAmounts($sub_rows['Sale_id'], $sub_rows['SaleDate'], $vSaVatChkbx, $sub_rows['sale_discountper'],$sub_rows['sale_discountamount'], $sub_rows['Sale_TransportAmount'], 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$sub_rows['Sale_WHTchecked'],$sub_rows['WHTPercentage'], 'U', $connection);
						$message  = $message . $CalculateResult;
						
					} */
					if ($Module_PostToJournal == 1)	{
						$message = Create_SalesJv($sub_rows['Sale_id'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
					}
					
				}
			}//end if error exists	
	} //end while sales loop
	
	if ($message == "") {
		$message = 'Delivery Transactions Reposted Successfully.';
	}
}
//Repost Purchases
else if ($transtype == 'PI') {
	$queryPurchaseSetup="Select PurchaseTTC, PurchaseDefaultType From PurchaseSetup";
	$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
	while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
		extract($rowPurchaseSetup);
	}

	$message = '';
	$ErrorExists = 0;
	
	$sub_query = " Select Purchase_ID, Purchase_Date, Supplier_Code, Currency_Code, ifNull(Purchase_VatChkbx,0) as Purchase_VatChkbx, Purchase_DiscountAmount, Purchase_DiscountPer, Purchase_VatBase1 ".
				 " From Purchases ".
				 " Where Purchases.Journal_Type = 'PI' ".
				 " And Upper(Purchase_Type) != 'PENDING' ".
				 " And ifNull(Purchases.Purchase_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Purchases.Purchase_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Purchases.Purchase_Reference, -1)) ".
				 " And Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) ".
				 " And Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$PPurSupplier = $sub_rows['Supplier_Code'];
		$PPurVatChkbx = $sub_rows['Purchase_VatChkbx'];
		$PurRates = GetPurchaseRates($sub_rows['Purchase_ID'],$connection);
		$vRate   = $PurRates[0];
		$vRateB1 = $PurRates[1];
		$vRateB2 = $PurRates[2];
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$sub_rows['Currency_Code']."') As DebitCur, ".
					 " FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
					 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, ".
					 " TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, ".
					 " CustomsDebitAccount, CustomsCreditAccount ".
					 " FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
			 
		$query = " Update Purchases SET ".
				 " Purchase_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Purchase_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", ".
				 " Purchase_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", Purchase_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", ".
				 " Purchase_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Purchase_DebitCur = ".GetSQLValueString($Acc_Result[6],'text').", ".
				 " Purchase_DebitAccount = ".GetSQLValueString($Acc_Result[5],'text').", ".
				 " FreightDebitAccount = ".GetSQLValueString($Acc_Result[6],'text').", FreightCreditAccount = ".GetSQLValueString($Acc_Result[7],'text').", ".
				 " CommissionsDebitAccount = ".GetSQLValueString($Acc_Result[8],'text').", CommissionsCreditAccount = ".GetSQLValueString($Acc_Result[9],'text').", ".
				 " InsuranceDebitAccount = ".GetSQLValueString($Acc_Result[10],'text').", InsuranceCreditAccount = ".GetSQLValueString($Acc_Result[11],'text').", ".
				 " ClearingDebitAccount = ".GetSQLValueString($Acc_Result[12],'text').", ClearingCreditAccount = ".GetSQLValueString($Acc_Result[13],'text').", ".
				 " TransportDebitAccount = ".GetSQLValueString($Acc_Result[14],'text').", TransportCreditAccount = ".GetSQLValueString($Acc_Result[15],'text').", ".
				 " OtherDebitAccount = ".GetSQLValueString($Acc_Result[16],'text').", OtherCreditAccount = ".GetSQLValueString($Acc_Result[17],'text').", ".
				 " CustomsDebitAccount = ".GetSQLValueString($Acc_Result[18],'text').", CustomsCreditAccount = ".GetSQLValueString($Acc_Result[19],'text').
				 " Where Purchase_ID = ".GetSQLValueString($sub_rows['Purchase_ID'],'double');
		
		$result=mysql_query($query,$connection);
		if (!$result){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
		
		
	if ($ErrorExists == 0) {
	$sub_query1 = " Select PurchaseDt_ID, PurchasesDt.Item_Code as Item_Code, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
				  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Items.Item_NonStock,0) as Item_NonStock, ifNull(Item_VatType, 1) as Item_VatType, ifNull(Item_Pack, 0) as Item_Pack ".
				  " From PurchasesDt ".
				  " Inner Join Items on PurchasesDt.Item_Code = Items.Item_Code ".
				  " Where PurchasesDt.Purchase_ID = ".GetSQLValueString($sub_rows['Purchase_ID'],'double');
						  
	$sub_result1 = mysql_query($sub_query1,$connection);
	while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
		
		$txtItemCode = $sub_rows1['Item_Code'];
		$ItemPack 	 = $sub_rows1['Item_Pack'];
		
		if ($ItemPack != 1) {

		$item_vat 	   = $sub_rows1['Item_Vat'];
		$ItemGroupCode = $sub_rows1['Group_code'];
		$ItemProd 	   = $sub_rows1['Item_Production'];
		$ItemTTCInc	   = $sub_rows1['Item_TTCInclude'];
		$ItemNonStock  = $sub_rows1['Item_NonStock'];
		$ItemVatType   = $sub_rows1['Item_VatType'];
		
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
				
		$vPurStpDirectStkDbt    	 = '';
		$vPurStpDirectStkCrd    	 = '';
		$vPurStpDirectStkCur    	 = '';	
		$vPurStpVatAcc          	 = '';	
		$vPurStpDebitAcc        	 = '';	
		$vPurStpVatNonStockAcc  	 = '';	
		$vPurStpVatAcc2         	 = '';
		$vPurStpVatAcc3         	 = '';
		$vPurStpVatNonStockAcc2 	 = '';
		$vPurStpVatNonStockAcc3 	 = '';
		$vPurStpDebitAcc2       	 = '';
		$vPurStpDebitAcc3       	 = '';
		$vPurStpDebitVatAcc     	 = '';
		$vPurStpDebitVatAcc2    	 = '';
		$vPurStpDebitVatAcc3    	 = '';
		$vPurStpDebitNonStockAcc  	 = '';
		$vPurStpDebitNonStockAcc2 	 = '';
		$vPurStpDebitNonStockAcc3 	 = '';
		$vPurStpDebitVatNonStockAcc  = '';
		$vPurStpDebitVatNonStockAcc2 = '';
		$vPurStpDebitVatNonStockAcc3 = '';
		$vPurStpDebitExportAcc		 = '';
		$vTransExport				 = '';
		
		// Get DirectStock Accounts
		$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock,  ".
				 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
				 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
				 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport ".
				 " FROM purchasesetup ";
					 
		$result = selectData($connection, $query);
			
		$vPurStpDirectStkDbt    	 = $result[0];
		$vPurStpDirectStkCrd    	 = $result[1];
		$vPurStpDirectStkCur    	 = $result[2];	
		$vPurStpVatAcc          	 = $result[3];	
		$vPurStpDebitAcc        	 = $result[4];	
		$vPurStpVatNonStockAcc  	 = $result[5];	
		$vPurStpVatAcc2         	 = $result[6];
		$vPurStpVatAcc3         	 = $result[7];
		$vPurStpVatNonStockAcc2 	 = $result[8];
		$vPurStpVatNonStockAcc3 	 = $result[9];
		$vPurStpDebitAcc2       	 = $result[10];
		$vPurStpDebitAcc3       	 = $result[11];
		$vPurStpDebitVatAcc     	 = $result[12];
		$vPurStpDebitVatAcc2    	 = $result[13];
		$vPurStpDebitVatAcc3    	 = $result[14];
		$vPurStpDebitNonStockAcc  	 = $result[15];
		$vPurStpDebitNonStockAcc2 	 = $result[16];
		$vPurStpDebitNonStockAcc3 	 = $result[17];
		$vPurStpDebitVatNonStockAcc  = $result[18];
		$vPurStpDebitVatNonStockAcc2 = $result[19];
		$vPurStpDebitVatNonStockAcc3 = $result[20];
		$vPurStpDebitExportAcc	 	 = $result[21];
		
		$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number = ".GetSQLValueString($PPurSupplier,'text')."; ";	
		$resexp = mysql_query($queryexp,$connection);
		$rwexp = mysql_fetch_row($resexp);
		$supplierexp = $rwexp[0];
	
		$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
				 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export,  ".
				 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
				 " FROM transactionsetup ".
				 " WHERE Journal_type = 'PI' ".
				 " 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];
		$vTransExport			= $result[10];
		$vSaDtWasteDbt 			= $result[11]; 
		$vSaDtWasteCrd 			= $result[12]; 
		$vSaDtExportAcc 		= $result[13];		
		
		if ($Module_RawMaterial == 1) {
			$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
			$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
			$vPurDtDirectStkCur = $vTranStpDirectStkCur;
			$vPurDtVatAcc       = $vTranStpVatAcc;
				
			if ($item_vat > 0 && $PPurVatChkbx == 1) {
				if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
			}
			else {
				if ($ItemProd == 1) {
					if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
				}	
				else {
					if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
				}
			}
			if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 			
		} 
		else {
			$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
			$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
			$vPurDtDirectStkCur = $vPurStpDirectStkCur;	

			if ($ItemNonStock == 1)	{
				if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
				else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
				else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
			}	
			else {
				if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
				else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
				else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
			}	
		
			if ($item_vat > 0 && $PPurVatChkbx == 1) {
				if ($ItemNonStock == 1)	{
					if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
					else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
					else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
				}	
				else {
					if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
					else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
					else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
				}
			}	
			else {
				if ($ItemNonStock == 1)	{
					if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
					else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
					else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
				}	
				else {
					if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
					else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
					else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
				}						
			}	
			if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 		
		}
		
		$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
		
		$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkDbt."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vPurDtDirectStkDbt = $sub_resultVat[0];
		
		$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkCrd."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vPurDtDirectStkCrd = $sub_resultVat[0];
		
		$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteDbt."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
		
		$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteCrd."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
		
		$querydt = " update purchasesdt set Purchasedt_DirectStkDbt = ".GetSQLValueString($vPurDtDirectStkDbt,'text').", Purchasedt_DirectStkCrd = ".GetSQLValueString($vPurDtDirectStkCrd,'text').", ".
				   " Purchasedt_DirectStkCur = ".GetSQLValueString($vPurDtDirectStkCur,'text').", PurchaseDt_VATAccount = ".GetSQLValueString($vPurDtVatAcc,'text').", ".	
				   " Purchasedt_ItemAccount = ".GetSQLValueString($vPurDtItemAcc,'text')." ".
				   " where PurchaseDt_id = ".$sub_rows1['PurchaseDt_ID'].";";	
				//echo $query."<br>";exit;				
		$resultdt=mysql_query($querydt,$connection);
								
	}	// End Case Not Pack Item
	else {
		$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
					   " FROM PackDt ".
					   " WHERE Item_Code = '".$txtItemCode."'  ";
		$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
		while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
					
			$vItemCodePacked = $rowspackdt[0];
			$vItemCode 		 = $rowspackdt[1];
			$vPackDtCostPer  = $rowspackdt[3];
			
			$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0), ifNull(Item_VatType, 1) ".
					 " FROM Items WHERE item_Code = '".$vItemCode."'";
			$result = selectData($connection, $query);
			$item_vat	   = $result[0];
			$ItemGroupCode = $result[2];
			$ItemProd 	   = $result[3];
			$ItemTTCInc    = $result[4];
			$ItemNonStock  = $result[6];
			$ItemVatType   = $result[7];
						
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
				
			$vPurDtDirectStkDbt = '';
			$vPurDtDirectStkCrd = '';
			$vPurDtDirectStkCur = '';
			$vPurDtVatAcc	    = '';
			$vPurDtItemAcc      = '';
			$vPurStpDirectStkDbt = '';
			$vPurStpDirectStkCrd = '';
			$vPurStpDirectStkCur = '';
			$vPurStpVatAcc       = '';
			$vPurStpDebitAcc     = '';
			$vTranStpDirectStkDbt = '';
			$vTranStpDirectStkCrd = '';
			$vTranStpDirectStkCur = '';
			$vTranStpVatAcc       = '';
			$vTranStpNonRmVatAcc  = '';
			$vTranStpRmVatAcc     = '';
			$vTranStpNonRmTTCIncAcc  = '';
			$vTranStpRmTTCIncAcc     = '';
			$vTranStpNonRmAcc  = '';
			$vTranStpRmAcc     = '';
			$vPurStpDebitExportAcc	= '';
			
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock,  ".
					 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
					 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
					 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport ".
					 " FROM purchasesetup ";
					 
			$result = selectData($connection, $query);
			
			$vPurStpDirectStkDbt    	 = $result[0];
			$vPurStpDirectStkCrd    	 = $result[1];
			$vPurStpDirectStkCur    	 = $result[2];	
			$vPurStpVatAcc          	 = $result[3];	
			$vPurStpDebitAcc        	 = $result[4];	
			$vPurStpVatNonStockAcc  	 = $result[5];
			$vPurStpVatAcc2         	 = $result[6];
			$vPurStpVatAcc3         	 = $result[7];
			$vPurStpVatNonStockAcc2 	 = $result[8];
			$vPurStpVatNonStockAcc3 	 = $result[9];
			$vPurStpDebitAcc2       	 = $result[10];
			$vPurStpDebitAcc3       	 = $result[11];
			$vPurStpDebitVatAcc     	 = $result[12];
			$vPurStpDebitVatAcc2    	 = $result[13];
			$vPurStpDebitVatAcc3   	 	 = $result[14];
			$vPurStpDebitNonStockAcc  	 = $result[15];
			$vPurStpDebitNonStockAcc2 	 = $result[16];
			$vPurStpDebitNonStockAcc3 	 = $result[17];
			$vPurStpDebitVatNonStockAcc  = $result[18];
			$vPurStpDebitVatNonStockAcc2 = $result[19];
			$vPurStpDebitVatNonStockAcc3 = $result[20];
			$vPurStpDebitExportAcc		 = $result[21];
			
			$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number =  ".GetSQLValueString($PPurSupplier,'text').";";	
			$resexp = mysql_query($queryexp,$connection);
			$rwexp = mysql_fetch_row($resexp);
			$supplierexp = $rwexp[0]; 
			
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export, ".
					 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PI' ".
					 " 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];
			$vTransExport			= $result[10];
			$vSaDtWasteDbt 			= $result[11]; 
			$vSaDtWasteCrd 			= $result[12]; 
			$vSaDtExportAcc 		= $result[13]; 
			
			if ($Module_RawMaterial == 1) {
				$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPurDtDirectStkCur = $vTranStpDirectStkCur;
				$vPurDtVatAcc       = $vTranStpVatAcc;
				
				if ($item_vat > 0 && $PPurVatChkbx == 1) {
					if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
					}
				}
				if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 
			} 
			else {
				$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
				$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
					
				if ($ItemNonStock == 1)	{
					if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
					else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
					else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
				}	
				else {
					if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
					else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
					else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
				}	
			
				if ($item_vat > 0 && $PPurVatChkbx == 1) {
					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
						else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
					}
				}	
				else {
					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
						else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
						else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
					}						
				}
				if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc;
			}
			
			$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual; ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vPurDtDirectStkDbt = $sub_resultVat[0];

			$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vPurDtDirectStkCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vPurDtDirectStkCrd = $sub_resultVat[0];

			$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];

			$sub_queryVat = " SELECT GetAllVATAccount('".$PPurSupplier."','".$vSaDtWasteCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
						
			$querydt = " update purchasesdt set Purchasedt_DirectStkDbt = ".GetSQLValueString($vPurDtDirectStkDbt,'text').", Purchasedt_DirectStkCrd = ".GetSQLValueString($vPurDtDirectStkCrd,'text').",  ".
					 " Purchasedt_DirectStkCur = ".GetSQLValueString($vPurDtDirectStkCur,'text').", PurchaseDt_VATAccount = ".GetSQLValueString($vPurDtVatAcc,'text').",  ".
					 " Purchasedt_ItemAccount = ".GetSQLValueString($vPurDtItemAcc,'text')."  ".
					 " where PurchaseDt_id = ".$sub_rows1['PurchaseDt_ID'].";";
					 
			$resultdt=mysql_query($querydt,$connection);
		} // End Loop Of Packdt
	} // End CasePack Item
		
	if (!$resultdt){
		$ErrorExists = 1;
		$message  = mysql_error($connection);
		Break;
	}
} //end while purchasedt 
			
	if ($Module_PostToJournal == 1 && $ErrorExists == 0) { 
		$queryBlg = "select Purchase_BelongsToGroup from purchases where purchase_id = ".$sub_rows['Purchase_ID'];
		$resBlg = mysql_query($queryBlg,$connection);
		$rowBlg = mysql_fetch_row($resBlg);
		$BelongsToGrp = $rowBlg[0];
		$message = Create_PurchaseJv($sub_rows['Purchase_ID'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'],$BelongsToGrp); 
	}
		}
	}	
				 
	if ($message == "") {
		$message = 'Purchase Transactions Reposted Successfully.';
	}
		
}

//Repost Stock IN/OUT and Adjustment
else if ($transtype == 'AI' || $transtype == 'AR' || $transtype == 'AD') {
	$message = '';
	$ErrorExists = 0;
	
	$sub_query = " Select Adjustment_ID, Adjustment_Date, Currency_Code, Date_format(Adjustment_Date,'%d/%m/%Y') as FormatAdjustDate, currency_code ".
				 " From Adjustment ".
				 " Where ifNull(Adjustment.Adjustment_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Adjustment.Adjustment_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Adjustment.Adjustment_Reference, -1)) ".
				 " And Date_format(Adjustment.Adjustment_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Adjustment.Adjustment_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Adjustment.Adjustment_Date,'%Y-%m-%d')) ".
				 " And Date_format(Adjustment.Adjustment_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Adjustment.Adjustment_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Adjustment.Adjustment_Date,'%Y-%m-%d'))  ";
				 
	if ($transtype == 'AI')	
		$sub_query .= " And Adjustment.Adjustment_EntryType = 'I' ";
	else if ($transtype == 'AR')
		$sub_query .= " And Adjustment.Adjustment_EntryType = 'O' ";
	else if ($transtype == 'AD')
		$sub_query .= " And Adjustment.Adjustment_EntryType = 'A' ";
	
	
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		
		$vAdjDtPrice      = 0;
		$vAdjDtPriceBase1 = 0;
		$vAdjDtPriceBase2 = 0;
		
		$vAdjCurr 		  = $sub_result['currency_code'];
		
		$vAdjDtDirectStkDbt = '';
		$vAdjDtDirectStkCrd = '';
		$vAdjDtDirectStkCur = '';
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vAdjCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vAdjCurr."' )";
		$result = selectData($connection, $query);
		$rate_dt = $result[0];

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$Base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$Base1."' )";
		$result = selectData($connection, $query);
		$rate_dt1 = $result[0];

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$Base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$Base2."' )";
		$result = selectData($connection, $query);
		$rate_dt2 = $result[0];
		
		$sub_query1 = " Select AdjustmentDt_ID, AdjustmentDt.Item_Code as Item_Code, Items.Item_Vat, Items.Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
					  " ifNull(Items.Item_CostMethod, 0) as Item_CostMethod, ifNull(Items.Item_NonStock,0) as Item_NonStock, Items.Currency_Code as ItemCurrency, ifNull(Item_Pack, 0) as Item_Pack, ".
					  " AdjustmentDt_Quantity, Item_Unit2Qty, AdjustmentDt_Price, Journal_Type ".
					  " From AdjustmentDt ".
					  " Inner Join Items on AdjustmentDt.Item_Code = Items.Item_Code ".
					  " Where AdjustmentDt.Adjustment_ID = ".GetSQLValueString($sub_rows['Adjustment_ID'],'double');
						  
		$sub_result1 = mysql_query($sub_query1,$connection);
		while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
			
			$txtItemCode		= $sub_rows1['Item_Code'];
			$ItemPack 			= $sub_rows1['Item_Pack'];		
			$Journal_Typedt    	= $sub_rows1['Journal_Type'];
						
			if ($ItemPack != 1) {

			$sub_query = " SELECT Item_Vat, Group_code ".
						 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
			$sub_result2 = selectData($connection, $sub_query);
			$ItemVat 	     = $sub_result2[0];
			$ItemGroupCode   = $sub_result2[1];
			
			$querysetup = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'AD' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";

			$resultsetup = selectData($connection, $querysetup);

			$vTranStpDirectStkDbt = $resultsetup[0];
			$vTranStpDirectStkCrd = $resultsetup[1];
			$vTranStpDirectStkCur = $resultsetup[2];

			$vAdjDtDirectStkDbt = $vTranStpDirectStkDbt;
			$vAdjDtDirectStkCrd = $vTranStpDirectStkCrd;
			$vAdjDtDirectStkCur = $vTranStpDirectStkCur;
			
			$querydt = " update adjustmentdt set AdjustmentDt_DirectStkDbt = ".GetSQLValueString($vAdjDtDirectStkDbt, 'text').", ".
					   " AdjustmentDt_DirectStkCrd = ".GetSQLValueString($vAdjDtDirectStkCrd, 'text').",  AdjustmentDt_DirectStkCur = ".GetSQLValueString($vAdjDtDirectStkCur, 'text')." ";
					   
			
			if ($adjustcost == 1 && $Journal_Typedt != 'AI') {
				
				$vAdjDtPrice = Get_CostPrice($sub_rows1['Item_Code'], $sub_rows1['ItemCurrency'], $sub_rows1['Item_CostMethod'], $sub_rows['FormatAdjustDate'], $sub_rows['Currency_Code'], $Base1, $Base2, $connection);
				if(empty($vAdjDtPrice)) $vAdjDtPrice = 0;
				
				$vAdjDtPriceBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, $sub_rows['Adjustment_Date'], $vAdjDtPrice, $connection);
				$vAdjDtPriceBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2, $sub_rows['Adjustment_Date'], $vAdjDtPrice, $connection);
				if (empty($vAdjDtPriceBase1)) $vAdjDtPriceBase1 = 0;
				if (empty($vAdjDtPriceBase2)) $vAdjDtPriceBase2 = 0;
				
				$querydt .= ", AdjustmentDt_Price = ".GetSQLValueString($vAdjDtPrice,'double').", AdjustmentDt_PriceBase1 = ".GetSQLValueString($vAdjDtPriceBase1,'double').
						  ", AdjustmentDt_PriceBase2 = ".GetSQLValueString($vAdjDtPriceBase2,'double');
			}
			$querydt .=	" where AdjustmentDt_ID = ".$sub_rows1['AdjustmentDt_ID']." ";		 
			
			$resultdt=mysql_query($querydt,$connection);
			//echo $query."<br>";exit;

		} 	
		else {
			$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
							" FROM PackDt ".
							" WHERE Item_Code = '".$txtItemCode."'  ";

			$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
			while($packdt_rows=mysql_fetch_array($packdt_result)){

				$vItemCodePacked = $packdt_rows[0];
				$vItemCode 		 = $packdt_rows[1];
				$vPackDtQty 	 = $packdt_rows[2];
				$vPackDtCostPer  = $packdt_rows[3];

				$vAdjDtDirectStkDbt = '';
				$vAdjDtDirectStkCrd = '';
				$vAdjDtDirectStkCur = '';

				$QtyExistExceeded   = 0;


				$sub_query2 = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), Currency_Code, ".
							 " ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0), ifNull(Item_Unit, 0) ".
							 " FROM Items WHERE Item_Code = '".$vItemCode."'";
				$sub_result2 = selectData($connection, $sub_query2);
				$ItemVat 	     = $sub_result2[0];
				$ItemGroupCode   = $sub_result2[1];
				$ItemProd        = $sub_result2[2];
				$ItemTTCInc      = $sub_result2[3];
				$ItemCurr		 = $sub_result2[4];
				//$ItemCostMethod  = $sub_result[5];
				$ItemCostMethod  = 0;
				$ItemNonStock    = $sub_result[6];
				$ItemUnit   	 = $sub_result[7];

				$querysetup =" SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'AD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";

				$resultsetup = selectData($connection, $querysetup);

				$vTranStpDirectStkDbt = $resultsetup[0];
				$vTranStpDirectStkCrd = $resultsetup[1];
				$vTranStpDirectStkCur = $resultsetup[2];

				$vAdjDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vAdjDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vAdjDtDirectStkCur = $vTranStpDirectStkCur;

				$querydt = " update adjustmentdt set AdjustmentDt_DirectStkDbt = ".GetSQLValueString($vAdjDtDirectStkDbt,'text').", ".
						   " AdjustmentDt_DirectStkCrd =  ".GetSQLValueString($vAdjDtDirectStkCrd,'text').", ".
						   " AdjustmentDt_DirectStkCur = ".GetSQLValueString($vAdjDtDirectStkCur,'text')." ";
											   
				if ($adjustcost == 1 && $Journal_Typedt != 'AI') {
				
				$vAdjDtPrice = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $sub_rows['FormatAdjustDate'], $sub_rows['Currency_Code'], $Base1, $Base2, $connection);
				if(empty($vAdjDtPrice)) $vAdjDtPrice = 0;
				
				$vAdjDtPriceBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, $sub_rows['Adjustment_Date'], $vAdjDtPrice, $connection);
				$vAdjDtPriceBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2, $sub_rows['Adjustment_Date'], $vAdjDtPrice, $connection);
				if (empty($vAdjDtPriceBase1)) $vAdjDtPriceBase1 = 0;
				if (empty($vAdjDtPriceBase2)) $vAdjDtPriceBase2 = 0;
				
				$querydt .= ", AdjustmentDt_Price = ".GetSQLValueString($vAdjDtPrice,'double').", AdjustmentDt_PriceBase1 = ".GetSQLValueString($vAdjDtPriceBase1,'double').
						  ", AdjustmentDt_PriceBase2 = ".GetSQLValueString($vAdjDtPriceBase2,'double');
				}
				$querydt .=	" where AdjustmentDt_ID = ".$sub_rows1['AdjustmentDt_ID']." ";	
				$resultdt=mysql_query($querydt,$connection);
				//echo $query."<br>";

			} // End Loop Of Packdt


		}
			
		if (!$result){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
			Break;
		}
					
	}
			
	if ($ErrorExists == 0 && $adjustcost == 1) {
		//Calculating Master Amounts
		$CalculateResult = Calculate_AdjustAmounts($sub_rows['Adjustment_ID'], $connection);
		$message  = $message . $CalculateResult;
	}
		
	if ($Module_PostToJournal == 1 && $Module_DirectStockAI == 1 && $ErrorExists == 0) {
		$message = Create_AdjustmentJv($sub_rows['Adjustment_ID'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
	}
		
}	
				 
				 
	if ($message == "") {
		if ($transtype == 'AI')	
			$message = 'Stock IN Transactions Reposted Successfully.';
		else if ($transtype == 'AR')
			$message = 'Stock OUT Transactions Reposted Successfully.';
		else if ($transtype == 'AD')
			$message = 'Adjustment Transactions Reposted Successfully.';
		
	}
		
} 
else if($transtype == 'DR'){
	$message = '';
	$ErrorExists = 0;
	
	$sub_query = " Select Delivery_ID, Delivery_Date, Client_Code, Salesman_Code, Currency_Code, ifNull(Delivery_VatChkbx,0) as Delivery_VatChkbx,  Delivery_DiscountPer,Delivery_DiscountAmount, 
					Delivery_transportAmount, Delivery_BonusAmount, Date_format(Deliveries.Delivery_Date,'%Y%m%d') as DeliveryDate ".
				 " From Deliveries ".
				 " Where Deliveries.Journal_Type = 'DR' ".
				 " And ifNull(Deliveries.Delivery_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Deliveries.Delivery_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Deliveries.Delivery_Reference, -1)) ".
				 " And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) ".
				 " And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$txtClientCode = $sub_rows['Client_Code'];
		$PRSaVatChkbx = $sub_rows['Delivery_VatChkbx'];
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$sub_rows['Currency_Code']."') As CreditCur, ".
					 " CreditAccountReturn, TipsAccount, VatAccount, CreditVATReturn, PromotionAccount, TransportAccount ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$sub_rows['Client_Code']."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
		
		$query = " Update Deliveries SET ".
				 " Delivery_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Delivery_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", ".
				 " Delivery_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", Delivery_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", ".
				 " Delivery_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Delivery_CreditCur = ".GetSQLValueString($Acc_Result[5],'text').", ".
				 " Delivery_CreditAccount = ".GetSQLValueString($Acc_Result[6],'text').", Delivery_TipsAccount = ".GetSQLValueString($Acc_Result[7],'text').", ".
				 " Delivery_VatAccount = ".GetSQLValueString($vSaVatAcc,'text').", Delivery_CreditAccountVat = ".GetSQLValueString($Acc_Result[9],'text').", ".
				 " Delivery_PromotionAcc = ".GetSQLValueString($Acc_Result[10],'text').", Delivery_TransportAccount = ".GetSQLValueString($Acc_Result[11],'text').", ".
				 " Delivery_CREDITACCcur = ".GetSQLValueString($Acc_Result[5],'text').", Delivery_CREDITACC = ".GetSQLValueString($Acc_Result[6],'text')." ".
				 " Where Delivery_ID = ".GetSQLValueString($sub_rows['Delivery_ID'],'double');
		
		$result=mysql_query($query,$connection);
		if (!$result){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
		
		
		if ($ErrorExists == 0) {
			$sub_query1 = " Select DeliveryDt_ID, DeliveryDt.Item_Code as Item_Code,ifNull(Item_Pack, 0) as Item_Pack, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
						  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Items.Item_NonStock,0) as Item_NonStock ".
						  " From DeliveryDt ".
						  " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						  " Where DeliveryDt.Delivery_ID = ".GetSQLValueString($sub_rows['Delivery_ID'],'double');
						  
			$sub_result1 = mysql_query($sub_query1,$connection);
			while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
				$ItemPack = $sub_rows1['Item_Pack']; 
				$txtItemCode = $sub_rows1['Item_Code']; 
				
				if ($ItemPack != 1) {
					$item_vat 	   = $sub_rows1['Item_Vat'];
					$ItemGroupCode = $sub_rows1['Group_code'];
					$ItemProd      = $sub_rows1['Item_Production'];
					$ItemTTCInc    = $sub_rows1['Item_TTCInclude'];
					$ItemPromo     = $sub_rows1['Item_Production'];
					$ItemNonStock  = $sub_rows1['Item_NonStock'];
					
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}
					
					// Get DirectStock Accounts
					$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditVATReturn, CreditAccountReturn, ".
							 " PromotionAccount, TipsAccount, CreditReturnNonStock, CreditVATReturnNonStock, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
							 " FROM salessetup ";
					$resulttrans = selectData($connection, $querytrans);
							
					$vSaStpDirectStkDbt = $resulttrans[0];
					$vSaStpDirectStkCrd = $resulttrans[1];
					$vSaStpDirectStkCur = $resulttrans[2];	
					$vSaStpDiscAcc      = $resulttrans[3];	
					$vSaStpVatAcc       = $resulttrans[4];	
					$vSaStpCreditVatAcc = $resulttrans[5];	
					$vSaStpCreditAcc    = $resulttrans[6];	
					$vSaStpPromoAcc     = $resulttrans[7];
					$vSaStpTipsAcc      = $resulttrans[8];
					$vSaStpCreditNonStockAcc    = $resulttrans[9];
					$vSaStpCreditVatNonStockAcc = $resulttrans[10];
					$vSaStpVatNonStockAcc 	  	= $resulttrans[11];
					$vSaStpCreditExportAcc	 	= $resulttrans[14];		
					
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $rwexp[0];	
					
					$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, ".
								"  Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export, trans_IncomeAcc ".
								" FROM transactionsetup ".
								" WHERE Journal_type = 'SR' AND Group_code = '".$ItemGroupCode."'  ";
							 
					$resulttrans = selectData($connection, $querytrans);
							
					$vTranStpDirectStkDbt = $resulttrans[0];
					$vTranStpDirectStkCrd = $resulttrans[1];
					$vTranStpDirectStkCur = $resulttrans[2];
					$vTranStpVatAcc       = $resulttrans[3];
					$vTranStpNonRmVatAcc  = $resulttrans[4];
					$vTranStpRmVatAcc     = $resulttrans[5];
					$vTranStpNonRmTTCIncAcc  = $resulttrans[6];
					$vTranStpRmTTCIncAcc     = $resulttrans[7];
					$vTranStpNonRmAcc        = $resulttrans[8];
					$vTranStpRmAcc           = $resulttrans[9];
					$vTranStpDiscAcc         = $resulttrans[10];
					$vTranStpPromoAcc        = $resulttrans[11]; 
					$vTranStpTipsAcc         = $resulttrans[12]; 
					$vTransStpExportAcc 	 = $resulttrans[13];
					$vTransStpIncomeAcc 	 = $resulttrans[14];
					
						if ($Module_RawMaterial == 1) {
					$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vSaDtDirectStkCur = $vTranStpDirectStkCur;
					$vSaDtVatAcc       = $vTranStpVatAcc;
					$vSaDtDiscAcc      = $vTranStpDiscAcc;
					$vSaDtPromoAcc     = $vTranStpPromoAcc;
					$vSaDtTipsAcc      = $vTranStpTipsAcc;
							
					if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
							if ($vTransStpIncomeAcc != '') $vSaDtItemAcc = $vTransStpIncomeAcc;
						}
						if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 		
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						//$vSaDtVatAcc       = $vSaStpVatAcc;
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
						$vSaDtPromoAcc     = $vSaStpPromoAcc;
						$vSaDtTipsAcc      = $vSaStpTipsAcc;
						
						if ($item_vat > 0 && $PRSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}

						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAcc;
						else	
							$vSaDtVatAcc = $vSaStpVatAcc;
						if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc;  
					}
					
						$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
						echo$adjustcost;
						$querydt = " update deliverydt set Deliverydt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Deliverydt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
								   " Deliverydt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Deliverydt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", ".
								   " Deliverydt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').", DeliveryDt_PromoAcc = ".GetSQLValueString($vSaDtPromoAcc,'text').", ".
								   " DeliveryDt_TipsAccount = ".GetSQLValueString($vSaDtTipsAcc,'text').", DeliveryDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')." ";
								   $queryc='';
						if($adjustcost == 1){  
						
							$query_cost = " select ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Delivery_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Delivery_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
							$result_cost = selectData($connection, $query_cost);
							
							$vSaDtCostBase1  = $result_cost[0]; 
							$vSaDtCostBase2  = $result_cost[1];
							$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_Code'], ($sub_rows['Delivery_Date']), $vSaDtCostBase1, $connection);
							
							if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
							if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
							if (empty($vSaDtCost)) $vSaDtCost = 0;
							
							$queryc = ", Deliverydt_Cost = ".GetSQLValueString($vSaDtCost,'double').", Deliverydt_Costbase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
									  ", Deliverydt_Costbase2 = ".GetSQLValueString($vSaDtCostBase2,'double');//echo$querydt;
						}		   
						$querydt .= $queryc." where DeliveryDt_id =".$sub_rows1['DeliveryDt_ID'];
						//echo $querydt."<br>";exit;				
						$resultdt=mysql_query($querydt,$connection);
						if (!$resultdt){
							$ErrorExists = 1;
							$message  = mysql_error($connection);
						}	
				} // end is not pack
				else {
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0) ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
								   
					$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
					while($rowspackdt=mysql_fetch_array($resultpackdt)){	
						$vItemCodePacked = $rowspackdt[0];
						$vItemCode = $rowspackdt[1];
						$vPackDtCostPer = $rowspackdt[2];
						$vPackDtPromo = $rowspackdt[3];
						$vPackDtPromoQty = $rowspackdt[4];
					
						$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$item_vat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd 	   = $result[3];
						$ItemTTCInc    = $result[4];
						$ItemUnit      = $result[5];
						$ItemNonStock  = $result[6];
						
						$tax_flag = 0;
						$notax_flag = 1;
						if ($item_vat > 0 && $PRSaVatChkbx == 1){
							$tax_flag = 1;
							$notax_flag = 0;
						}
						
							// Get DirectStock Accounts
						$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditVATReturn, CreditAccountReturn, ".
								 " PromotionAccount, TipsAccount, CreditReturnNonStock, CreditVATReturnNonStock, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS, creditaccountexport ".
								 " FROM salessetup ";
						$resulttrans = selectData($connection, $querytrans);
								
						$vSaStpDirectStkDbt = $resulttrans[0];
						$vSaStpDirectStkCrd = $resulttrans[1];
						$vSaStpDirectStkCur = $resulttrans[2];	
						$vSaStpDiscAcc      = $resulttrans[3];	
						$vSaStpVatAcc       = $resulttrans[4];	
						$vSaStpCreditVatAcc = $resulttrans[5];	
						$vSaStpCreditAcc    = $resulttrans[6];	
						$vSaStpPromoAcc     = $resulttrans[7];
						$vSaStpTipsAcc      = $resulttrans[8];
						$vSaStpCreditNonStockAcc    = $resulttrans[9];
						$vSaStpCreditVatNonStockAcc = $resulttrans[10];
						$vSaStpVatNonStockAcc 	  	= $resulttrans[11];
						$vSaStpCreditExportAcc	 	= $resulttrans[14];					
						
						$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
						$resexp = mysql_query($queryexp,$connection);
						$rwexp = mysql_fetch_row($resexp);
						$clientexp = $rwexp[0];		
					
						$querydt = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc,  ".
								 " Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc, trans_export, trans_IncomeAcc ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = 'SR' ".
								 " AND Group_code = '".$ItemGroupCode."'  ";
											 
						$resulttrans = selectData($connection, $querydt);
									
						$vTranStpDirectStkDbt = $resulttrans[0];
						$vTranStpDirectStkCrd = $resulttrans[1];
						$vTranStpDirectStkCur = $resulttrans[2];
						$vTranStpVatAcc       = $resulttrans[3];
						$vTranStpNonRmVatAcc  = $resulttrans[4];
						$vTranStpRmVatAcc     = $resulttrans[5];
						$vTranStpNonRmTTCIncAcc  = $resulttrans[6];
						$vTranStpRmTTCIncAcc     = $resulttrans[7];
						$vTranStpNonRmAcc        = $resulttrans[8];
						$vTranStpRmAcc           = $resulttrans[9];
						$vTranStpDiscAcc         = $resulttrans[10];
						$vTranStpPromoAcc        = $resulttrans[11]; 
						$vTranStpTipsAcc         = $resulttrans[12]; 
						$vTransStpExportAcc 	 = $resulttrans[13];
						$vTransStpIncomeAcc 	 = $resulttrans[14];
						
						if ($Module_RawMaterial == 1) {
							$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
							$vSaDtDirectStkCur = $vTranStpDirectStkCur;
							$vSaDtVatAcc       = $vTranStpVatAcc;
							$vSaDtDiscAcc      = $vTranStpDiscAcc;
							$vSaDtPromoAcc     = $vTranStpPromoAcc;
							$vSaDtTipsAcc      = $vTranStpTipsAcc;
										
							if ($item_vat > 0 && $PRSaVatChkbx == 1) {
								if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
							}
							else {
								if ($ItemProd == 1) {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
								}	
								else {
									if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
								}
								if($vTransStpIncomeAcc != '') $vSaDtItemAcc = $vTransStpIncomeAcc;
							}
							if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 		
						} 
						else {
							$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
							$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
							$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
							//$vSaDtVatAcc       = $vSaStpVatAcc;
							$vSaDtDiscAcc      = $vSaStpDiscAcc;
							$vSaDtPromoAcc     = $vSaStpPromoAcc;
							$vSaDtTipsAcc      = $vSaStpTipsAcc;
								
							if ($item_vat > 0 && $PRSaVatChkbx == 1) {
								if ($ItemNonStock == 1)
									$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
								else
									$vSaDtItemAcc = $vSaStpCreditVatAcc;
							} else {
								if ($ItemNonStock == 1)
									$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
								else	
									$vSaDtItemAcc = $vSaStpCreditAcc;
							}

							if ($ItemNonStock == 1)
								$vSaDtVatAcc = $vSaStpVatNonStockAcc;
							else	
								$vSaDtVatAcc = $vSaStpVatAcc;
							if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc;  
						}
						
						$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
						$sub_resultVat = selectData($connection, $sub_queryVat);
						if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
					}
						$querydt = " update deliverydt set Deliverydt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Deliverydt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
								   " Deliverydt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Deliverydt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", ".
								   " Deliverydt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').", DeliveryDt_PromoAcc = ".GetSQLValueString($vSaDtPromoAcc,'text').", ".
								   " DeliveryDt_TipsAccount = ".GetSQLValueString($vSaDtTipsAcc,'text').", DeliveryDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')." ";
						if($adjustcost == 1){  
						
							$query_cost = " select ifNull(MeanCostCur('".$vItemCode."', '".($sub_rows['Delivery_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
									  " ifNull(MeanCostCur('".$vItemCode."', '".($sub_rows['Delivery_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
							$result_cost = selectData($connection, $query_cost);
							
							$vSaDtCostBase1  = $result_cost[0]; 
							$vSaDtCostBase2  = $result_cost[1];
							$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_Code'], ($sub_rows['Delivery_Date']), $vSaDtCostBase1, $connection);
							
							if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
							if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
							if (empty($vSaDtCost)) $vSaDtCost = 0;
							
							$querydt .= ", SaleDt_Price = ".GetSQLValueString($vSaDtCost,'double').", SaleDt_PriceBase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
									  ", SaleDt_PriceBase2 = ".GetSQLValueString($vSaDtCostBase2,'double');
						}		   
							$querydt .=" where DeliveryDt_id =".$sub_rows1['DeliveryDt_ID'];
						//echo $query."<br>";exit;				
						$resultdt=mysql_query($querydt,$connection);
						if (!$resultdt){
							$ErrorExists = 1;
							$message  = mysql_error($connection);
						}	
					
				} //end is pack
			} //end while deliverydt loop
			
			
			if($ErrorExists == 0 && $adjustcost == 1 && $Module_Delivery == 0) {
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' )";
				$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];
				
				$CalculateResult = Calculate_MasterAmountsdelivery($sub_rows['Delivery_ID'], $sub_rows['DeliveryDate'], $PSaVatChkbx,$sub_rows['Delivery_DiscountPer'], $sub_rows['Delivery_DiscountAmount'], $sub_rows['Delivery_transportAmount'], $sub_rows['Delivery_BonusAmount'], $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'U', $connection);
				$message  = $message . $CalculateResult;
			}
			if ($Module_PostToJournal == 1 && $ErrorExists == 0) {
				$message = Create_DeliveryJv($sub_rows['Delivery_ID'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
			}
		}
	}	
				 
				 
	if ($message == "") {
		$message = 'Delivery Transactions Reposted Successfully.';
	}
		
	
}

else if ( $transtype == 'SR') {
	$message = '';
	$ErrorExists = 0;
	 
	$sub_query = " Select Sale_id, Sale_Date, sales.Client_code as Client_code, sales.Currency_code as Currency_code, ifNull(sale_chkvat,0) as sale_chkvat, sale_discountper, sale_discountamount, 
				Sale_BonusAmount, Sale_TransportAmount,Sale_WHTchecked, WHTPercentage, Date_format(sales.Sale_Date,'%Y%m%d') as SaleDate ".
				 " From sales ".
				 " inner join clients on clients.Ledger_number = sales.Client_code".
				 " Where sales.Journal_Type = 'SR' ".
				 " And ifNull(sales.Sale_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(sales.Sale_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(sales.Sale_Reference, -1)) ".
				 " And Date_format(sales.Sale_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) ".
				 " And Date_format(sales.Sale_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(sales.Sale_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$txtClientCode = $sub_rows['Client_code'];
		$vSaVatChkbx = $sub_rows['sale_chkvat'];
		
		$query1 = "Select Client_VAT From clients Where ledger_number = '".$txtClientCode."'";
		
		$res1 = selectData($connection, $query1);
		$vClientVat = $res1[0];
		
		$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, CreditCur, CreditAccount, TipsAccount, ".
					 " VatAccount, CreditAccountVAT, Sale_CLAAccount, Sale_DCTAccount, Sale_AWAccount, Sale_TRPAccount, PromotionAccount, ".
					 " TransportAccount, BonusAccount, CreditAccountNonStock, CreditAccountVatNonStock ".
					 " FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$vSaVatAcc = $Acc_Result[8];
		$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaVatAcc."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
	
		$update = " update sales set Sale_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Sale_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", Sale_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", ".
				  " Sale_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", Sale_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Sale_CreditCur = ".GetSQLValueString($Acc_Result[5],'text').", ".
				  " Sale_CreditAccount = ".GetSQLValueString($Acc_Result[6],'text').", Sale_TipsAccount = ".GetSQLValueString($Acc_Result[7],'text').", Sale_Vataccount = ".GetSQLValueString($Acc_Result[8],'text').", ".
				  " Sale_creditaccountvat = ".GetSQLValueString($Acc_Result[9],'text').", Sale_CreditCLA = ".GetSQLValueString($Acc_Result[10],'text').", Sale_CreditDCT =".GetSQLValueString($Acc_Result[11],'text').", ".
				  " Sale_CreditAW = ".GetSQLValueString($Acc_Result[12],'text').", Sale_CreditTRP = ".GetSQLValueString($Acc_Result[13],'text').", Sale_PromotionAcc = ".GetSQLValueString($Acc_Result[14],'text').",  ".
				  " Sale_TransportAccount = ".GetSQLValueString($Acc_Result[15],'text').", Sale_BonusAccount = ".GetSQLValueString($Acc_Result[16],'text')." ".
				  " where sale_id = ".$sub_rows['Sale_id']; 
		$resupdate = mysql_query($update,$connection);		  
		if (!$resupdate){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
			if ($ErrorExists == 0) {
				$sub_query1 = " Select SaleDt_id, salesdt.Item_code as Item_code,  ifNull(Item_Pack, 0) as Item_Pack, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
						  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Item_Promotion, 0) as Item_Promotion,  ifNull(Items.Item_NonStock,0) as Item_NonStock ".
						  " From salesdt ".
						  " Inner Join Items on salesdt.Item_code = Items.Item_Code ".
						  " Where salesdt.Sale_id = ".GetSQLValueString($sub_rows['Sale_id'],'double');
						  
				$sub_result1 = mysql_query($sub_query1,$connection);
				while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
					$item_vat 	   = $sub_rows1['Item_Vat'];
					$ItemGroupCode = $sub_rows1['Group_code'];
					$ItemProd      = $sub_rows1['Item_Production'];
					$ItemTTCInc    = $sub_rows1['Item_TTCInclude'];
					$ItemPromo     = $sub_rows1['Item_Promotion'];
					$ItemNonStock  = $sub_rows1['Item_NonStock'];
					$txtItemCode   = $sub_rows1['Item_code'];
					$txtsaledt_id   = $sub_rows1['SaleDt_id'];
					// Get DirectStock Accounts
					$querytrans = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, ".
							 " CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS ".
							 " FROM salessetup ";
									 
					$resulttrans = selectData($connection, $querytrans);
							
					$vSaStpDirectStkDbt = $resulttrans[0];
					$vSaStpDirectStkCrd = $resulttrans[1];
					$vSaStpDirectStkCur = $resulttrans[2];	
					$vSaStpDiscAcc      = $resulttrans[3];	
					$vSaStpCreditVatAcc = $resulttrans[4];	
					$vSaStpCreditAcc    = $resulttrans[5];	
					
					$vSaStpCreditNonStockAcc    = $resulttrans[6];
					$vSaStpCreditVatNonStockAcc = $resulttrans[7];
					$vSaStpVatAcc 		  	  	= $resulttrans[8];
					$vSaStpVatNonStockAcc 	  	= $resulttrans[9];
					$vSaStpVatAccCash	  	  	= $resulttrans[10];
					$vSaStpVatNonStockAccCash 	= $resulttrans[11];
							
					$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$txtClientCode."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$clientexp = $rwexp[0];
					
					$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, trans_export, ledger_costAcc ".
						 " FROM transactionsetup ".
						 " WHERE Journal_type = 'SR' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
								 
					$resulttrans = selectData($connection, $querytrans);
							
					$vTranStpDirectStkDbt = $resulttrans[0];
					$vTranStpDirectStkCrd = $resulttrans[1];
					$vTranStpDirectStkCur = $resulttrans[2];
					$vTranStpVatAcc       = $resulttrans[3];
					$vTranStpNonRmVatAcc  = $resulttrans[4];
					$vTranStpRmVatAcc     = $resulttrans[5];
					$vTranStpNonRmTTCIncAcc  = $resulttrans[6];
					$vTranStpRmTTCIncAcc     = $resulttrans[7];
					$vTranStpNonRmAcc        = $resulttrans[8];
					$vTranStpRmAcc           = $resulttrans[9];
					$vTranStpDiscAcc         = $resulttrans[10];
					$vLedger_costAcc		 = $resulttrans[12];
					$vLedger_Account		 = $resulttrans[1];
					
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
								
						if ($item_vat > 0 && $vSaVatChkbx == 1) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
						}	
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
								
						if ($item_vat > 0 && $vSaVatChkbx == 1) {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
							else
								$vSaDtItemAcc = $vSaStpCreditVatAcc;
						} else {
							if ($ItemNonStock == 1)
								$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
							else	
								$vSaDtItemAcc = $vSaStpCreditAcc;
						}

						if ($ItemNonStock == 1)
							$vSaDtVatAcc = $vSaStpVatNonStockAcc;
						else	
							$vSaDtVatAcc = $vSaStpVatAcc;
					}
					
					if($clientexp == 1) $vSaDtItemAcc = $result[11]; 
				
					$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
					
					$querydt =  " update salesdt set Saledt_DirectStkDbt = ".GetSQLValueString($vSaDtDirectStkDbt,'text').", Saledt_DirectStkCrd = ".GetSQLValueString($vSaDtDirectStkCrd,'text').", ".
								" Saledt_DirectStkCur = ".GetSQLValueString($vSaDtDirectStkCur,'text').", Saledt_discountacc = ".GetSQLValueString($vSaDtDiscAcc,'text').", Saledt_ItemAccount = ".GetSQLValueString($vSaDtItemAcc,'text').", ".
								" SaleDt_VatAccount = ".GetSQLValueString($vSaDtVatAcc,'text')." , salesdt_CostAcc = ".GetSQLValueString($vLedger_costAcc,'text').", ".
								" salesdt_Account = ".GetSQLValueString($vLedger_Account,'text')." ";
					/* if($adjustcost == 1){  
						
						$query_cost = " select ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Sale_Date'])."', 1, '', ''),0) MeanCostAmountB1 ,  ".
								  " ifNull(MeanCostCur('".$txtItemCode."', '".($sub_rows['Sale_Date'])."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
						$result_cost = selectData($connection, $query_cost);
						
						$vSaDtCostBase1  = $result_cost[0]; 
						$vSaDtCostBase2  = $result_cost[1];
						$vSaDtCost=ConvertCurrency($Base1, $sub_rows['Currency_code'], ($sub_rows['Sale_Date']), $vSaDtCostBase1, $connection);
						
						if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
						if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
						if (empty($vSaDtCost)) $vSaDtCost = 0;
						
						$querydt .= ", SaleDt_Price = ".GetSQLValueString($vSaDtCost,'double').", SaleDt_PriceBase1 = ".GetSQLValueString($vSaDtCostBase1,'double').
								  ", SaleDt_PriceBase2 = ".GetSQLValueString($vSaDtCostBase2,'double');
					} */
					$querydt .= " where SaleDt_id = ".$sub_rows1['SaleDt_id'];			 
					//echo $querydt;exit;
					$resultdt=mysql_query($querydt,$connection);
					if (!$resultdt){
						$ErrorExists = 1;
						$message  = mysql_error($connection);
					}
				} // end while salesdt loop
				
				if($ErrorExists == 0){
					/* if($adjustcost == 1){  
						$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_code']."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_code']."' )";
						$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];
						
						$CalculateResult = Calculate_salesMasterAmounts($sub_rows['Sale_id'], $sub_rows['SaleDate'], $vSaVatChkbx, $sub_rows['sale_discountper'],$sub_rows['sale_discountamount'], $sub_rows['Sale_TransportAmount'], 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC,$sub_rows['Sale_WHTchecked'],$sub_rows['WHTPercentage'], 'U', $connection);
						$message  = $message . $CalculateResult;
						
					} */
					if ($Module_PostToJournal == 1)	{
						$message = Create_SalesJv($sub_rows['Sale_id'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
					}
					
				}
			}//end if error exists	
	} //end while sales loop
	
	if ($message == "") {
		$message = 'Delivery Transactions Reposted Successfully.';
	}
}

else if ($transtype == 'PR'){
	$message = '';
	$ErrorExists = 0;
	
	$sub_query = " Select Purchase_ID, Purchase_Date, Supplier_Code, Currency_Code, ifNull(Purchase_VatChkbx,0) as Purchase_VatChkbx ".
				 " From Purchases ".
				 " Where Purchases.Journal_Type = 'PR' ".
				 " And Upper(Purchase_Type) != 'PENDING' ".
				 " And ifNull(Purchases.Purchase_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Purchases.Purchase_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Purchases.Purchase_Reference, -1)) ".
				 " And Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) ".
				 " And Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Purchases.Purchase_Date,'%Y-%m-%d'))  ";
	//echo $sub_query; exit;			 
	$sub_result = mysql_query($sub_query,$connection);
	while ($sub_rows=mysql_fetch_assoc($sub_result)) {
		$PPurSupplier = $sub_rows['Supplier_Code'];
		$PPurVatChkbx = $sub_rows['Purchase_VatChkbx'];
		
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$sub_rows['Currency_Code']."') As DebitCur, ".
					 " FreightDebitAccount, FreightCreditAccount, CommissionsDebitAccount, CommissionsCreditAccount, ".
					 " InsuranceDebitAccount, InsuranceCreditAccount, ClearingDebitAccount, ClearingCreditAccount, ".
					 " TransportDebitAccount, TransportCreditAccount, OtherDebitAccount, OtherCreditAccount, ".
					 " CustomsDebitAccount, CustomsCreditAccount ".
					 " FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
			 
		$query = " Update Purchases SET ".
				 " Purchase_Acctax1 = ".GetSQLValueString($Acc_Result[0],'text').", Purchase_Acctax2 = ".GetSQLValueString($Acc_Result[1],'text').", ".
				 " Purchase_Acctax3 = ".GetSQLValueString($Acc_Result[2],'text').", Purchase_Acctax4 = ".GetSQLValueString($Acc_Result[3],'text').", ".
				 " Purchase_Acctax5 = ".GetSQLValueString($Acc_Result[4],'text').", Purchase_DebitCur = ".GetSQLValueString($Acc_Result[6],'text').", ".
				 " Purchase_DebitAccount = ".GetSQLValueString($Acc_Result[5],'text').", ".
				 " FreightDebitAccount = ".GetSQLValueString($Acc_Result[7],'text').", FreightCreditAccount = ".GetSQLValueString($Acc_Result[8],'text').", ".
				 " CommissionsDebitAccount = ".GetSQLValueString($Acc_Result[9],'text').", CommissionsCreditAccount = ".GetSQLValueString($Acc_Result[10],'text').", ".
				 " InsuranceDebitAccount = ".GetSQLValueString($Acc_Result[11],'text').", InsuranceCreditAccount = ".GetSQLValueString($Acc_Result[12],'text').", ".
				 " ClearingDebitAccount = ".GetSQLValueString($Acc_Result[13],'text').", ClearingCreditAccount = ".GetSQLValueString($Acc_Result[14],'text').", ".
				 " TransportDebitAccount = ".GetSQLValueString($Acc_Result[15],'text').", TransportCreditAccount = ".GetSQLValueString($Acc_Result[16],'text').", ".
				 " OtherDebitAccount = ".GetSQLValueString($Acc_Result[17],'text').", OtherCreditAccount = ".GetSQLValueString($Acc_Result[18],'text').", ".
				 " CustomsDebitAccount = ".GetSQLValueString($Acc_Result[19],'text').", CustomsCreditAccount = ".GetSQLValueString($Acc_Result[20],'text').
				 " Where Purchase_ID = ".GetSQLValueString($sub_rows['Purchase_ID'],'double');
		
		$result=mysql_query($query,$connection);
		if (!$result){
			$ErrorExists = 1;
			$message  = mysql_error($connection);
		}	
		
		
		if ($ErrorExists == 0) {
			$sub_query1 = " Select PurchaseDt_ID, PurchasesDt.Item_Code as Item_Code, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ifNull(Items.Item_Production, 0) as Item_Production, ".
						  " ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, ifNull(Items.Item_NonStock,0) as Item_NonStock, ifNull(Item_VatType, 1) as Item_VatType ".
						  " From PurchasesDt ".
						  " Inner Join Items on PurchasesDt.Item_Code = Items.Item_Code ".
						  " Where PurchasesDt.Purchase_ID = ".GetSQLValueString($sub_rows['Purchase_ID'],'double');
						  
			$sub_result1 = mysql_query($sub_query1,$connection);
			while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
				
				$txtItemCode = $sub_rows1['Item_Code'];
				
				if ($ItemPack != 1) {
					
					$item_vat 	   = $sub_rows1['Item_Vat'];
					$ItemGroupCode = $sub_rows1['Group_code'];
					$ItemProd 	   = $sub_rows1['Item_Production'];
					$ItemTTCInc	   = $sub_rows1['Item_TTCInclude'];
					$ItemNonStock  = $sub_rows1['Item_NonStock'];
					$ItemVatType   = $sub_rows1['Item_VatType'];
					$txtsaledt_id   = $sub_rows1['SaleDt_id'];
			
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
				
					$vPurDtDirectStkDbt 	= '';
					$vPurDtDirectStkCrd 	= '';
					$vPurDtDirectStkCur 	= '';
					$vPurDtVatAcc	    	= '';
					$vPurDtItemAcc      	= '';
					$vPurStpDirectStkDbt 	= '';
					$vPurStpDirectStkCrd 	= '';
					$vPurStpDirectStkCur 	= '';
					$vPurStpVatAcc       	= '';
					$vPurStpDebitAcc     	= '';
					$vTranStpDirectStkDbt 	= '';
					$vTranStpDirectStkCrd 	= '';
					$vTranStpDirectStkCur 	= '';
					$vTranStpVatAcc       	= '';
					$vTranStpNonRmVatAcc  	= '';
					$vTranStpRmVatAcc     	= '';
					$vTranStpNonRmTTCIncAcc = '';
					$vTranStpRmTTCIncAcc    = '';
					$vTranStpNonRmAcc  		= '';
					$vTranStpRmAcc     		= '';
					$vPurStpDebitExportAcc	= '';
					$vTransExport			= '';
					
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock, ".
							 " VatAccount2, VatAccount3, VATAccountNonStock2, VATAccountNonStock3, DebitAccount2, DebitAccount3, DebitAccountVAT, ".
							 " DebitAccountVat2, DebitAccountVat3, DebitAccountNonStock, DebitAccountNonStock2, DebitAccountNonStock3, DebitAccountVATNonStock, ".
							 " DebitAccountVATNonStock2, DebitAccountVATNonStock3, debitaccountexport  ".
							 " FROM purchasesetup ";
				 
					$result = selectData($connection, $query);
						
					$vPurStpDirectStkDbt   = $result[0];
					$vPurStpDirectStkCrd   = $result[1];
					$vPurStpDirectStkCur   = $result[2];	
					$vPurStpVatAcc         = $result[3];	
					$vPurStpDebitAcc       = $result[4];	
					$vPurStpVatNonStockAcc = $result[5];	
								
					$vPurStpVatAcc2         	= $result[6];
					$vPurStpVatAcc3         	= $result[7];
					$vPurStpVatNonStockAcc2 	= $result[8];
					$vPurStpVatNonStockAcc3 	= $result[9];
					$vPurStpDebitAcc2       	= $result[10];
					$vPurStpDebitAcc3       	= $result[11];
					$vPurStpDebitVatAcc     	= $result[12];
					$vPurStpDebitVatAcc2    	= $result[13];
					$vPurStpDebitVatAcc3    	= $result[14];
					$vPurStpDebitNonStockAcc  	 = $result[15];
					$vPurStpDebitNonStockAcc2 	 = $result[16];
					$vPurStpDebitNonStockAcc3 	 = $result[17];
					$vPurStpDebitVatNonStockAcc  = $result[18];
					$vPurStpDebitVatNonStockAcc2 = $result[19];
					$vPurStpDebitVatNonStockAcc3 = $result[20];
					$vPurStpDebitExportAcc	 	 = $result[21];	
				
					$queryexp = "select ifnull(Supplier_Export,0) from suppliers where Ledger_number =  '".ereg_replace("'", "\'", trim($PPurSupplier))."' ";	
					$resexp = mysql_query($queryexp,$connection);
					$rwexp = mysql_fetch_row($resexp);
					$supplierexp = $rwexp[0];
					
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PR' ".
							 " 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];
					$vTransExport     		= $result[10];
					
				if ($Module_RawMaterial == 1) {
					$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vPurDtDirectStkCur = $vTranStpDirectStkCur;
					$vPurDtVatAcc       = $vTranStpVatAcc;
						
					if ($item_vat > 0 && $PPurVatChkbx == 1) {
						if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
						}
					}	
					if($supplierexp == 1) $vPurDtItemAcc = $vTransExport; 	
				} 
				else {
					$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
					$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
					$vPurDtDirectStkCur = $vPurStpDirectStkCur;	
			
					if ($ItemNonStock == 1)	{
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatNonStockAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatNonStockAcc3;
					}	
					else {
						if ($ItemVatType == 1)		$vPurDtVatAcc = $vPurStpVatAcc;
						else if ($ItemVatType == 2)	$vPurDtVatAcc = $vPurStpVatAcc2;
						else if ($ItemVatType == 3)	$vPurDtVatAcc = $vPurStpVatAcc3;
					}	
				 
					if ($item_vat > 0 && $PPurVatChkbx == 1) {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitVatAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitVatAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitVatAcc3;
						}
					}	
					else {
						if ($ItemNonStock == 1)	{
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitNonStockAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitNonStockAcc3;
						}	
						else {
							if ($ItemVatType == 1)		$vPurDtItemAcc = $vPurStpDebitAcc;
							else if ($ItemVatType == 2)	$vPurDtItemAcc = $vPurStpDebitAcc2;
							else if ($ItemVatType == 3)	$vPurDtItemAcc = $vPurStpDebitAcc3;
						}						
					}	
					
					if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 
				} 
					
					$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
					$querydt = " update purchasesdt set Purchasedt_DirectStkDbt = ".GetSQLValueString($vPurDtDirectStkDbt,'text').", Purchasedt_DirectStkCrd = ".GetSQLValueString($vPurDtDirectStkCrd,'text').", ".
							   " Purchasedt_DirectStkCur = ".GetSQLValueString($vPurDtDirectStkCur,'text').", PurchaseDt_VATAccount = ".GetSQLValueString($vPurDtVatAcc,'text').", ".
							   " Purchasedt_ItemAccount = ".GetSQLValueString($vPurDtItemAcc,'text')." ".
							   " where PurchaseDt_id = ".$sub_rows1['PurchaseDt_ID'].";";
					
					//echo $querydt."<br>";//exit;				
					$resultdt=mysql_query($querydt,$connection);
				} // End Case Not Pack Item
				else {
				
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
							   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
				
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtCostPer = $rowspackdt[3];
						
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$item_vat	   = $result[0];
					$ItemGroupCode = $result[2];
					$ItemProd 	   = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemNonStock  = $result[6];
					
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	

					$vPurDtDirectStkDbt = '';
					$vPurDtDirectStkCrd = '';
					$vPurDtDirectStkCur = '';
					$vPurDtVatAcc	    = '';
					$vPurDtItemAcc      = '';
					$vPurStpDirectStkDbt = '';
					$vPurStpDirectStkCrd = '';
					$vPurStpDirectStkCur = '';
					$vPurStpVatAcc       = '';
					$vPurStpDebitAcc     = '';
					$vTranStpDirectStkDbt = '';
					$vTranStpDirectStkCrd = '';
					$vTranStpDirectStkCur = '';
					$vTranStpVatAcc       = '';
					$vTranStpNonRmVatAcc  = '';
					$vTranStpRmVatAcc     = '';
					$vTranStpNonRmTTCIncAcc  = '';
					$vTranStpRmTTCIncAcc     = '';
					$vTranStpNonRmAcc  = '';
					$vTranStpRmAcc     = '';
					$vPurStpDebitExportAcc	= '';
					$vTransExport			= '';
					
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock, debitaccountexport  ".
							 " FROM purchasesetup ";
							 
					$result = selectData($connection, $query);
					
					$vPurStpDirectStkDbt   = $result[0];
					$vPurStpDirectStkCrd   = $result[1];
					$vPurStpDirectStkCur   = $result[2];	
					$vPurStpVatAcc         = $result[3];	
					$vPurStpDebitAcc       = $result[4];	
					$vPurStpVatNonStockAcc = $result[5];
					$vPurStpDebitExportAcc = $result[6];	
					
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, trans_export ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PR' ".
							 " 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];
					$vTransExport     		= $result[10];
					
					if ($Module_RawMaterial == 1) {
						$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPurDtDirectStkCur = $vTranStpDirectStkCur;
						$vPurDtVatAcc       = $vTranStpVatAcc;
						
						if ($item_vat > 0 && $PPurVatChkbx == 1) {
							if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
							}
						}
						if($supplierexp == 1) $vPurDtItemAcc = $vTransExport;
					} 
					else {
						$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
						$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
						
						if ($ItemNonStock == 1)		
							$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else
							$vPurDtVatAcc = $vPurStpVatAcc;
						
						if ($item_vat > 0 && $PPurVatChkbx == 1)
							$vPurDtItemAcc = $vPurStpVatAcc;
						else
							$vPurDtItemAcc = $vPurStpDebitAcc;	
						if($supplierexp == 1) $vPurDtItemAcc = $vPurStpDebitExportAcc; 
					}
						
					$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
						
					$querydt = " update purchasesdt set Purchasedt_DirectStkDbt = ".GetSQLValueString($vPurDtDirectStkDbt,'text').", Purchasedt_DirectStkCrd = ".GetSQLValueString($vPurDtDirectStkCrd,'text').", ".
							   " Purchasedt_DirectStkCur = ".GetSQLValueString($vPurDtDirectStkCur,'text').", PurchaseDt_VATAccount = ".GetSQLValueString($vPurDtVatAcc,'text').", ".
							   " Purchasedt_ItemAccount = ".GetSQLValueString($vPurDtItemAcc,'text')." ".
							   " where PurchaseDt_id = ".$sub_rows1['PurchaseDt_ID'].";";
					//	echo $querydt;	 
					$resultdt = mysql_query($querydt,$connection);
						
				} // End Loop Of Packdt
			} // End CasePack Item
				if (!$resultdt){
					$ErrorExists = 1;
					$message  = mysql_error($connection);
					Break;
				}
					
			} 
			
			if ($Module_PostToJournal == 1 && $ErrorExists == 0) {
				$queryBlg = "select Purchase_BelongsToGroup from purchases where purchase_id = ".$sub_rows['Purchase_ID'];
				$resBlg = mysql_query($queryBlg,$connection);
				$rowBlg = mysql_fetch_row($resBlg);
				$BelongsToGrp = $rowBlg[0];
				$message = Create_PurchaseJv($sub_rows['Purchase_ID'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'],$BelongsToGrp); 
			}
		}
	}	
				 
				 
	if ($message == "") {
		$message = 'Purchase Transactions Reposted Successfully.';
	}

}	

else if( $transtype == 'PD'){
	$message = '';
	$ErrorExists = 0;
	if($module_newproduction == 0){
		$sub_query = " Select Production_id, Date_format(Production_Date,'%d/%m/%Y') as Production_Date, production.Currency_Code as Currency_Code, production.Item_Code as Item_Code, Item_Vat, Group_code, ifNull(Item_Production, 0) as Item_Production, ifNull(Item_TTCInclude, 0) as Item_TTCInclude ".
					 " From production ".
					 " inner join items on items.item_code = production.item_code ".
					 " Where ".
					 " ifNull(production.Production_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(production.Production_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(production.Production_Reference, -1)) ".
					 " And Date_format(production.Production_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(production.Production_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(production.Production_Date,'%Y-%m-%d')) ".
					 " And Date_format(production.Production_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(production.Production_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(production.Production_Date,'%Y-%m-%d')) 
						";
		 
		$sub_result = mysql_query($sub_query,$connection);
		while ($sub_rows=mysql_fetch_assoc($sub_result)) {
			$vPrdItemCode  = $sub_rows['Item_Code'];
			$ItemVat 	   = $sub_rows['ItemVat'];
			$ItemGroupCode = $sub_rows['Group_code'];
			$ItemProd  	   = $sub_rows['Item_Production'];
			$ItemTTCInc    = $sub_rows['Item_TTCInclude'];
			
			$vPrdDirectStkDbt = '';
			$vPrdDirectStkCrd = '';
			$vPrdDirectStkCur = '';
			$vPrdWasteDbtAcc  = '';
			$vPrdWasteCrdAcc  = '';
			$vPrdWasteDifAcc  = '';
			$vPrdItemAcc      = '';
			
			$sub_query11 = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
					 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PD' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
			//echo $sub_query; exit;			 
			$sub_result11 = selectData($connection, $sub_query11);
					
			$vTranStpDirectStkDbt = $sub_result11[0];
			$vTranStpDirectStkCrd = $sub_result11[1];
			$vTranStpDirectStkCur = $sub_result11[2];
			$vTranStpWasteDbtAcc  = $sub_result11[3];
			$vTranStpWasteCrdAcc  = $sub_result11[4];
			$vTranStpWasteDifAcc  = $sub_result11[5];
			$vTranStpNonRmVatAcc  = $sub_result11[6];
			$vTranStpRmVatAcc     = $sub_result11[7];
			$vTranStpNonRmTTCIncAcc  = $sub_result11[8];
			$vTranStpRmTTCIncAcc     = $sub_result11[9];
			$vTranStpNonRmAcc        = $sub_result11[10];
			$vTranStpRmAcc           = $sub_result11[11];
					
			$vPrdDirectStkDbt = $vTranStpDirectStkDbt;
			$vPrdDirectStkCrd = $vTranStpDirectStkCrd;
			$vPrdDirectStkCur = $vTranStpDirectStkCur;
			$vPrdWasteDbtAcc  = $vTranStpWasteDbtAcc;
			$vPrdWasteCrdAcc  = $vTranStpWasteCrdAcc;
			$vPrdWasteDifAcc  = $vTranStpWasteDifAcc;
						
			if ($ItemVat > 0) {
				if ($ItemProd == 1)	$vPrdItemAcc = $vTranStpNonRmVatAcc; else $vPrdItemAcc = $vTranStpRmVatAcc;
			}
			else {
				if ($ItemProd == 1) {
					if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdItemAcc = $vTranStpNonRmAcc;
				}	
				else {
					if ($ItemTTCInc == 1) $vPrdItemAcc = $vTranStpRmTTCIncAcc; else $vPrdItemAcc = $vTranStpRmAcc;
				}
			}
			
			$query = " update production set Production_ItemAccount = ".GetSQLValueString($vPrdItemAcc, 'text').", Production_DirectStkDbt = ".GetSQLValueString($vPrdDirectStkDbt, 'text').", ".
				 " Production_DirectStkCrd = ".GetSQLValueString($vPrdDirectStkCrd, 'text').", Production_DirectStkCur = ".GetSQLValueString($vPrdDirectStkCur, 'text').", ".
				 " Production_WasteDebit = ".GetSQLValueString($vPrdWasteDbtAcc, 'text').", Production_WasteCredit = ".GetSQLValueString($vPrdWasteCrdAcc, 'text').", ".
				 " Production_WasteDiff = ".GetSQLValueString($vPrdWasteDifAcc, 'text')." ".
				 " where Production_ID = ".$sub_rows['Production_id'].";"; 	
			$result = mysql_query($query,$connection);
			if (!$result){
				$ErrorExists = 1;
				$message  = mysql_error($connection);
			}	
		
			if($ErrorExists == 0){
				$sub_query1 = " select ProductionDt_id, productiondt.Item_Code as Item_Code, ifNull(Item_Pack, 0) as Item_Pack, Items.Item_Vat as Item_Vat, Items.Group_code as Group_code, ".
							  " ifNull(Items.Item_Production, 0) as Item_Production, ifNull(Items.Item_TTCInclude, 0) as Item_TTCInclude, Items.Currency_Code as Currency_Code, ".
							  " ifNull(Items.Item_CostMethod,0) as Item_CostMethod, ifNull(Items.Item_NonStock,0) as Item_NonStock ".
							  " From productiondt ".
							  " Inner Join Items on Items.Item_Code = productiondt.Item_Code ".
							  " Where productiondt.Production_id = ".GetSQLValueString($sub_rows['Production_id'],'double');
						
				$sub_result1 = mysql_query($sub_query1,$connection);
				while ($sub_rows1=mysql_fetch_assoc($sub_result1)) {
					
					
					$ItemPack    = $sub_rows1['Item_Pack'];
					$txtItemCode = $sub_rows1['Item_Code'];
					if ($ItemPack != 1) {
							
						$ItemVat 	     = $sub_rows1['Item_Vat'];
						$ItemGroupCode   = $sub_rows1['Group_code'];
						$ItemProd        = $sub_rows1['Item_Production'];
						$ItemTTCInc      = $sub_rows1['Item_TTCInclude'];
						$ItemCurr		 = $sub_rows1['Currency_Code'];
						$ItemCostMethod  = $sub_rows1['Item_CostMethod'];
						$ItemNonStock    = $sub_rows1['Item_NonStock'];
							
						$vPrdDtDirectStkDbt = '';
						$vPrdDtDirectStkCrd = '';
						$vPrdDtDirectStkCur = '';
						$vPrdDtWasteDbtAcc  = '';
						$vPrdDtWasteCrdAcc  = '';
						$vPrdDtItemAcc      = '';
					
						$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
									 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
									 " FROM transactionsetup ".
									 " WHERE Journal_type = 'PD' ".
									 " AND Group_code = '".$ItemGroupCode."'  ";
												 
						$resulttrans = selectData($connection, $querytrans);
										
						$vTranStpDirectStkDbt 	= $resulttrans[0];
						$vTranStpDirectStkCrd 	= $resulttrans[1];
						$vTranStpDirectStkCur 	= $resulttrans[2];
						$vTranStpWasteDbtAcc  	= $resulttrans[3];
						$vTranStpWasteCrdAcc  	= $resulttrans[4];
						$vTranStpWasteDifAcc  	= $resulttrans[5];
						$vTranStpNonRmVatAcc  	= $resulttrans[6];
						$vTranStpRmVatAcc     	= $resulttrans[7];
						$vTranStpNonRmTTCIncAcc = $resulttrans[8];
						$vTranStpRmTTCIncAcc    = $resulttrans[9];
						$vTranStpNonRmAcc       = $resulttrans[10];
						$vTranStpRmAcc          = $resulttrans[11];
								
						$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
						$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
						$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
									
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
							}
						}
										
						$querydt = " update productiondt set ProductionDt_ItemAccount = ".GetSQLValueString($vPrdDtItemAcc,'text').", ProductionDt_DirectStkDbt = ".GetSQLValueString($vPrdDtDirectStkDbt,'text').", ".
								   " ProductionDt_DirectStkCrd = ".GetSQLValueString($vPrdDtDirectStkCrd,'text').", ProductionDt_DirectStkCur = ".GetSQLValueString($vPrdDtDirectStkCur,'text').", ".
								   " ProductionDt_WasteDebit = ".GetSQLValueString($vPrdDtWasteDbtAcc,'text').", ProductionDt_WasteCredit = ".GetSQLValueString($vPrdDtWasteCrdAcc,'text')."  ";
						if ($adjustcost == 1){
							$vPrdDtCost      = Get_CostPrice($txtItemCode, $ItemCurr, $ItemCostMethod, $sub_rows['Production_Date'], $sub_rows['Currency_Code'], $Base1, $Base2, $connection);
							$vPrdDtCostBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, insertMySQLDate($sub_rows['Production_Date']), $vPrdDtCost, $connection);
							$vPrdDtCostBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2,insertMySQLDate($sub_rows['Production_Date']), $vPrdDtCost, $connection);
							if (empty($vPrdDtCostBase1)) $vPrdDtCostBase1 = 0;
							if (empty($vPrdDtCostBase2)) $vPrdDtCostBase2 = 0;
							$querydt .=  " ,ProductionDt_cost= $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2 ";					
						}
						$querydt .=  " where ProductionDt_ID = ".$sub_rows1['ProductionDt_id'] .";"; //echo $querydt."<br> ";//exit;	
						$resultdt=mysql_query($querydt,$connection);
					}	// End Case Not Pack Item
						
					else {
						$packdt_query = " SELECT Item_Code, Item_CodePackDt, PackDt_CostPercentage ".
									" FROM PackDt ".
									" WHERE Item_Code = '".$txtItemCode."'  ";
										   
						$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
					while($packdt_rows=mysql_fetch_array($packdt_result)){
					
						$vItemCodePacked = $packdt_rows[0];
						$vItemCode 		 = $packdt_rows[1];
						$vPackDtCostPer  = $packdt_rows[2];
												
						$vPrdDtDirectStkDbt = '';
						$vPrdDtDirectStkCrd = '';
						$vPrdDtDirectStkCur = '';
						$vPrdDtWasteDbtAcc  = '';
						$vPrdDtWasteCrdAcc  = '';
						$vPrdDtItemAcc      = '';
						
						$sub_query2 = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), Currency_Code, ".
									 " ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0) ".
									 " FROM Items WHERE Item_Code = '".$vItemCode."'";
						$sub_result2 = selectData($connection, $sub_query2);
						$ItemVat 	     = $sub_result2[0];
						$ItemGroupCode   = $sub_result2[1];
						$ItemProd        = $sub_result2[2];
						$ItemTTCInc      = $sub_result2[3];
						$ItemCurr		 = $sub_result2[4];
						$ItemCostMethod  = $sub_result2[5];
						$ItemNonStock    = $sub_result2[6];
						
						$querytrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
									 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
									 " FROM transactionsetup ".
									 " WHERE Journal_type = 'PD' ".
									 " AND Group_code = '".$ItemGroupCode."'  ";
											 
						$restrans = selectData($connection, $querytrans);
									
						$vTranStpDirectStkDbt 	= $restrans[0];
						$vTranStpDirectStkCrd 	= $restrans[1];
						$vTranStpDirectStkCur 	= $restrans[2];
						$vTranStpWasteDbtAcc  	= $restrans[3];
						$vTranStpWasteCrdAcc  	= $restrans[4];
						$vTranStpWasteDifAcc  	= $restrans[5];
						$vTranStpNonRmVatAcc  	= $restrans[6];
						$vTranStpRmVatAcc     	= $restrans[7];
						$vTranStpNonRmTTCIncAcc = $restrans[8];
						$vTranStpRmTTCIncAcc    = $restrans[9];
						$vTranStpNonRmAcc       = $restrans[10];
						$vTranStpRmAcc          = $restrans[11];
									
						$vPrdDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPrdDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPrdDtDirectStkCur = $vTranStpDirectStkCur;
						$vPrdDtWasteDbtAcc  = $vTranStpWasteDbtAcc;
						$vPrdDtWasteCrdAcc  = $vTranStpWasteCrdAcc;
										
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
							}
						}
						
													
						$querydt = " update productiondt set ProductionDt_ItemAccount = ".GetSQLValueString($vPrdDtItemAcc,'text').", ProductionDt_DirectStkDbt ".GetSQLValueString($vPrdDtDirectStkDbt,'text').", ".
								 " ProductionDt_DirectStkCrd = ".GetSQLValueString($vPrdDtDirectStkCrd,'text').", ProductionDt_DirectStkCur = ".GetSQLValueString($vPrdDtDirectStkCur,'text').", ".
								 " ProductionDt_WasteDebit = ".GetSQLValueString($vPrdDtWasteDbtAcc,'text').", ProductionDt_WasteCredit = ".GetSQLValueString($vPrdDtWasteCrdAcc,'text')." ";
						if ($adjustcost == 1){
							$vPrdDtCost      = Get_CostPrice($vItemCodePacked, $ItemCurr, $ItemCostMethod, $sub_rows['Production_Date'], $sub_rows['Currency_Code'], $Base1, $Base2, $connection);
							$vPrdDtCostBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, insertMySQLDate($sub_rows['Production_Date']), $vPrdDtCost, $connection);
							$vPrdDtCostBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2,insertMySQLDate($sub_rows['Production_Date']), $vPrdDtCost, $connection);
							if (empty($vPrdDtCostBase1)) $vPrdDtCostBase1 = 0;
							if (empty($vPrdDtCostBase2)) $vPrdDtCostBase2 = 0;
							$querydt .=  " ,ProductionDt_cost= $vPrdDtCost, ProductionDt_CostBase1 = $vPrdDtCostBase1, ProductionDt_CostBase2 = $vPrdDtCostBase2 ";					
						}		 
						$querydt .=" where ProductionDt_ID = ".$sub_rows1['ProductionDt_id'] ."; ";			
						//echo $querydt."<br> ";//exit;	
						$resultdt = mysql_query($querydt,$connection);
					} // End Loop Of Packdt	
				}  // End CasePack Item
						
					if (!$resultdt){
						$ErrorExists = 1;
						$message  = mysql_error($connection);
					}	
				}//end while loop productiondt
				
			}
			
			if($ErrorExists == 0){
				$vPrdTotalCost      = 0;
				$vPrdTotalCostBase1 = 0;
				$vPrdTotalCostBase2 = 0;
				$vPrdTotalCostIdeal = 0;

				//Calculating Master Amounts
				$querycost = " Select ifNull(Sum(ifNull(ProductionDt_Quantity,0)*ifNull(ProductionDt_Cost,0)),0) As TotalCost,  ".
							 " ifNull(Sum(ifNull(ProductionDt_IdealQty,0)*ifNull(ProductionDt_Cost,0)),0) As TotalCostIdeal ".
							 " From ProductionDt ".
							 " Where Production_ID = ".$sub_rows['Production_id']."; ";
				$resultcost = selectData($connection, $querycost);
				
				$vPrdTotalCost       = $resultcost[0];
				$vPrdTotalCostIdeal  = $resultcost[1];
				$vPrdTotalCostBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, insertMySQLDate($sub_rows['Production_Date']), $vPrdTotalCost, $connection);
				$vPrdTotalCostBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2, insertMySQLDate($sub_rows['Production_Date']), $vPrdTotalCost, $connection);				
				
				$query1 = " UPDATE production SET ".
							  " Production_Total = $vPrdTotalCost, Production_TotalBase1 = $vPrdTotalCostBase1, ".
							  " Production_TotalBase2 = $vPrdTotalCostBase2, Production_IdealTotal = $vPrdTotalCostIdeal ".
							  " WHERE Production_ID = ".$sub_rows['Production_id']."; ";
								 
				$result1=mysql_query($query1,$connection);
				if (!$result){
				$ErrorExists = 1;
				$message  = mysql_error($connection);
				}	else {
						if ($Module_PostToJournal == 1 && $Module_DirectStockPD == 1)	
						 $message = Create_AssembleJv($sub_rows['Production_id'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
				}
					
			}
		
		} //end while loop production
		if ($message == "") {
			$message = 'Production Transactions Reposted Successfully.';
		}
	}

	else if($module_newproduction == 1){
		$sub_query = " Select ProductionHD_Id, Date_format(ProductionHD_Date,'%d/%m/%Y') as ProductionHD_Date, Currency_Code as Currency_Code ".
					 " From ProductionHD ".
					 " Where ".
					 " ifNull(ProductionHD_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(ProductionHD_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(ProductionHD_Reference, -1)) ".
					 " And Date_format(ProductionHD_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(ProductionHD_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(ProductionHD_Date,'%Y-%m-%d')) ".
					 " And Date_format(ProductionHD_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(ProductionHD_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(ProductionHD_Date,'%Y-%m-%d')) ";
		// echo $sub_query;
		$sub_result = mysql_query($sub_query,$connection);
		while ($sub_rows=mysql_fetch_assoc($sub_result)) {
			$ProductionHD_Id = $sub_rows['ProductionHD_Id'];
			
		 	// Read from ProductionRM
			$query_rm = "select ProductionRM_ID, ProductionRM.Item_code, Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), items.Currency_Code, ifNull(Item_CostMethod,0),
						ifNull(Item_NonStock,0), ifNull(Item_Unit,0)
						from ProductionRM
						inner join items on items.item_code = ProductionRM.item_code
						where ProductionHD_ID =  $ProductionHD_Id "; 
			$res_rm = mysql_query($query_rm, $connection);			
			while ($rw_rm = mysql_fetch_array($res_rm)){
				$ProductionRM_ID = $rw_rm[0];
				$Item_code 		 = $rw_rm[1];
				$ItemVat 	     = $rw_rm[2];
				$ItemGroupCode   = $rw_rm[3];
				$ItemProd        = $rw_rm[4];
				$ItemTTCInc      = $rw_rm[5];
				$ItemCurr		 = $rw_rm[6];
				$ItemCostMethod  = $rw_rm[7];
				$ItemNonStock    = $rw_rm[8];
				$ItemUnit        = $rw_rm[9];
				
				$vPrdDtDirectStkDbt = '';
				$vPrdDtDirectStkCrd = '';
				$vPrdDtDirectStkCur = '';
				$vPrdDtWasteDbtAcc  = '';
				$vPrdDtWasteCrdAcc  = '';
				
				$queryTrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
							 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$resultTrans = selectData($connection, $queryTrans);
							
				$vTranStpDirectStkDbt 	 = $resultTrans[0];
				$vTranStpDirectStkCrd 	 = $resultTrans[1];
				$vTranStpDirectStkCur 	 = $resultTrans[2];
				$vTranStpWasteDbtAcc  	 = $resultTrans[3];
				$vTranStpWasteCrdAcc  	 = $resultTrans[4];
				$vTranStpWasteDifAcc  	 = $resultTrans[5];
				$vTranStpNonRmVatAcc  	 = $resultTrans[6];
				$vTranStpRmVatAcc     	 = $resultTrans[7];
				$vTranStpNonRmTTCIncAcc  = $resultTrans[8];
				$vTranStpRmTTCIncAcc     = $resultTrans[9];
				$vTranStpNonRmAcc        = $resultTrans[10];
				$vTranStpRmAcc           = $resultTrans[11];
							
				$vPrdDtDirectStkDbt 	= $vTranStpDirectStkDbt;
				$vPrdDtDirectStkCrd 	= $vTranStpDirectStkCrd;
				$vPrdDtDirectStkCur 	= $vTranStpDirectStkCur;
				$vPrdDtWasteDbtAcc  	= $vTranStpWasteDbtAcc;
				$vPrdDtWasteCrdAcc  	= $vTranStpWasteCrdAcc;
				
				if ($ItemVat > 0) {
				if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
					}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
				
				$updaterm = "update ProductionRM set ProductionRM_ItemAccount = '".$vPrdDtItemAcc."',ProductionRM_DirectStkDbt = '".$vPrdDtDirectStkDbt."', ProductionRM_DirectStkCrd = '".$vPrdDtDirectStkCrd."', 
								ProductionRM_DirectStkCur = '".$vPrdDtDirectStkCur."', ProductionRM_WasteDebit = '".$vPrdDtWasteDbtAcc."', ProductionRM_WasteCredit = '".$vPrdDtWasteCrdAcc."' ";
				
				// Adjust Cost
				if ($adjustcost == 1){
					$vPrdDtCost      	= Get_CostPrice($Item_code, $ItemCurr, $ItemCostMethod, $sub_rows['ProductionHD_Date'], $sub_rows['Currency_Code'], $Base1, $Base2, $connection);
					$vPrdDtCostBase1    = ConvertCurrency($sub_rows['Currency_Code'], $Base1, insertMySQLDate($sub_rows['ProductionHD_Date']), $vPrdDtCost, $connection);
					$vPrdDtCostBase2    = ConvertCurrency($sub_rows['Currency_Code'], $Base2,insertMySQLDate($sub_rows['ProductionHD_Date']), $vPrdDtCost, $connection);
					
					if (empty($vPrdDtCostBase1)) $vPrdDtCostBase1 = 0;
					if (empty($vPrdDtCostBase2)) $vPrdDtCostBase2 = 0;
					$updaterm .=  " ,ProductionRM_Cost= $vPrdDtCost, ProductionRM_CostBase1 = $vPrdDtCostBase1, ProductionRM_CostBase2 = $vPrdDtCostBase2 ";					
				}	 				
				$updaterm .= "	where ProductionRM_ID = $ProductionRM_ID ";
				$res_updaterm = mysql_query($updaterm, $connection);
				if (!$res_updaterm){
					$ErrorExists1 = 1;
					$message  = mysql_error($connection);
				}				
				
			} 
			 
			// Read from ProductionFG
		 	$query_fg = "select ProductionFG_Id, ProductionFG.Item_Code, Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), items.Currency_Code, ifNull(Item_CostMethod,0),
						ifNull(Item_NonStock,0), ifNull(Item_Unit,0)
						from ProductionFG
						inner join items on items.item_code = ProductionFG.item_code
						where ProductionHD_Id =  $ProductionHD_Id ";
			$res_fg = mysql_query($query_fg, $connection);			
			while ($rw_fg = mysql_fetch_array($res_fg)){
				$ProductionFG_Id = $rw_fg[0];
				$Item_code 		 = $rw_fg[1];
				$ItemVat 	     = $rw_fg[2];
				$ItemGroupCode   = $rw_fg[3];
				$ItemProd        = $rw_fg[4];
				$ItemTTCInc      = $rw_fg[5];
				$ItemCurr		 = $rw_fg[6];
				$ItemCostMethod  = $rw_fg[7];
				$ItemNonStock    = $rw_fg[8];
				$ItemUnit        = $rw_fg[9];
				
				$vPrdDtDirectStkDbt = '';
				$vPrdDtDirectStkCrd = '';
				$vPrdDtDirectStkCur = '';
				$vPrdDtWasteDbtAcc  = '';
				$vPrdDtWasteCrdAcc  = '';
				
				$queryTrans = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, ".
							 " Trans_wasteDifferenceAcc, Trans_NonRMVatAcc, Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PD' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$resultTrans = selectData($connection, $queryTrans);
							
				$vTranStpDirectStkDbt 	 = $resultTrans[0];
				$vTranStpDirectStkCrd 	 = $resultTrans[1];
				$vTranStpDirectStkCur 	 = $resultTrans[2];
				$vTranStpWasteDbtAcc  	 = $resultTrans[3];
				$vTranStpWasteCrdAcc  	 = $resultTrans[4];
				$vTranStpWasteDifAcc  	 = $resultTrans[5];
				$vTranStpNonRmVatAcc  	 = $resultTrans[6];
				$vTranStpRmVatAcc     	 = $resultTrans[7];
				$vTranStpNonRmTTCIncAcc  = $resultTrans[8];
				$vTranStpRmTTCIncAcc     = $resultTrans[9];
				$vTranStpNonRmAcc        = $resultTrans[10];
				$vTranStpRmAcc           = $resultTrans[11];
							
				$vPrdDtDirectStkDbt 	= $vTranStpDirectStkDbt;
				$vPrdDtDirectStkCrd 	= $vTranStpDirectStkCrd;
				$vPrdDtDirectStkCur 	= $vTranStpDirectStkCur;
				$vPrdDtWasteDbtAcc  	= $vTranStpWasteDbtAcc;
				$vPrdDtWasteCrdAcc  	= $vTranStpWasteCrdAcc;
				
				if ($ItemVat > 0) {
				if ($ItemProd == 1)	$vPrdDtItemAcc = $vTranStpNonRmVatAcc; else $vPrdDtItemAcc = $vTranStpRmVatAcc;
					}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPrdDtItemAcc = $vTranStpRmTTCIncAcc; else $vPrdDtItemAcc = $vTranStpRmAcc;
					}
				}
				
				$updatefg = "update ProductionFG set ProductionFG_ItemAccount = '".$vPrdDtItemAcc."',ProductionFG_DirectStkDbt = '".$vPrdDtDirectStkDbt."', ProductionFG_DirectStkCrd = '".$vPrdDtDirectStkCrd."', 
								ProductionFG_DirectStkCur = '".$vPrdDtDirectStkCur."', ProductionFG_WasteDebit = '".$vPrdDtWasteDbtAcc."', ProductionFG_WasteCredit = '".$vPrdDtWasteCrdAcc."' ";
				$updatefg .= " where ProductionFG_Id = $ProductionFG_Id ";
				$res_updatefg = mysql_query($updatefg, $connection);
				if (!$res_updatefg){
					$ErrorExists2 = 1;
					$message  = $message." ".mysql_error($connection);
				}
			} 
		
			if ($ErrorExists1 == 0 && $ErrorExists2 == 0){
				// Adjust Total Cost
				if ($adjustcost == 1){
					$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$sub_rows['Currency_Code']."' )";
					$result = selectData($connection, $query);
					$rate_dt = $result[0];
					echo $query;
					$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];	
					
					$queryCost = " Select ifNull(Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_Cost,0)),0) As TotalCost,  ".
								 " ifNull(Sum(ifNull(ProductionRM_IdealQty,0)*ifNull(ProductionRM_Cost,0)),0) As TotalCostIdeal, ".
								 " ifNull(Sum(ifNull(ProductionRM_Waste,0)*ifNull(ProductionRM_Cost,0)),0) As TotalCostWaste ".
								 " From ProductionRM ".
								 " Where ProductionHD_ID = $ProductionHD_Id ";
					$resultCost = selectData($connection, $queryCost);
														 
					$vPrdTotalCost       = $resultCost[0];
					$vPrdTotalCostIdeal  = $resultCost[1];
					$vPrdTotalCostWaste  = $resultCost[2];
					$vPrdTotalCostBase1  = ConvertCurrency($sub_rows['Currency_Code'], $Base1, insertMySQLDate($sub_rows['ProductionHD_Date']), $vPrdTotalCost, $connection);
					$vPrdTotalCostBase2  = ConvertCurrency($sub_rows['Currency_Code'], $Base2, insertMySQLDate($sub_rows['ProductionHD_Date']), $vPrdTotalCost, $connection);
					
					$sub_query1 = " UPDATE ProductionHD SET ".
								  " ProductionHD_Total = $vPrdTotalCost, ProductionHD_TotalBase1 = $vPrdTotalCostBase1, ".
								  " ProductionHD_TotalBase2 = $vPrdTotalCostBase2, ProductionHD_IdealTotal = $vPrdTotalCostIdeal, ".
								  " ProductionHD_WasteTotal = $vPrdTotalCostWaste ".
								  " WHERE ProductionHD_ID = $ProductionHD_Id ";
					$sub_result1=mysql_query($sub_query1,$connection);		

					DistributeCostFG($ProductionHD_Id, $Base1, $Base2, $rate_dt, $rate_dt1, $rate_dt2, $connection);
				}
				
				$message = Create_ProductionJv($ProductionHD_Id, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
				
			} else break;  
		}

		if ($message == "") {
			$message = 'Production Transactions Reposted Successfully.';
		}	 
		
	
		
	}
	
}


//Sales Order
else if( $transtype == 'SO'){
	$sub_query = " Select Sorder_id, Sorder_date, Client_Code, Salesman_Code, Currency_Code, ifNull(Sorder_VATChckbx,0) as Sorder_VATChckbx, Sorder_discountper, Sorder_discountamount, Sorder_TransportAmount,
					Date_format(sorder.Sorder_date,'%Y%m%d') as Sorderdate".
				 " From sorder ".
				 " Where sorder.Journal_Type = 'SO' ".
				 " And ifNull(sorder.sorder_reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(sorder.sorder_reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(sorder.sorder_reference, -1)) ".
				 " And Date_format(sorder.Sorder_date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(sorder.Sorder_date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(sorder.Sorder_date,'%Y-%m-%d')) ".
				 " And Date_format(sorder.Sorder_date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(sorder.Sorder_date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(sorder.Sorder_date,'%Y-%m-%d'))  ";
	
	$res_sub = mysql_query($sub_query, $connection);
	while ($rw_sub = mysql_fetch_array($res_sub)){
		$sorder_id 				= $rw_sub[0];
		$Sorder_date 			= $rw_sub[1];
		$Client_Code 			= $rw_sub[2];
		$Currency_Code 			= $rw_sub[4];
		$Sorder_VATChckbx 		= $rw_sub[5];
		$Sorder_discountper 	= $rw_sub[6];
		$Sorder_discountamount 	= $rw_sub[7];
		$Sorder_TransportAmount	= $rw_sub[8];
		$Sorderdate 			= $rw_sub[9];
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$Currency_Code."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$Currency_Code."' )";
		$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];
		
		$querydt =  " select SorderDt_id, sorderdt.Currency_Code, sorderdt.Item_code,  items.Item_Vat, ITEM_MAXQTY, items.Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ".
					" ifNull(Item_NonStock,0) ".
					" from sorderdt inner join items on items.item_code = sorderdt.item_code ".
					" where sorder_id = $sorder_id ";
		$resdt = mysql_query($querydt, $connection);
		while ($rwdt = mysql_fetch_array($resdt)){
			$SorderDt_id   = $rwdt[0];
			$Currency_Code = $rwdt[1];
			$Item_code 	   = $rwdt[2];
			$item_vat      = $rwdt[3];
			$Item_MaxQty   = $rwdt[4];
			$ItemGroupCode = $rwdt[5];
			$ItemProd  	   = $rwdt[6];
			$ItemTTCInc	   = $rwdt[7];
			$ItemUnit 	   = $rwdt[8];
			$ItemPromo     = $rwdt[9];
			$ItemNonStock  = $rwdt[10];
			
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
			
			$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, ".
					 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'SO' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";//echo $query;exit;
			$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]; 
			$vSaDtWasteDbt 			= $result[12]; 
			$vSaDtWasteCrd 			= $result[13]; 
			$vSaDtExportAcc 		= $result[14]; 	
			
			if ($Module_RawMaterial == 1 || $SubItem_Production == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				
				//if($vSaDtChkGeneralAcc == 0){
					if ($item_vat > 0 && $Sorder_VATChckbx == 1) {
						if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
					}
					else {
						if ($ItemProd == 1) {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
						}	
						else {
							if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
						}
					}
				//}			
			} 
			else {
				$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
				$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
				$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
						
				if ($item_vat > 0 && $Sorder_VATChckbx == 1)
					$vSaDtItemAcc = $vSaStpCreditVatAcc;
				else
					$vSaDtItemAcc = $vSaStpCreditAcc;	
						
			}
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$Client_Code."','".$vSaDtDirectStkDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$Client_Code."','".$vSaDtDirectStkCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkCrd = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$Client_Code."','".$vSaDtWasteDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$Client_Code."','".$vSaDtWasteCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
			
			$sub_query1 = " UPDATE sorderdt SET  ".
						  " Sorderdt_ItemAccount = '".$vSaDtItemAcc."', ".
						  " Sorderdt_DirectStkDbt = ".strformat($vSaDtDirectStkDbt).", ".
						  " Sorderdt_DirectStkCrd = ".strformat($vSaDtDirectStkCrd).", ".
						  " Sorderdt_DirectStkCur = ".strformat($vSaDtDirectStkCur).", ".
						  " Sorderdt_DirectWasteDbt = ".strformat($vSaDtWasteDbt).", ".
						  " Sorderdt_DirectWasteCrd = ".strformat($vSaDtWasteCrd).", ".
						  " Sorderdt_exportAccount = ".strformat($vSaDtExportAcc)." ".
						  " Where SorderDt_ID = ".$SorderDt_id;
			$result1 = mysql_query($sub_query1, $connection);			  
			
		} // end while rwdt
		if ($adjustcost == 1) {  
			$CalculateResult = Calculate_SOMasterAmounts($sorder_id, $Sorderdate, $Sorder_VATChckbx, $Sorder_discountper, $Sorder_discountamount, $Sorder_TransportAmount, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'P', $connection);
		} // end if adjust cost
		if ($Module_GenerateSorderJV == 1 || $Module_GenerateSorderJV == 2) {
			$message = Create_SalesOrderJv($sorder_id, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
		}
	} // end while rw_sub
	
}else if($transtype == 'TR'){
	$querys = "Select Transferrequest_Id, Transferrequest_Reference, Transferrequest_Date, Transferrequest_Remark, Transferrequest_Posted, Transferrequest_Edit, Project_code1, Project_code2, Costcenter_Code, ToCostcenter_Code,".
			" Journal_id, TransferrequestDt_ID, SendReceive_Reference, Transferrequest_BelongsToGroup, Synchronized, ".
			" Adjustment_id, Driver_Name,Document_RefNo, Vehicle_No, f_Date, Requestedby, User_account, Company_Name, Transferrequest_WarehouseFrom, Transferrequest_WarehouseTo,".
			" currencycode,client_code,datefrom,dateto , total,totalbase1,totalbase2,discount,discountbase1,discountbase2,vat,vatbase1,vatbase2,taxable,taxablebase1,taxablebase2,".
			" nonetaxable,nonetaxablebase1,nonetaxablebase2,discountper".
			" FROM Transferrequest". 
			" where ifNull(Transferrequest.Transferrequest_Reference, -1) Between ifNull(".GetSQLValueString($fromref,'double').", ifNull(Transferrequest.Transferrequest_Reference, -1)) and ifNull(".GetSQLValueString($toref,'double').", ifNull(Transferrequest.Transferrequest_Reference, -1)) ".
			" And Date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($PFromDate,'date').",date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($PToDate,'date').",date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d')) ".
			" And Date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d') between ifNull(". GetSQLValueString($DirFromDate,'date').",date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d')) and ifNull(". GetSQLValueString($DirToDate,'date').",date_format(Transferrequest.Transferrequest_Date,'%Y-%m-%d'))  ";
		//	echo $querys; exit;			 
	$results = mysql_query($querys,$connection);
	while ($rows=mysql_fetch_assoc($results)) {
				
		$sub_query = " Select transferrequestDt_id, Cur_Code, ifNull(TransferRequestDt_Price,0), ifNull(TransferRequestDt_PriceBase1,0), ifNull(TransferRequestDt_PriceBase2,0),Item_Code  ".
					//" ifNull(TransferRequestDt_discountAmout,0), ifNull(TransferRequestDt_discountAmoutBase1,0), ifNull(TransferRequestDt_discountAmoutBase2,0)".
					" From transferrequestdt ".
					" Where TransferRequest_ID = ".$rows['Transferrequest_Id'];	//echo$sub_query;exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
					" FROM Items WHERE item_Code = '".$sub_row[5]."'";
					
			$result = selectData($connection, $query);
			$item_vat 		= $result[0];
			$Item_MaxQty 	= $result[1];
			$ItemGroupCode 	= $result[2];
			$ItemProd   	= $result[3];
			$ItemTTCInc 	= $result[4];
			$ItemUnit   	= $result[5];
			$ItemPromo  	= $result[6];
			$ItemNonStock  	= $result[7];
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
				
			$PSaVatChkbx = $txtSaVatChk;
			
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, CreditAccountVAT, CreditAccount, PromotionAccount, TipsAccount,  ".
						" CreditAccountNonStock, CreditAccountVatNonStock, VatAccount, VATAccountNonStock, VatAccountPOS, VATAccountNonStockPOS".
						" FROM salessetup ";
								
			$result = selectData($connection, $query);
					
			$vSaStpDirectStkDbt = $result[0];
			$vSaStpDirectStkCrd = $result[1];
			$vSaStpDirectStkCur = $result[2];	
			$vSaStpDiscAcc      = $result[3];	
			$vSaStpCreditVatAcc = $result[4];	
			$vSaStpCreditAcc    = $result[5];	
			$vSaStpPromoAcc     = $result[6];
			$vSaStpTipsAcc      = $result[7];
			
			$vSaStpCreditNonStockAcc    = $result[8];
			$vSaStpCreditVatNonStockAcc = $result[9];
			$vSaStpVatAcc 		  	  	= $result[10];
			$vSaStpVatNonStockAcc 	  	= $result[11];
			$vSaStpVatAccCash	  	  	= $result[12];
			$vSaStpVatNonStockAccCash 	= $result[13];	
			
			$queryexp = "select ifnull(client_export,0) from clients where Ledger_number =  '".$rows['client_code']."' ";	
			$resexp = mysql_query($queryexp,$connection);
			$rwexp = mysql_fetch_row($resexp);
			$clientexp = $rwexp[0];

			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
						" Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc, Trans_TipsAcc,trans_export ".
						" FROM transactionsetup ".
						" WHERE Journal_type = 'SI' ".
						" AND Group_code = '".$ItemGroupCode."'  ";
			// echo $query."<br>";				 
			$result = selectData($connection, $query);
			
			$vTranStpDirectStkDbt = $result[0];
			$vTranStpDirectStkCrd = $result[1];
			$vTranStpDirectStkCur = $result[2];
			$vTranStpVatAcc       = $result[3];
			$vTranStpNonRmVatAcc  = $result[4];
			$vTranStpRmVatAcc     = $result[5];
			$vTranStpNonRmTTCIncAcc  = $result[6];
			$vTranStpRmTTCIncAcc     = $result[7];
			$vTranStpNonRmAcc        = $result[8];
			$vTranStpRmAcc           = $result[9];
			$vTranStpDiscAcc         = $result[10];
			$vTranStpPromoAcc        = $result[11]; 
			$vTranStpTipsAcc         = $result[12]; 
			$vTransStpExportAcc 	 = $result[13];
			//echo $Module_RawMaterial;exit;
			//$Module_RawMaterial=0;
			if ($Module_RawMaterial == 1) {
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				// echo $vSaDtVatAcc." || ".$vSaDtDiscAcc;exit;
				if ($item_vat > 0 && $PSaVatChkbx == 1) {
					if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
					}
				}	
				if($clientexp == 1) $vSaDtItemAcc = $vTransStpExportAcc; 
			}else{	
				//$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
						
				if ($item_vat > 0 && $PSaVatChkbx == 1) {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditVatNonStockAcc;
					else
						$vSaDtItemAcc = $vSaStpCreditVatAcc;
				} else {
					if ($ItemNonStock == 1)
						$vSaDtItemAcc = $vSaStpCreditNonStockAcc;
					else	
						$vSaDtItemAcc = $vSaStpCreditAcc;
				}

				/*if ($vSaPayMode == 1) {
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAccCash;
					else	
						$vSaDtVatAcc = $vSaStpVatAccCash;
				} else {*/
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
				//}
				
				if($clientexp == 1) $vSaDtItemAcc = $vSaStpCreditExportAcc; 						
			}		
						
			$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vSaDtVatAcc."') from dual "; //echo $sub_queryVat;exit;
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
			$sub_query1 = " Update transferrequestdt SET ".
							" TransferRequestDt_discountAccount = '".$vSaDtDiscAcc."', ".
							" TransferRequestDt_ItemAccount = '".$vSaDtItemAcc."', ".
							" TransferRequestDt_VatAccount = '".$vSaDtVatAcc."' ".
							" Where transferrequestdt_id = ".$sub_row[0];
				//echo $sub_query1;exit;	
			if (!updateData($connection, $sub_query1, true)){		 
				$message  = mysql_error(); 
			}
		}
		
		$message = Create_TransferRequestJv($rows['Transferrequest_Id'], $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);
		
	}
}

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

//echo $mode.$message; exit;

header ("Location: ./Form_RepostTransactions.php?transtype=".$transtype."&fromdate=".$fromdate."&todate=".$todate."&fromref=".$fromref."&toref=".$toref."&adjustcost=".$adjustcost."&message=".$message);

function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}


function Create_SalesJv($PSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_SalesAutoJv(".$PSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	//echo $query; exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_SalesAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_SalesJv: '.$error;

	Return $error;
	

}

function Create_DeliveryJv($PSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_DeliveryAutoJv(".$PSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	//echo $query; exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_DeliveryAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_DeliveryJv: '.$error;

	Return $error;
	

}

function Calculate_AdjustAmounts($PId, $connection) {

	$vAdjTotalCost      = 0;
	$vAdjTotalCostBase1 = 0;
	$vAdjTotalCostBase2 = 0;

	//Calculating Master Amounts
	$sub_query = " Select ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)*ifNull(AdjustmentDt_Price,0)),0) As TotalCost, ".
				 " ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)*ifNull(AdjustmentDt_PriceBase1,0)),0) As TotalCostB1, ".
				 " ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)*ifNull(AdjustmentDt_PriceBase2,0)),0) As TotalCostB2 ".
				 " From AdjustmentDt ".
				 " Where Adjustment_ID = ".$PId;
	$sub_result = selectData($connection, $sub_query);

	//echo $sub_query;exit;

	$vAdjTotalCost       = $sub_result[0];
	$vAdjTotalCostBase1  = $sub_result[1];
	$vAdjTotalCostBase2  = $sub_result[2];


	fbegin();

	$sub_query1 = " UPDATE Adjustment SET ".
				  " Adjustment_Amount = $vAdjTotalCost, Adjustment_AmountBase1 = $vAdjTotalCostBase1, ".
				  " Adjustment_AmountBase2 = $vAdjTotalCostBase2 ".
				  " WHERE Adjustment_ID = ".$PId;

	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();

	}else{
		$message  = mysql_error();
		$error = 'Error In Function Calculate_AdjustAmounts: '.$message;
		frollback();
	}

	Return $error;

}


function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PVatBase1, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PModuleAdditionalTaxes, $PPurchasesVATMod, $PPurchaseTTC, $PMode, $connection) {

	$vPurDtTotal = 0;
	$vItemVat    = 0;
	
	$vPurTaxable = 0;
	$vPurNoneTaxable = 0;
	$vPurGrossTotal = 0;
	$vPurDiscountAmt = 0;
	$vPurDiscountPer = 0;
	$vPurVat = 0;
	$vPurVatBase1 = 0;
	$vPurVatBase2 = 0;
		
	$vPurTax1 = 0;
	$vPurTax2 = 0;
	$vPurTax3 = 0;
	$vPurTax4 = 0;
	$vPurTax5 = 0;
	$vPurTax1B1 = 0;
	$vPurTax2B1 = 0;
	$vPurTax3B1 = 0;
	$vPurTax4B1 = 0;
	$vPurTax5B1 = 0;
	$vPurTax1B2 = 0;
	$vPurTax2B2 = 0;
	$vPurTax3B2 = 0;
	$vPurTax4B2 = 0;
	$vPurTax5B2 = 0;
	
	if (empty($PVatBase1)) $PVatBase1 = 0;

	$vPurDiscountPer = $PDiscPer;
	
	//Added 2011/09/26
	if ($PPurchaseTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE PurchasesDt SET  ".
				 " PurchaseDt_Price = PurchaseDt_PriceTTC, PurchaseDt_PriceBase1 = PurchaseDt_PriceTTCbase1, PurchaseDt_PriceBase2 = PurchaseDt_PriceTTCbase2 ".
				 " Where Purchase_ID = ".$PId;

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

		$query = " UPDATE PurchasesDt SET  ".
				 " PurchaseDt_Price      = (PurchaseDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " PurchaseDt_PriceBase1 = (PurchaseDt_PriceTTCbase1 / (1 + Item_Vat/100)), ".
				 " PurchaseDt_PriceBase2 = (PurchaseDt_PriceTTCbase2 / (1 + Item_Vat/100)) ".
				 " Where Purchase_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	

						 
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0))-((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*ifNull(PurchaseDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " PurchaseDt_Quantity, ifNull(PurchaseDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From PurchasesDt ".
				 " Where Purchase_ID = ".$PId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
	//echo $sub_query;exit;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

	//echo $sub_rows[4];
	
		$vPurDtTotal = $sub_rows[1];
		$vItemVat    = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vPurTaxable     = $vPurTaxable     + ($vPurDtTotal*$tax_flag);
		$vPurNoneTaxable = $vPurNoneTaxable + ($vPurDtTotal*$notax_flag);
		$ndate = explode("-",$PDate);
		$PDate2 = $ndate[0].$ndate[1].$ndate[2];		
		// Calculation of Vat Amount
		if ((($PDate2 > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vPurDtTotal > 0)
			$vPurVat = $vPurVat + (($vPurDtTotal - $sub_rows[4])*$vItemVat/100);
			

				
		if ($PModuleAdditionalTaxes == 1 && $vPurDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vPurTax1 = $vPurTax1 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vPurTax2 = $vPurTax2 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vPurTax3 = $vPurTax3 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vPurTax4 = $vPurTax4 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vPurTax5 = $vPurTax5 + (($vPurDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
	//exit;				
					
	$vPurGrossTotal = $vPurTaxable + $vPurNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vPurDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vPurDiscountPer > 0)
			$vPurDiscountAmt = (($vPurGrossTotal * $vPurDiscountPer) / 100);
	}				
			
	$query    = " SELECT Currency_Code FROM purchases WHERE Purchase_id = $PId ";
	$result   = selectData($connection, $query);
	$vPurCurr = $result[0];	
	
	$query    = " SELECT base1, base2 FROM setup";
	$result   = selectData($connection, $query);
	$base1 = $result[0];
	$base2 = $result[1];


					
	$vPurNetTotal         = $vPurGrossTotal + $vPurVat - $vPurDiscountAmt;
	$vPurTaxableBase1     = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTaxable, $connection);
	$vPurTaxableBase2     = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTaxable, $connection);
	$vPurNoneTaxableBase1 = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurNoneTaxable, $connection);
	$vPurNoneTaxableBase2 = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurNoneTaxable, $connection);
	$vPurDiscountAmtBase1 = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurDiscountAmt, $connection);
	$vPurDiscountAmtBase2 = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurDiscountAmt, $connection);
	$vPurGrossTotalBase1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurGrossTotal, $connection);
	$vPurGrossTotalBase2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurGrossTotal, $connection);
	
	//If User Has Access To Modify Vat Base1
	if ($PPurchasesVATMod == 1)
		$vPurVatBase1 = $PVatBase1;
	else	
		$vPurVatBase1 = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurVat, $connection);
	
	$vPurVatBase2 = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurVat, $connection);
	

	$vPurTax1B1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTax1, $connection);
	$vPurTax1B2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTax1, $connection);		
	$vPurTax2B1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTax2, $connection);
	$vPurTax2B2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTax2, $connection);		
	$vPurTax3B1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTax3, $connection);
	$vPurTax3B2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTax3, $connection);		
	$vPurTax4B1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTax4, $connection);
	$vPurTax4B2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTax4, $connection);		
	$vPurTax5B1  = ConvertCurrencyRate($vPurCurr, $base1, ($PDate), $PRate, $PRate1, $vPurTax5, $connection);
	$vPurTax5B2  = ConvertCurrencyRate($vPurCurr, $base2, ($PDate), $PRate, $PRate2, $vPurTax5, $connection);	
	
	fbegin();
	
	$sub_query1 = " UPDATE purchases SET ".
				  " Purchase_Taxable = $vPurTaxable, Purchase_TaxableBase1 = $vPurTaxableBase1, Purchase_TaxableBase2 = $vPurTaxableBase2, ".
				  " Purchase_NoneTaxable = $vPurNoneTaxable, Purchase_NoneTaxableBase1 = $vPurNoneTaxableBase1, Purchase_NoneTaxableBase2 = $vPurNoneTaxableBase2, ".
				  " Purchase_DiscountAmount = $vPurDiscountAmt, Purchase_DiscountBase1 = $vPurDiscountAmtBase1, Purchase_DiscountBase2 = $vPurDiscountAmtBase2, ".
				  " Purchase_DiscountPer = $vPurDiscountPer, Purchase_VAT = $vPurVat, Purchase_VATBase1 = $vPurVatBase1, Purchase_VATBase2 = $vPurVatBase2, ".
				  " Purchase_Total = $vPurGrossTotal, Purchase_TotalBase1 = $vPurGrossTotalBase1, Purchase_TotalBase2 = $vPurGrossTotalBase2, ".
				  " Purchase_Tax1 = $vPurTax1, Purchase_Tax1Base1 = $vPurTax1B1, Purchase_Tax1Base2 = $vPurTax1B2,  ".
				  " Purchase_Tax2 = $vPurTax2, Purchase_Tax2Base1 = $vPurTax2B1, Purchase_Tax2Base2 = $vPurTax2B2,  ".
				  " Purchase_Tax3 = $vPurTax3, Purchase_Tax3Base1 = $vPurTax3B1, Purchase_Tax3Base2 = $vPurTax3B2,  ".
				  " Purchase_Tax4 = $vPurTax4, Purchase_Tax4Base1 = $vPurTax4B1, Purchase_Tax4Base2 = $vPurTax4B2,  ".
				  " Purchase_Tax5 = $vPurTax5, Purchase_Tax5Base1 = $vPurTax5B1, Purchase_Tax5Base2 = $vPurTax5B2  ".
				  " WHERE Purchase_ID = ".$PId;
			//	 echo $sub_query1;exit;
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}
function GetPurchaseRates($PPurId,$connection) {

	$query = "Select Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2 From Purchases where Purchase_ID = '".$PPurId."'";
	//echo $query; exit;
	$result = selectData($connection, $query);
	
	Return $result;

}


function Calculate_MasterAmountsdelivery($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PBonusAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {

	$vSaDtTotal = 0;
	$vItemVat    = 0;
	
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountPer    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaTransportAmtTTC = 0;
	$vSaBonusAmt   	    = 0;
	$vSaBonusAmtB1      = 0;
	$vSaBonusAmtB2      = 0;
	$vSaBonusAmtTTC     = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
		
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;
	
	$vSaTotalWeight = 0;

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

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

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

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

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

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
		
		
			
		// Calculation of Vat Amount
		if ((($PDate > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
		$vSaTotalWeight = $vSaTotalWeight + ($sub_rows[10]*$sub_rows[11]);
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		$vSaTransportAmtTTC = $PTransportAmt;					
		$vSaTransportAmt    = ($vSaTransportAmtTTC / (1 + $PSetupVatPercentage/100));
		$vSaBonusAmtTTC 	= $PBonusAmt;					
		$vSaBonusAmt    	= ($vSaBonusAmtTTC / (1 + $PSetupVatPercentage/100));
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
	
				
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
	$vSaTransportAmtB1   = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2   = ($vSaTransportAmt*$PRate)/$PRate2;	
	$vSaBonusAmtB1 	     = ($vSaBonusAmt*$PRate)/$PRate1;
	$vSaBonusAmtB2	     = ($vSaBonusAmt*$PRate)/$PRate2;	
					

	$vSaTax1B1  = ($vSaTax1*$PRate)/$PRate1;
	$vSaTax1B2  = ($vSaTax1*$PRate)/$PRate2;		
	$vSaTax2B1  = ($vSaTax2*$PRate)/$PRate1;
	$vSaTax2B2  = ($vSaTax2*$PRate)/$PRate2;		
	$vSaTax3B1  = ($vSaTax3*$PRate)/$PRate1;
	$vSaTax3B2  = ($vSaTax3*$PRate)/$PRate2;		
	$vSaTax4B1  = ($vSaTax4*$PRate)/$PRate1;
	$vSaTax4B2  = ($vSaTax4*$PRate)/$PRate2;		
	$vSaTax5B1  = ($vSaTax5*$PRate)/$PRate1;
	$vSaTax5B2  = ($vSaTax5*$PRate)/$PRate2;	
	
	fbegin();
	//echo $delivery_date;exit;
	$sub_query1 = " UPDATE deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_DiscountPer = $vSaDiscountPer, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_VatChkbx = $PVatChk, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_TransportAmount = $vSaTransportAmt, Delivery_TransportAmountBase1 = $vSaTransportAmtB1, Delivery_TransportAmountBase2 = $vSaTransportAmtB2, Delivery_TransportTTC = $vSaTransportAmtTTC, ".
				  " Delivery_BonusAmount = $vSaBonusAmt, Delivery_BonusBase1 = $vSaBonusAmtB1, Delivery_BonusBase2 = $vSaBonusAmtB2, Delivery_BonusTTC = $vSaBonusAmtTTC, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2,  ".
				  " totalWeight = $vSaTotalWeight ".
				  " WHERE Delivery_ID = ".$PId;
	//echo $sub_query1."<br>";exit;	
	$sub_result1=mysql_query($sub_query1,$connection);
	
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}



function Calculate_salesMasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PBonusAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC,$PWHTChk,$PWHTPer, $PMode, $connection) {

	$vSaDtTotal = 0;
	$vItemVat    = 0;
	
	$vSaTaxable         = 0;
	$vSaTaxableTTC      = 0;
	$vSaNoneTaxable     = 0;
	$vSaGrossTotal      = 0;
	$vSaDiscountAmt     = 0;
	$vSaDiscountPer     = 0;
	$vSaDiscountAmtTTC  = 0;
	$vSaTransportAmt    = 0;
	$vSaTransportAmtB1  = 0;
	$vSaTransportAmtB2  = 0;
	$vSaTransportAmtTTC = 0;
	$vSaBonusAmt   	    = 0;
	$vSaBonusAmtB1      = 0;
	$vSaBonusAmtB2      = 0;
	$vSaBonusAmtTTC     = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
	
	$vSaWHT      = 0;
	$vSaWHTBase1 = 0;
	$vSaWHTBase2 = 0;
	
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;

	$vSaDiscountPer = $PDiscPer;
	
	if($PWHTChk == '') $PWHTChk = 0;
	
	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE SalesDt SET  ".
				 " SaleDt_Price = SaleDt_PriceTTC, ".
				 " SaleDt_PriceBase1 = SaleDt_PriceTTCBase1, ".
				 " SaleDt_PriceBase2 = SaleDt_PriceTTCBase2 ".
				 " Where Sale_ID = ".$PId;

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

		$query = " UPDATE SalesDt SET  ".
				 " SaleDt_Price      = (SaleDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " SaleDt_PriceBase1 = (SaleDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " SaleDt_PriceBase2 = (SaleDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Sale_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	
	
	
	//Calculating Master Amounts
	$sub_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(SaleDt_TransportAmount,0) - ifNull(SaleDt_BonusAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From SalesDt ".
				 " Where Sale_ID = ".$PId;			 
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if ((($PDate > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
	
	
	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		$vSaTransportAmtTTC = $PTransportAmt;					
		$vSaTransportAmt    = ($vSaTransportAmtTTC / (1 + $PSetupVatPercentage/100));
		$vSaBonusAmtTTC 	= $PBonusAmt;					
		$vSaBonusAmt    	= ($vSaBonusAmtTTC / (1 + $PSetupVatPercentage/100));
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
			$vSaDiscountAmtTTC   = 0;
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
			
			$vSaDiscountAmtTTC   = 0;
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
	}		
					
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
	$vSaTransportAmtB1   = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2   = ($vSaTransportAmt*$PRate)/$PRate2;	
	$vSaBonusAmtB1 	     = ($vSaBonusAmt*$PRate)/$PRate1;
	$vSaBonusAmtB2	     = ($vSaBonusAmt*$PRate)/$PRate2;	
					

	$vSaTax1B1  = ($vSaTax1*$PRate)/$PRate1;
	$vSaTax1B2  = ($vSaTax1*$PRate)/$PRate2;		
	$vSaTax2B1  = ($vSaTax2*$PRate)/$PRate1;
	$vSaTax2B2  = ($vSaTax2*$PRate)/$PRate2;		
	$vSaTax3B1  = ($vSaTax3*$PRate)/$PRate1;
	$vSaTax3B2  = ($vSaTax3*$PRate)/$PRate2;		
	$vSaTax4B1  = ($vSaTax4*$PRate)/$PRate1;
	$vSaTax4B2  = ($vSaTax4*$PRate)/$PRate2;		
	$vSaTax5B1  = ($vSaTax5*$PRate)/$PRate1;
	$vSaTax5B2  = ($vSaTax5*$PRate)/$PRate2;	
	
	
	if($PWHTChk == 1) {
		if($PSalesTTC == 1) 
			$vSaWHT      = ((($vSaTaxableTTC + $vSaNoneTaxable) - $vSaVat)*$PWHTPer/100); 
		else 
			$vSaWHT      = (($vSaTaxable + $vSaNoneTaxable)*$PWHTPer/100); 
		$vSaWHTBase1 = ($vSaWHT*$PRate)/$PRate1;
		$vSaWHTBase2 = ($vSaWHT*$PRate)/$PRate2;
	} else {
		$vSaWHT      = 0;
		$vSaWHTBase1 = 0;
		$vSaWHTBase2 = 0;
		
	}	
	
	fbegin();
	
	$sub_query1 = " UPDATE sales SET ".
				  " Sale_Taxable = $vSaTaxable, Sale_TaxableBase1 = $vSaTaxableBase1, Sale_TaxableBase2 = $vSaTaxableBase2, ".
				  " Sale_NoneTaxable = $vSaNoneTaxable, Sale_NoneTaxableBase1 = $vSaNoneTaxableBase1, Sale_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Sale_DiscountAmount = $vSaDiscountAmt, Sale_DiscountBase1 = $vSaDiscountAmtBase1, Sale_DiscountBase2 = $vSaDiscountAmtBase2, ";
				  
	//if ($PTransportAmt > 0)			  
		$sub_query1 = $sub_query1." Sale_TransportAmount = $vSaTransportAmt, Sale_TransportBase1 = $vSaTransportAmtB1, Sale_TransportBase2 = $vSaTransportAmtB2, Sale_TransportTTC = $vSaTransportAmtTTC, ";
	//if ($PBonusAmt > 0)	
		$sub_query1 = $sub_query1." Sale_BonusAmount = $vSaBonusAmt, Sale_BonusBase1 = $vSaBonusAmtB1, Sale_BonusBase2 = $vSaBonusAmtB2, Sale_BonusTTC = $vSaBonusAmtTTC, ";
	
	
	$sub_query1 = $sub_query1.
				  " Sale_DiscountPer = $vSaDiscountPer, Sale_VAT = $vSaVat, Sale_VATBase1 = $vSaVatBase1, Sale_VATBase2 = $vSaVatBase2, ".
				  " Sale_Total = $vSaGrossTotal, Sale_TotalBase1 = $vSaGrossTotalBase1, Sale_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Sale_DiscountTTC = $vSaDiscountAmtTTC, Sale_TaxableTTC = $vSaTaxableTTC,  ".
				  " Sale_Tax1 = $vSaTax1, Sale_Tax1Base1 = $vSaTax1B1,   Sale_Tax1Base2 = $vSaTax1B2,  ".
				  " Sale_Tax2 = $vSaTax2, Sale_Tax2Base1 = $vSaTax2B1,   Sale_Tax2Base2 = $vSaTax2B2,  ".
				  " Sale_Tax3 = $vSaTax3, Sale_Tax3Base1 = $vSaTax3B1,   Sale_Tax3Base2 = $vSaTax3B2,  ".
				  " Sale_Tax4 = $vSaTax4, Sale_Tax4Base1 = $vSaTax4B1,   Sale_Tax4Base2 = $vSaTax4B2,  ".
				  " Sale_Tax5 = $vSaTax5, Sale_Tax5Base1 = $vSaTax5B1,   Sale_Tax5Base2 = $vSaTax5B2,  ".
				  " Sale_WHTchecked = $PWHTChk, Sale_WHTAmount = $vSaWHT, Sale_WHTAmountBase1 = $vSaWHTBase1, Sale_WHTAmountBase2 = $vSaWHTBase2 ".
				  " WHERE Sale_ID = ".$PId;
	//echo $sub_query1."<br>";exit;				 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}




function Calculate_SOMasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {

	$vSorDtTotal = 0;
	$vItemVat    = 0;
	
	$vSorTaxable 		 = 0;
	$vSorNoneTaxable 	 = 0;
	$vSorGrossTotal 	 = 0;
	$vSorDiscountAmt 	 = 0;
	$vSorDiscountPer 	 = 0;
	$vSorTransportAmt    = 0;
	$vSorTransportAmtB1  = 0;
	$vSorTransportAmtB2  = 0;
	$vSorTransportAmtTTC = 0;
	$vSorVat 	  = 0;
	$vSorVatBase1 = 0;
	$vSorVatBase2 = 0;
		
	$vSorTax1 = 0;
	$vSorTax2 = 0;
	$vSorTax3 = 0;
	$vSorTax4 = 0;
	$vSorTax5 = 0;
	$vSorTax1B1 = 0;
	$vSorTax2B1 = 0;
	$vSorTax3B1 = 0;
	$vSorTax4B1 = 0;
	$vSorTax5B1 = 0;
	$vSorTax1B2 = 0;
	$vSorTax2B2 = 0;
	$vSorTax3B2 = 0;
	$vSorTax4B2 = 0;
	$vSorTax5B2 = 0;

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

		$query = " UPDATE SorderDt SET  ".
				 " SorderDt_Price = SorderDt_PriceTTC, ".
				 " SorderDt_PriceBase1 = ((SorderDt_PriceTTC*$PRate)/$PRate1), ".
				 " SroderDt_PriceBase2 = ((SorderDt_PriceTTC*$PRate)/$PRate2) ".
				 " Where Sorder_ID = ".$PId;

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

		$query = " UPDATE SorderDt SET  ".
				 " SorderDt_Price      = (SorderDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " SorderDt_PriceBase1 = (((SorderDt_PriceTTC*$PRate)/$PRate1) / (1 + Item_Vat/100)), ".
				 " SroderDt_PriceBase2 = (((SorderDt_PriceTTC*$PRate)/$PRate2) / (1 + Item_Vat/100)) ".
				 " Where Sorder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	
	
		
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0)*ifNull(SorderDt_Discount,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SorderDt_Quantity, (ifNull(SorderDt_DiscountAmount,0) - ifNull(SorderDt_TransportAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ".
				 " ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0)*ifNull(SorderDt_Discount,0))/100)) As TotalTTC ".
				 " From SorderDt ".
				 " Where Sorder_ID = ".$PId;
										 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSorDtTotal    = $sub_rows[1];
		$vItemVat       = $sub_rows[2];
		$vSorDtTotalTTC = $sub_rows[10];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
		//if ($PSalesTTC ==1 && $PVatChk == 0) {					
			//$vSorTaxable     = $vSorTaxable     + ($vSorDtTotalTTC*$tax_flag);
			//$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotalTTC*$notax_flag);
		//} else {
			$vSorTaxable     = $vSorTaxable     + ($vSorDtTotal*$tax_flag);
			$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotal*$notax_flag);
		//}
						
		
		// Calculation of Vat Amount
		if ((($PDate > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSorDtTotal > 0)
			$vSorVat = $vSorVat + (($vSorDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSorDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSorTax1 = $vSorTax1 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSorTax2 = $vSorTax2 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSorTax3 = $vSorTax3 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSorTax4 = $vSorTax4 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSorTax5 = $vSorTax5 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSorGrossTotal = $vSorTaxable + $vSorNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vSorDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vSorDiscountPer > 0)
			$vSorDiscountAmt = (($vSorGrossTotal * $vSorDiscountPer) / 100);
	}	

	if ($PSalesTTC == 1) {
		$vSorTransportAmtTTC = $PTransportAmt;					
		$vSorTransportAmt    = ($vSorTransportAmtTTC / (1 + $PSetupVatPercentage/100));	
	} else {
		$vSorTransportAmt    = $PTransportAmt;
		$vSorTransportAmtTTC = 0;
	}
				
					
	$vSorNetTotal         = $vSorGrossTotal + $vSorVat - $vSorDiscountAmt;
	$vSorTaxableBase1     = ($vSorTaxable*$PRate)/$PRate1;
	$vSorTaxableBase2     = ($vSorTaxable*$PRate)/$PRate2;
	$vSorNoneTaxableBase1 = ($vSorNoneTaxable*$PRate)/$PRate1;
	$vSorNoneTaxableBase2 = ($vSorNoneTaxable*$PRate)/$PRate2;
	$vSorDiscountAmtBase1 = ($vSorDiscountAmt*$PRate)/$PRate1;
	$vSorDiscountAmtBase2 = ($vSorDiscountAmt*$PRate)/$PRate2;
	$vSorGrossTotalBase1  = ($vSorGrossTotal*$PRate)/$PRate1;
	$vSorGrossTotalBase2  = ($vSorGrossTotal*$PRate)/$PRate2;
	$vSorVatBase1 		  = ($vSorVat*$PRate)/$PRate1;
	$vSorVatBase2 		  = ($vSorVat*$PRate)/$PRate2;
	$vSorTransportAmtB1   = ($vSorTransportAmt*$PRate)/$PRate1;
	$vSorTransportAmtB2   = ($vSorTransportAmt*$PRate)/$PRate2;	
					

	$vSorTax1B1  = ($vSorTax1*$PRate)/$PRate1;
	$vSorTax1B2  = ($vSorTax1*$PRate)/$PRate2;		
	$vSorTax2B1  = ($vSorTax2*$PRate)/$PRate1;
	$vSorTax2B2  = ($vSorTax2*$PRate)/$PRate2;		
	$vSorTax3B1  = ($vSorTax3*$PRate)/$PRate1;
	$vSorTax3B2  = ($vSorTax3*$PRate)/$PRate2;		
	$vSorTax4B1  = ($vSorTax4*$PRate)/$PRate1;
	$vSorTax4B2  = ($vSorTax4*$PRate)/$PRate2;		
	$vSorTax5B1  = ($vSorTax5*$PRate)/$PRate1;
	$vSorTax5B2  = ($vSorTax5*$PRate)/$PRate2;	
	
	fbegin();
	
	$sub_query1 = " UPDATE sorder SET ".
				  " Sorder_Taxable = $vSorTaxable, Sorder_TaxableBase1 = $vSorTaxableBase1, Sorder_TaxableBase2 = $vSorTaxableBase2, ".
				  " Sorder_NoneTaxable = $vSorNoneTaxable, Sorder_NoneTaxableBase1 = $vSorNoneTaxableBase1, Sorder_NoneTaxableBase2 = $vSorNoneTaxableBase2, ".
				  " Sorder_DiscountAmount = $vSorDiscountAmt, Sorder_DiscountBase1 = $vSorDiscountAmtBase1, Sorder_DiscountBase2 = $vSorDiscountAmtBase2, ".
				  " Sorder_DiscountPer = $vSorDiscountPer, Sorder_VAT = $vSorVat, Sorder_VATBase1 = $vSorVatBase1, Sorder_VATBase2 = $vSorVatBase2, ".
				  " Sorder_VATChckbx = $PVatChk, ".
				  " Sorder_tax1 = $vSorTax1, Sorder_tax1base1 = $vSorTax1B1, Sorder_tax1base2 = $vSorTax1B2,  ".
				  " Sorder_tax2 = $vSorTax2, Sorder_tax2base1 = $vSorTax2B1, Sorder_tax2base2 = $vSorTax2B2,  ".
				  " Sorder_tax3 = $vSorTax3, Sorder_tax3base1 = $vSorTax3B1, Sorder_tax3base2 = $vSorTax3B2,  ".
				  " Sorder_tax4 = $vSorTax4, Sorder_tax4base1 = $vSorTax4B1, Sorder_tax4base2 = $vSorTax4B2,  ".
				  " Sorder_tax5 = $vSorTax5, Sorder_tax5base1 = $vSorTax5B1, Sorder_tax5base2 = $vSorTax5B2  ";
				  
	//if ($PTransportAmt > 0)			  
		$sub_query1 = $sub_query1.", Sorder_TransportAmount = $vSorTransportAmt, Sorder_TransportBase1 = $vSorTransportAmtB1, Sorder_TransportBase2 = $vSorTransportAmtB2, Sorder_TransportTTC = $vSorTransportAmtTTC ";
		
	$sub_query1 = $sub_query1." WHERE Sorder_id = ".$PId ;
		
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_SOMasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


function Create_SalesOrderJv($PSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_SalesOrderAutoJv(".$PSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	//echo $query; exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_SalesOrderAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_SalesOrderJv: '.$error;

	Return $error;
	

}


function DistributeCostFG($PId, $PBase1, $PBase2, $PRate, $PRate1, $PRate2, $connection) {
	
	$TotalQtyRM  = 0;
	$TotalQtyFG  = 0;
	$TotalCostRM = 0;
	$TotalCostFG = 0;
	$TotalCostIdealRM = 0;
	$TotalQtyIdealRM  = 0;
	
	//Get TotalCost and TotalQty For RM
	$sub_query = " Select Sum(ifNull(ProductionRM_Quantity,0)), Sum(ifNull(ProductionRM_Quantity,0)*ifNull(ProductionRM_Cost,0))  ".
				 " From ProductionRM ".
				 " Where ProductionHD_ID = '".$PId."'";
	$sub_result = selectData($connection, $sub_query);
	$TotalQtyRM  = $sub_result[0];
	$TotalCostRM = $sub_result[1];
	
	//Get TotalCost and TotalQty For FG (Have Fixed Cost Option)
	$sub_query = " Select Sum(ifNull(ProductionFG_Quantity,0)), Sum(ifNull(ProductionFG_Quantity,0)*ifNull(ProductionFG_Cost,0))  ".
				 " From ProductionFG ".
				 " Where ProductionHD_ID = '".$PId."' ".
     			 " And ifNull(ProductionFG_CostOption,1) = 3  ";//echo $sub_query;
	$sub_result = selectData($connection, $sub_query);
	
	//Amount To Distribute = TotalAmount RM - TotalAmount FG That Has Fixed Cost Option
	$TotalQtyRM  = $TotalQtyRM  - $sub_result[0];
	$TotalCostRM = $TotalCostRM - $sub_result[1];
	
	
	if ($TotalCostRM != 0 || $TotalQtyRM != 0) {
	
		$TotalCostIdealRM = 0;
		$TotalCostIdealFG = 0;
	
		//Get TotalCost and TotalQty For FG (Have No Fixed Cost Option)
		$sub_query = " Select ProductionFG_ID, ProductionFG.Item_Code, ifNull(ProductionFG_Quantity,0), ProductionFG.Currency_Code,   ".
					 " Date_Format(ProductionHD_Date, '%d/%m/%Y') As ProductionHD_Date, ifNull(ProductionFG.ProductionFG_CostOption, 1) ".
					 " From ProductionFG As ProductionFG ".
					 " Where ProductionHD_ID = '".$PId."' ".
					 " And ifNull(ProductionFG_CostOption,1) != 3  ";
		//echo $sub_query ; exit;			 
		$sub_result=mysql_query($sub_query, $connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_row($sub_result)){
					
			$vItemCode   	= $sub_rows[1];
			$vItemQty    	= $sub_rows[2];
			$vPrdCurr   	= $sub_rows[3];
			$vPrdDate		= $sub_rows[4];
			$vDistOption 	= $sub_rows[5];
			
			if ($vDistOption == 1) {
				$sub_query1 = " Select ProdRecipeFG.ProdRecipe_Id, ProdRecipeFG.Item_Code, ProdRecipeFG.Item_CodePacked, ifNull(ProdRecipeFG_Quantity, 1)  ".
							  " From ProdRecipeFG ".
							  " Where ProdRecipeFG.Item_Code = '".$vItemCode."' ";echo $sub_query1;
				
				$sub_result1=mysql_query($sub_query1, $connection) or die(mysql_error());
				while($sub_rows1=mysql_fetch_array($sub_result1)){
					$vProdRecipeId   = $sub_rows1[0];
					$vProdRecipeQty += $sub_rows1[3];
					
					$TotalCost = 0;
					
					$sub_query2 = " Select ProdRecipeRM.ProdRecipeRM_Id, ProdRecipeRM.Item_Code, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Warehouse_Code, ".
								  " ifNull(ProdRecipeRM_Quantity, 1), ProdRecipeRM_Remark, ifNull(ProdRecipeRM_DistOption, 1), Items.Currency_Code, ifNull(Items.Item_CostMethod,0)  ".
								  " From ProdRecipeRM ".
								  " Inner Join Items on  ProdRecipeRM.Item_Code = Items.Item_Code ".
								  " Where ProdRecipeRM.ProdRecipe_Id = '".$vProdRecipeId."' ";

					$sub_result2=mysql_query($sub_query2, $connection) or die(mysql_error());
					while($sub_rows2=mysql_fetch_array($sub_result2)){	
						$vItemCodeRM	= $sub_rows2[1];
						$vItemQtyRM		= $sub_rows2[4];
						$ItemCurr 		= $sub_rows2[7];
						$ItemCostMethod = $sub_rows2[8];
			
						$vPrdDtCost  = 0;
						$vPrdDtCost  = Get_CostPrice($vItemCodeRM, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $PBase1, $PBase2, $connection);
						
						$TotalCost = $TotalCost + ($vItemQtyRM * $vPrdDtCost);
						
					}
					
					
				}
				
				$TotalCostIdealRM = $TotalCostIdealRM + ($TotalCost/$vProdRecipeQty)*$vItemQty;
			
			}
			else if ($vDistOption == 2) {
				$TotalQtyFG  = $TotalQtyFG  + $vItemQty;
			}	
			
		}		
					 
		
		//Distribute Cost On FG Items According To Distribution Method (Exclude Items With Fixed Option)
		$sub_query = " Select ProductionFG_ID, ProductionFG.Item_Code, ifNull(ProductionFG_Quantity,0), ProductionFG.Currency_Code,   ".
					 " Date_Format(ProductionHD_Date, '%d/%m/%Y') As ProductionHD_Date,  ifNull(ProductionFG.ProductionFG_CostOption, 1) ".
					 " From ProductionFG ".
					 " Inner Join Items on  ProductionFG.Item_Code = Items.Item_Code ".
					 //" Left Join ProdRecipeFG on ProdRecipeFG.Item_Code = ProductionFG.Item_Code and ProdRecipeFG.Warehouse_Code = ProductionFG.Warehouse_Code ".
					 " Where ProductionHD_ID = '".$PId."' ".
					 " And ifNull(ProductionFG_CostOption,1) != 3  ";
					 
		$sub_result=mysql_query($sub_query, $connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
					
			$vPrdFGId   	= $sub_rows[0];		
			$vItemCode   	= $sub_rows[1];
			$vItemQty    	= $sub_rows[2];
			$vPrdCurr   	= $sub_rows[3];
			$vPrdDate		= $sub_rows[4];
			$vDistOption 	= $sub_rows[5];
			
			$vMultiplier 	 = 0;
			$vPrdDtCost      = 0;
			$vPrdDtCostBase1 = 0;
			$vPrdDtCostBase2 = 0;
			
			$TotalCostIdealFG = 0;
			
			if ($vDistOption == 1) {
				$vMultiplier = ($TotalCostRM/$TotalCostIdealRM);
				//echo $vMultiplier; exit;
				$sub_query1 = " Select ProdRecipeFG.ProdRecipe_Id, ProdRecipeFG.Item_Code, ProdRecipeFG.Item_CodePacked, ifNull(ProdRecipeFG_Quantity, 1)  ".
							  " From ProdRecipeFG ".
							  " Where ProdRecipeFG.Item_Code = '".$vItemCode."' ";
				
				$sub_result1=mysql_query($sub_query1, $connection) or die(mysql_error());
				while($sub_rows1=mysql_fetch_array($sub_result1)){
					$vProdRecipeId = $sub_rows1[0];
					$vItemQtyFG	   = $sub_rows1[3];
					
					$sub_query2 = " Select ProdRecipeRM.ProdRecipeRM_Id, ProdRecipeRM.Item_Code, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Warehouse_Code, ".
								  " ifNull(ProdRecipeRM_Quantity, 1), ProdRecipeRM_Remark, ifNull(ProdRecipeRM_DistOption, 1), Items.Currency_Code, ifNull(Items.Item_CostMethod,0)  ".
								  " From ProdRecipeRM ".
								  " Inner Join Items on  ProdRecipeRM.Item_Code = Items.Item_Code ".
								  " Where ProdRecipeRM.ProdRecipe_Id = '".$vProdRecipeId."' ";

					$sub_result2=mysql_query($sub_query2, $connection) or die(mysql_error());
					while($sub_rows2=mysql_fetch_array($sub_result2)){	
						$vItemCodeRM	= $sub_rows2[1];
						$vItemQtyRM		= $sub_rows2[4];
						$ItemCurr 		= $sub_rows2[7];
						$ItemCostMethod = $sub_rows2[8];
			
						$vPrdDtCost  = 0;
						$vPrdDtCost  = Get_CostPrice($vItemCodeRM, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $PBase1, $PBase2, $connection);
						
						$TotalCostIdealFG = $TotalCostIdealFG + ($vItemQtyRM * $vPrdDtCost);	
						//echo "Qty=".$vItemQtyRM." Cost=".$vPrdDtCost." Total=".$TotalCostIdealFG."<br>";
					}
				}
				
				//$vPrdDtCost      = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vPrdDate, $vPrdCurr, $PBase1, $PBase2, $connection);
				$vPrdDtCost		 = (($TotalCostIdealFG*$vMultiplier)/$vItemQtyFG);
				$vPrdDtCostBase1 = ($vPrdDtCost*$PRate)/$PRate1;
				$vPrdDtCostBase2 = ($vPrdDtCost*$PRate)/$PRate2;
			}
			else if ($vDistOption == 2) {
				$vMultiplier = ($vItemQty/$TotalQtyFG)*100;
				
				$vPrdDtCost		 = (($TotalCostRM*$vMultiplier/100)/$vItemQty);
				$vPrdDtCostBase1 = ($vPrdDtCost*$PRate)/$PRate1;
				$vPrdDtCostBase2 = ($vPrdDtCost*$PRate)/$PRate2;
			}
				
			//return $vPrdDtCost . '===' . $TotalCostRM; exit;
			
			$sub_query3 = " UPDATE ProductionFG SET ".
						  " ProductionFG_Cost = $vPrdDtCost, ProductionFG_CostBase1 = $vPrdDtCostBase1, ProductionFG_CostBase2 = $vPrdDtCostBase2  ".
						  " WHERE ProductionFG_ID = '".$vPrdFGId."'";
						 
			$sub_result3=mysql_query($sub_query3,$connection);
			//echo $sub_query3."<br>";exit;
			
		}		
	}
	
	
	Return 1;
}

function Create_TransferRequestJv($PSaId, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_RentInvoiceAutoJv(".$PSaId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	// echo $query; exit;
	$result = mysql_query($query,$conn) or die($query." ".mysql_error());
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	
	
	
	//echo $cur1[0];exit;
	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_DeliveryAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_DeliveryJv: '.$error;

	Return $error;
	

}

?>