<?php
	//session_start();

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
	
//Return Date in DD/MM/YYYY format
function displayDate($data){
	return substr($data, 6, 2)."/".substr($data, 4, 2)."/".substr($data, 0, 4);		
}
//Return Today's Date in DD/MM/YYYY format
function displayToday(){
	return strftime("%d")."/".strftime("%m")."/".strftime("%Y");
}
//Return Today's Date in YYYYMMDD format
function insertToday(){
	return strftime("%Y") . strftime("%m") . strftime("%d");
}

//Return Date in YYYY-MM-DD HH:MM:SS format. Supplied Format: DD/MM/YYYY
function insertMySQLDate($data){
	$data = insertDate($data);
	return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");
}
	
//Return Date in YYYYMMDD format. Supplied Format: DD/MM/YYYY
function insertDate($data){
	return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
}

//Return Date in YYYYMMDD format. Supplied Format: YYYY-MM-DD
function insertParadoxDate($data){
	return substr($data, 0, 4) . substr($data, 5, 2) . substr($data, 8, 2);
}

//Return Date in YYYY-MM-DD format. Supplied Format: YYYYMMDD
function displayParadoxDate($data){
	return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2);
}

//// Return Date in YYYY-MM-DD format
function explodeword($date)
{

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

return $trim;
}

// Return the number of days between the two dates format YYYY-MM-DD:
function dateDiff ($d1, $d2) {
	return round(abs(strtotime($d1)-strtotime($d2))/86400);
}

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

//Method to query database and get the first row
function selectData($conn, $query){
	$result = mysql_query($query, $conn);
	$cur = mysql_fetch_row($result);		
	return $cur;
}
function updateIData($conn, $query, $commit){
	//mysqli_autocommit($conn, false);
	if (mysql_query($conn, $query)){
		if ($commit){
			mysql_commit($conn);
		}
		return true;
	}else{
		return false;
	}		
}

//Method to Insert/ Update/ Delete Record in Database
function updateData($conn, $query, $commit){
	if (mysql_query($query, $conn)){				
		return true;
	}else{
		return false;
	}
}

function get_nextsequence($SeqField , $ProjCostCent ,$connection)
{
	//mysql_query("START TRANSACTION",$connection);
	$query = "Select ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject , ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter From Module ";
	$result= mysql_query($query,$connection) or die( mysql_error());
	while($rowmodule=mysql_fetch_array($result)){
		extract($rowmodule);
	}
	
	$query = "Select Count(*) From Sequence";

	if ($ProjCostCent != '' && $Module_ReferenceByCostcenter == 1)
		$query = $query."  Where '".$ProjCostCent."' like Concat(Sequence.CostCenter,'%') ";
	else if ($ProjCostCent != '' && $Module_ReferenceByProject == 1)
		$query = $query."  Where '".$ProjCostCent."' Like Concat(Sequence.Project,'%') ";	
		
	$result1=mysql_query($query,$connection)	or die( mysql_error());
	$row=mysql_fetch_row($result1);
	$Countt = $row[0];
	 
	 
	if ($Countt==0)
	{
		if ($ProjCostCent != '' && $Module_ReferenceByCostcenter == 1)
			$query = "Insert Into Sequence (".$SeqField.",CostCenter) Values (1,'".$ProjCostCent."')";
		else if ($ProjCostCent != '' && $Module_ReferenceByProject == 1)	
			$query = "Insert Into Sequence (".$SeqField.",Project) Values (1,'".$ProjCostCent."')";
		else	
			$query = "Insert Into Sequence (".$SeqField.") Values (1)";
			
		$result1=mysql_query($query,$connection)	or die( mysql_error());
	}	
	else
	{
		if ($ProjCostCent == '') 
		{
			$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where Sequence.CostCenter is null and Sequence.Project is null";
			$result1=mysql_query($query,$connection)	or die( mysql_error());
		}
		else
		{
			if ($Module_ReferenceByCostcenter == 1)
				$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where '".$ProjCostCent."' like Concat(Sequence.CostCenter,'%') ";
			else if ($Module_ReferenceByProject == 1)
				$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where '".$ProjCostCent."' Like Concat(Sequence.Project,'%') ";
			
			$result1=mysql_query($query,$connection)	or die( mysql_error());
		}
		
	}
	
	$query = " SELECT LAST_INSERT_ID()";
	$result1=mysql_query($query,$connection)	or die( mysql_error());
	$row=mysql_fetch_row($result1);
	$NextValue = $row[0];
	if ($NextValue =='')
		$NextValue = 1 ;
 	
	//mysql_query("COMMIT",$connection);
	return $NextValue;
}


function Distribute_TotalDiscount($PPurId, $PRate, $PRate1, $PRate2, $connection, $PLoggedCode) {
	
	//echo $PPurId.', '.$PPurGrossTotal.', '. $PPurDiscountAmt.', '. $connection; exit;
	
	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 from setup ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	while($rowsetup=mysql_fetch_array($resultsetup)){
		extract($rowsetup);
	}
	
	$querytotal = " Select Purchase_ID, Purchases.Currency_code, Purchase_Total, Purchase_DiscountAmount ".
				  " From Temp_Purchases As Purchases  ".
				  " Where Purchase_ID = ".$PPurId;
				  //" And Logged_Code = '".$PLoggedCode."' ";
		
	
	$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
	$rowstotal=mysql_fetch_array($resulttotal);
	
	$vPurTotal   = $rowstotal[2];
	$vPurDisAmt   = $rowstotal[3];
	
	$query = " Select PurchaseDt_ID,  ".
             " ((PurchaseDt_Quantity*PurchaseDt_Price)-((PurchaseDt_Quantity*PurchaseDt_Price*ifNull(PurchaseDt_DiscountPer,0))/100)) As Total ".
         	 " From Temp_PurchasesDt As PurchasesDt  ".
			 " Where PurchasesDt.Purchase_ID = ".$PPurId;
			 //" And PurchasesDt.Logged_Code = '".$PLoggedCode."' ";
			   
	//echo $query; 
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){
	
		$vPurDtId = $rows[0];
		$vPurDtTotal = $rows[1];
		
		$vPurDtDiscountAmt = 0;
		$vPurDtDiscountAmt = ($vPurDtTotal/$vPurTotal)*$vPurDisAmt;
		$vPurDtDiscountAmtBase1 = ($vPurDtDiscountAmt*$PRate)/$PRate1;
		$vPurDtDiscountAmtBase2 = ($vPurDtDiscountAmt*$PRate)/$PRate2;
		
		$queryupd =  " UPDATE temp_purchasesdt SET PurchaseDt_DiscountAmount = $vPurDtDiscountAmt, ".
					 " PurchaseDt_DiscountBase1 = $vPurDtDiscountAmtBase1, PurchaseDt_DiscountBase2 = $vPurDtDiscountAmtBase2  ".
					 " Where PurchaseDt_ID = ".$vPurDtId;
					 //" And Logged_Code = '".$PLoggedCode."' ";
		
		if (!updateData($connection, $queryupd, true))
			$error  = mysql_error(); 
		

	}
	
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalDiscount: '.$error;
	   
	Return $error;
}

function Distribute_TotalCharges($PPurId, $connection, $PLoggedCode) {
	
	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 from setup ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	while($rowsetup=mysql_fetch_array($resultsetup)){
		extract($rowsetup);
	}

	
	$queryupd =  " UPDATE temp_purchasesdt SET PurchaseDt_Charges = 0, PurchaseDt_ChargesBase1 = 0, PurchaseDt_ChargesBase2 = 0,  ".
			     " PurchaseDt_VatCharge = 0, PurchaseDt_VatChargeBase1 = 0, PurchaseDt_VatChargeBase2 = 0  ".
			     " Where Purchase_ID = ".$PPurId;
			     //" And Logged_Code = '".$PLoggedCode."' ";
	
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
			

	$queryupd =  " UPDATE temp_purchases SET Purchase_Charges = 0, Purchase_ChargesBase1 = 0, Purchase_ChargesBase2 = 0,  ".
				 " Purchase_VatCharges = 0, Purchase_VatChargesBase1 = 0, Purchase_VatChargesBase2 = 0  ".
				 " Where Purchase_ID = ".$PPurId;
				 //" And Logged_Code = '".$PLoggedCode."' ";
									 
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
					
			
			
			
	$querycharges = " Select Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, ifNull(Charges_Amount,0), ifNull(Charges_AmountBase1,0), ifNull(Charges_AmountBase2,0), ".
					" Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charges_isSubjToCharge, Auto ".
					" From temp_purchasecharges ".
					" Where Purchase_ID = ".$PPurId;
					//" And Logged_Code = '".$PLoggedCode."' ";

	$resultcharges=mysql_query($querycharges,$connection) or die(mysql_error());
	
	
		
	
	// Loop From TempCharges Table
	while($rowcharges=mysql_fetch_array($resultcharges)){
		$vPurNetTotal   = 0;
		$vPurNetTotalB1 = 0;
		$vPurNetTotalB2 = 0;
		$vTotalQty 	  = 0;
		$vTotalVolume = 0;
		
		$vPurCharges   = 0;
		$vPurChargesB1 = 0;
		$vPurChargesB2 = 0;
		$vPurVatCharges   = 0;
		$vPurVatChargesB1 = 0;
		$vPurVatChargesB2 = 0;
		
		//Distribution Option
		$vChgDistOption = $rowcharges[6];
		
		// Charges Amount Should Not Be Zero
		if ($rowcharges[3] > 0) {
		
			if ($vChgDistOption == 1) {
				$querytotal = " Select Purchase_ID, Purchases.Currency_code, (Purchase_Total - Purchase_DiscountAmount) As NetTotal, ".
							  " (Purchase_TotalBase1 - Purchase_DiscountBase1) As NetTotalBase1, (Purchase_TotalBase2 - Purchase_DiscountBase2) As NetTotalBase2 ".
							  " From Temp_Purchases As Purchases  ".
							  " Where Purchase_ID = ".$PPurId;
							
			} else {			
				$querytotal = " Select Purchase_ID, Currency_code, Sum(PurchaseDt_Quantity) As TotalQuantity, Sum(PurchaseDt_Volume) As TotalVolume ".
							  " From Temp_PurchasesDt As PurchasesDt  ".
							  " Where PurchasesDt.Purchase_ID = ".$PPurId.
							  " Group By Purchase_ID, Currency_code ";
			}
			
			//echo $querytotal;
			$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
			$rowstotal=mysql_fetch_array($resulttotal);
			
			if ($vChgDistOption == 1) {
				$vPurNetTotal   = $rowstotal[2];
				$vPurNetTotalB1 = $rowstotal[3];
				$vPurNetTotalB2 = $rowstotal[4];
			} else
			{
				$vTotalQty = $rowstotal[2];
				$vTotalVolume = $rowstotal[3];
			}
			
			$vChgAmt   = $rowcharges[3];
			$vChgAmtB1 = $rowcharges[4];
			$vChgAmtB2 = $rowcharges[5];
			
			// If Charges Currency Differs From Purchase Currency
			if ($rowcharges[2] != $rowstotal[1]) {
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' )";
				$result = selectData($connection, $query);
				$ratefr = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' )";
				$result = selectData($connection, $query);
				$rateto = $result[0];
				
				$vChgAmt = ($vChgAmt*$ratefr)/$rateto;
			}
				
		
			$querypurdt = " Select PurchaseDt_ID,  ".
						  " ((PurchaseDt_Quantity*PurchaseDt_Price)-((PurchaseDt_Quantity*PurchaseDt_Price*ifNull(PurchaseDt_DiscountPer,0))/100) - PurchaseDt_DiscountAmount) As NetTotal, ".
						  " ((PurchaseDt_Quantity*PurchaseDt_PriceBase1)-((PurchaseDt_Quantity*PurchaseDt_PriceBase1*ifNull(PurchaseDt_DiscountPer,0))/100) - PurchaseDt_DiscountBase1) As NetTotalBase1, ".
						  " ((PurchaseDt_Quantity*PurchaseDt_PriceBase2)-((PurchaseDt_Quantity*PurchaseDt_PriceBase2*ifNull(PurchaseDt_DiscountPer,0))/100) - PurchaseDt_DiscountBase2) As NetTotalBase2, ".
						  " PurchaseDt_Quantity, PurchaseDt_Volume, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2  ".
						  " From Temp_PurchasesDt As PurchasesDt  ".
						  " Where PurchasesDt.Purchase_ID = ".$PPurId;
						  //" And PurchasesDt.Logged_Code = '".$PLoggedCode."' ";
				   
			//echo $querypurdt; exit;
			$resultpurdt=mysql_query($querypurdt,$connection) or die(mysql_error());
			$TotalRecords = mysql_num_rows($resultpurdt); 
			$CurRow = 0; // Count For Current Row In Loop Of PurchasesDt Table
			while($rowspurdt=mysql_fetch_array($resultpurdt)){
				
				$CurRow = $CurRow + 1;
				
				$vPurDtId         = '';
				$vPurDtNetTotal   = 0;
				$vPurDtNetTotalB1 = 0;
				$vPurDtNetTotalB2 = 0;
				$vPurDtQty 	  = 0;
				$vPurDtVolume = 0;
				$vPurDtChgPer = 0;
				$vPurDtChgAmt   = 0;
				$vPurDtChgAmtB1 = 0;
				$vPurDtChgAmtB2 = 0;
				
				$vPurDtCharges   = 0;
				$vPurDtChargesB1 = 0;
				$vPurDtChargesB2 = 0;
				
				$vPurDtId         = $rowspurdt[0];
				$vPurDtNetTotal   = $rowspurdt[1];
				$vPurDtNetTotalB1 = $rowspurdt[2];
				$vPurDtNetTotalB2 = $rowspurdt[3];
				$vPurDtQty    = $rowspurdt[4];
				$vPurDtVolume = $rowspurdt[5];
				$vPurDtChgPer = $rowspurdt[6];
				$vPurDtChgAmt   = $rowspurdt[7];
				$vPurDtChgAmtB1 = $rowspurdt[8];
				$vPurDtChgAmtB2 = $rowspurdt[9];
				
				//Calculation For PurchaseDt Charges
				if ($vChgDistOption == 1) {
					$vPurDtCharges   = ($vPurDtNetTotal   / $vPurNetTotal  ) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtNetTotalB1 / $vPurNetTotalB1) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtNetTotalB2 / $vPurNetTotalB2) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 2)
				{ 
					$vPurDtCharges   = ($vPurDtQty / $vTotalQty) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtQty / $vTotalQty) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtQty / $vTotalQty) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 3 && $vTotalVolume > 0)
				{
					$vPurDtCharges   = ($vPurDtVolume / $vTotalVolume) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtVolume / $vTotalVolume) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtVolume / $vTotalVolume) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 4)
				{ 
					$vPurDtCharges   = (($vPurDtNetTotal   * $vPurDtChgPer) / 100);
					$vPurDtChargesB1 = (($vPurDtNetTotalB1 * $vPurDtChgPer) / 100);
					$vPurDtChargesB2 = (($vPurDtNetTotalB2 * $vPurDtChgPer) / 100);
					
					$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				else if ($vChgDistOption == 5)
				{ 
					$vPurDtCharges   = $vPurDtChgAmt;
					$vPurDtChargesB1 = $vPurDtChgAmtB1;
					$vPurDtChargesB2 = $vPurDtChgAmtB2;
					
					$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				
				$vPurDtCharges   = $vPurDtCharges;
				$vPurDtChargesB1 = $vPurDtChargesB1;
				$vPurDtChargesB2 = $vPurDtChargesB2;
					
				//Calculation For Purchase Charges
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$vPurCharges   = $vPurCharges   + $vPurDtCharges;
					$vPurChargesB1 = $vPurChargesB1 + $vPurDtChargesB1;
					$vPurChargesB2 = $vPurChargesB2 + $vPurDtChargesB2;
				} else {
					$vPurVatCharges   = $vPurVatCharges   + $vPurDtCharges;
					$vPurVatChargesB1 = $vPurVatChargesB1 + $vPurDtChargesB1;
					$vPurVatChargesB2 = $vPurVatChargesB2 + $vPurDtChargesB2;
				}
				
				//Add the difference between total charges amount and the sum of distributed amount to the last record in purchasesdt
				// to avoid differences due to rounding
				if ($CurRow == $TotalRecords) {
					$vPurDtCharges   = $vPurDtCharges   + ($vChgAmt   - $vPurCharges - $vPurVatCharges);
					$vPurDtChargesB1 = $vPurDtChargesB1 + ($vChgAmtB1 - $vPurChargesB1 - $vPurVatChargesB1);
					$vPurDtChargesB2 = $vPurDtChargesB2 + ($vChgAmtB2 - $vPurChargesB2 - $vPurVatChargesB2);
					
					//ChargesIsVat False
					if ($rowcharges[7] == 0) {
						$vPurCharges   = $vChgAmt;
						$vPurChargesB1 = $vChgAmtB1;
						$vPurChargesB2 = $vChgAmtB2;
					} else {
						$vPurVatCharges   = $vChgAmt;
						$vPurVatChargesB1 = $vChgAmtB1;
						$vPurVatChargesB2 = $vChgAmtB2;
					}
				}
				//echo $vPurDtCharges.'-'.$vPurDtChargesB1.'-'.$vPurDtChargesB2,'<br>';exit;
				
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$querypurdtupd =  " UPDATE temp_purchasesdt SET PurchaseDt_Charges = ifNull(PurchaseDt_Charges,0) + $vPurDtCharges, ".
									  " PurchaseDt_ChargesBase1 = ifNull(PurchaseDt_ChargesBase1,0) + $vPurDtChargesB1, ".
									  " PurchaseDt_ChargesBase2 = ifNull(PurchaseDt_ChargesBase2,0) + $vPurDtChargesB2  ".
									  " Where PurchaseDt_ID = ".$vPurDtId;
				}
				else {
					$querypurdtupd =  " UPDATE temp_purchasesdt SET PurchaseDt_VatCharge = ifNull(PurchaseDt_VatCharge,0) + $vPurDtCharges, ".
									  " PurchaseDt_VatChargeBase1 = ifNull(PurchaseDt_VatChargeBase1,0) + $vPurDtChargesB1, ".
									  " PurchaseDt_VatChargeBase2 = ifNull(PurchaseDt_VatChargeBase2,0) + $vPurDtChargesB2  ".
									  " Where PurchaseDt_ID = ".$vPurDtId;
				}
				
				if (!updateData($connection, $querypurdtupd, true))
					$error  = mysql_error(); 
			

			} //End Loop Fo PurchasesDt Table
		
			//Update Purchase Charges
			$querypurupd =  " UPDATE temp_purchases SET ".
							" Purchase_Charges = ifNull(Purchase_Charges,0) + $vPurCharges, ".
							" Purchase_ChargesBase1 = ifNull(Purchase_ChargesBase1,0) + $vPurChargesB1, ".
							" Purchase_ChargesBase2 = ifNull(Purchase_ChargesBase2,0) + $vPurChargesB2,  ".
							" Purchase_VatCharges = ifNull(Purchase_VatCharges,0) + $vPurVatCharges, ".
							" Purchase_VatChargesBase1 = ifNull(Purchase_VatChargesBase1,0) + $vPurVatChargesB1, ".
							" Purchase_VatChargesBase2 = ifNull(Purchase_VatChargesBase2,0) + $vPurVatChargesB2  ".
							" Where Purchase_ID = ".$PPurId;
							//" And Logged_Code = '".$PLoggedCode."' ";
									
			if (!updateData($connection, $querypurupd, true))
				$error  = mysql_error(); 
					
			
			if ($vChgDistOption == 4 || $vChgDistOption == 5) {
				//Update Charges Table
				$querychgupd =  " UPDATE temp_purchasecharges SET Charges_Amount = $vChgAmt, ".
								" Charges_AmountBase1 = $vChgAmtB1, Charges_AmountBase2 = $vChgAmtB2  ".
								" Where Purchase_ID = ".$PPurId.
								" And Auto = ".$rowcharges[10];
										 
				if (!updateData($connection, $querychgupd, true))
					$error  = mysql_error(); 
						
						
			}
			
			
		}		
	} //End Loop From TempCharges Table
		
	//echo 'error= '.$error; exit;
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalCharges: '.$error;
	
	Return $error;
}



function Distribute_TotalChargesOrder($PPurId, $connection, $PLoggedCode) {
	
	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 from setup ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	while($rowsetup=mysql_fetch_array($resultsetup)){
		extract($rowsetup);
	}

	
	$queryupd =  " UPDATE temp_porderdt SET PorderDt_Charges = 0, PorderDt_ChargesBase1 = 0, PorderDt_ChargesBase2 = 0,  ".
			     " PorderDt_VatCharge = 0, PorderDt_VatChargeBase1 = 0, PorderDt_VatChargeBase2 = 0  ".
			     " Where Porder_ID = ".$PPurId;
			     //" And Logged_Code = '".$PLoggedCode."' ";
	
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
			

	$queryupd =  " UPDATE temp_Porder SET Porder_Charges = 0, Porder_ChargesBase1 = 0, Porder_ChargesBase2 = 0,  ".
				 " Porder_VatCharges = 0, Porder_VatChargesBase1 = 0, Porder_VatChargesBase2 = 0  ".
				 " Where Porder_ID = ".$PPurId;
				 //" And Logged_Code = '".$PLoggedCode."' ";
									 
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
					
			
	
			
	$querycharges = " Select Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, ifNull(Charges_Amount,0), ifNull(Charges_AmountBase1,0), ifNull(Charges_AmountBase2,0), ".
					" Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charges_isSubjToCharge, Auto ".
					" From Temp_Purchaseordercharges ".
					" Where Purchase_id = ".$PPurId;
					//" And Logged_Code = '".$PLoggedCode."' ";

	$resultcharges=mysql_query($querycharges,$connection) or die(mysql_error());
	
	
		
	
	// Loop From TempCharges Table
	while($rowcharges=mysql_fetch_array($resultcharges)){
		$vPurNetTotal   = 0;
		$vPurNetTotalB1 = 0;
		$vPurNetTotalB2 = 0;
		$vTotalQty 	  = 0;
		$vTotalVolume = 0;
		
		$vPurCharges   = 0;
		$vPurChargesB1 = 0;
		$vPurChargesB2 = 0;
		$vPurVatCharges   = 0;
		$vPurVatChargesB1 = 0;
		$vPurVatChargesB2 = 0;
		
		//Distribution Option
		$vChgDistOption = $rowcharges[6];
		
		// Charges Amount Should Not Be Zero
		if ($rowcharges[3] > 0) {
		
			if ($vChgDistOption == 1) {
				$querytotal = " Select Porder_ID, Porder.Currency_code, (Porder_Total - Porder_DiscountAmount) As NetTotal, ".
							  " (Porder_TotalBase1 - Porder_DiscountBase1) As NetTotalBase1, (Porder_TotalBase2 - Porder_DiscountBase2) As NetTotalBase2 ".
							  " From Temp_Porder As Porder  ".
							  " Where Porder_ID = ".$PPurId;
							
			} else {			
				$querytotal = " Select Porder_ID, Currency_code, Sum(PorderDt_Quantity) As TotalQuantity, Sum(PorderDt_Volume) As TotalVolume ".
							  " From Temp_PorderDt As PorderDt  ".
							  " Where PorderDt.Porder_ID = ".$PPurId.
							  " Group By Porder_ID, Currency_code ";
			}
			
			//echo $querytotal;
			$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
			$rowstotal=mysql_fetch_array($resulttotal);
			
			if ($vChgDistOption == 1) {
				$vPurNetTotal   = $rowstotal[2];
				$vPurNetTotalB1 = $rowstotal[3];
				$vPurNetTotalB2 = $rowstotal[4];
			} else
			{
				$vTotalQty = $rowstotal[2];
				$vTotalVolume = $rowstotal[3];
			}
			
			$vChgAmt   = $rowcharges[3];
			$vChgAmtB1 = $rowcharges[4];
			$vChgAmtB2 = $rowcharges[5];
			
			// If Charges Currency Differs From Porder Currency
			if ($rowcharges[2] != $rowstotal[1]) {
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' )";
				$result = selectData($connection, $query);
				$ratefr = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' )";
				$result = selectData($connection, $query);
				$rateto = $result[0];
				
				$vChgAmt = ($vChgAmt*$ratefr)/$rateto;
			}
				
		
			$querypurdt = " Select PorderDt_ID,  ".
						  " ((PorderDt_Quantity*PorderDt_Price)-((PorderDt_Quantity*PorderDt_Price*ifNull(PorderDt_Discount,0))/100) - PorderDt_DiscountAmount) As NetTotal, ".
						  " ((PorderDt_Quantity*PorderDt_PriceBase1)-((PorderDt_Quantity*PorderDt_PriceBase1*ifNull(PorderDt_Discount,0))/100) - PorderDt_DiscountBase1) As NetTotalBase1, ".
						  " ((PorderDt_Quantity*ProderDt_PriceBase2)-((PorderDt_Quantity*ProderDt_PriceBase2*ifNull(PorderDt_Discount,0))/100) - PorderDt_DiscountBase2) As NetTotalBase2, ".
						  " PorderDt_Quantity, PorderDt_Volume, PorderDt_ChargePer, PorderDt_Charges, PorderDt_ChargesBase1, PorderDt_ChargesBase2  ".
						  " From Temp_PorderDt As PorderDt  ".
						  " Where PorderDt.Porder_ID = ".$PPurId;
						  //" And PurchasesDt.Logged_Code = '".$PLoggedCode."' ";
				   
			//echo $querypurdt; exit;
			$resultpurdt=mysql_query($querypurdt,$connection) or die(mysql_error());
			$TotalRecords = mysql_num_rows($resultpurdt); 
			$CurRow = 0; // Count For Current Row In Loop Of PurchasesDt Table
			while($rowspurdt=mysql_fetch_array($resultpurdt)){
				
				$CurRow = $CurRow + 1;
				
				$vPurDtId         = '';
				$vPurDtNetTotal   = 0;
				$vPurDtNetTotalB1 = 0;
				$vPurDtNetTotalB2 = 0;
				$vPurDtQty 	  = 0;
				$vPurDtVolume = 0;
				$vPurDtChgPer = 0;
				$vPurDtChgAmt   = 0;
				$vPurDtChgAmtB1 = 0;
				$vPurDtChgAmtB2 = 0;
				
				$vPurDtCharges   = 0;
				$vPurDtChargesB1 = 0;
				$vPurDtChargesB2 = 0;
				
				$vPurDtId         = $rowspurdt[0];
				$vPurDtNetTotal   = $rowspurdt[1];
				$vPurDtNetTotalB1 = $rowspurdt[2];
				$vPurDtNetTotalB2 = $rowspurdt[3];
				$vPurDtQty    = $rowspurdt[4];
				$vPurDtVolume = $rowspurdt[5];
				$vPurDtChgPer = $rowspurdt[6];
				$vPurDtChgAmt   = $rowspurdt[7];
				$vPurDtChgAmtB1 = $rowspurdt[8];
				$vPurDtChgAmtB2 = $rowspurdt[9];
				
				//Calculation For PorderDt Charges
				if ($vChgDistOption == 1) {
					$vPurDtCharges   = ($vPurDtNetTotal   / $vPurNetTotal  ) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtNetTotalB1 / $vPurNetTotalB1) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtNetTotalB2 / $vPurNetTotalB2) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 2)
				{ 
					$vPurDtCharges   = ($vPurDtQty / $vTotalQty) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtQty / $vTotalQty) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtQty / $vTotalQty) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 3 && $vTotalVolume > 0)
				{
					$vPurDtCharges   = ($vPurDtVolume / $vTotalVolume) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtVolume / $vTotalVolume) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtVolume / $vTotalVolume) * $vChgAmtB2;
				}
				else if ($vChgDistOption == 4)
				{ 
					$vPurDtCharges   = (($vPurDtNetTotal   * $vPurDtChgPer) / 100);
					$vPurDtChargesB1 = (($vPurDtNetTotalB1 * $vPurDtChgPer) / 100);
					$vPurDtChargesB2 = (($vPurDtNetTotalB2 * $vPurDtChgPer) / 100);
					
					$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				else if ($vChgDistOption == 5)
				{ 
					$vPurDtCharges   = $vPurDtChgAmt;
					$vPurDtChargesB1 = $vPurDtChgAmtB1;
					$vPurDtChargesB2 = $vPurDtChgAmtB2;
					
					$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				
				$vPurDtCharges   = $vPurDtCharges;
				$vPurDtChargesB1 = $vPurDtChargesB1;
				$vPurDtChargesB2 = $vPurDtChargesB2;
					
				//Calculation For porder Charges
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$vPurCharges   = $vPurCharges   + $vPurDtCharges;
					$vPurChargesB1 = $vPurChargesB1 + $vPurDtChargesB1;
					$vPurChargesB2 = $vPurChargesB2 + $vPurDtChargesB2;
				} else {
					$vPurVatCharges   = $vPurVatCharges   + $vPurDtCharges;
					$vPurVatChargesB1 = $vPurVatChargesB1 + $vPurDtChargesB1;
					$vPurVatChargesB2 = $vPurVatChargesB2 + $vPurDtChargesB2;
				}
				
				//Add the difference between total charges amount and the sum of distributed amount to the last record in purchasesdt
				// to avoid differences due to rounding
				if ($CurRow == $TotalRecords) {
					$vPurDtCharges   = $vPurDtCharges   + ($vChgAmt   - $vPurCharges - $vPurVatCharges);
					$vPurDtChargesB1 = $vPurDtChargesB1 + ($vChgAmtB1 - $vPurChargesB1 - $vPurVatChargesB1);
					$vPurDtChargesB2 = $vPurDtChargesB2 + ($vChgAmtB2 - $vPurChargesB2 - $vPurVatChargesB2);
					
					//ChargesIsVat False
					if ($rowcharges[7] == 0) {
						$vPurCharges   = $vChgAmt;
						$vPurChargesB1 = $vChgAmtB1;
						$vPurChargesB2 = $vChgAmtB2;
					} else {
						$vPurVatCharges   = $vChgAmt;
						$vPurVatChargesB1 = $vChgAmtB1;
						$vPurVatChargesB2 = $vChgAmtB2;
					}
				}
				//echo $vPurDtCharges.'-'.$vPurDtChargesB1.'-'.$vPurDtChargesB2,'<br>';exit;
				
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$querypurdtupd =  " UPDATE temp_Porderdt SET PorderDt_Charges = ifNull(PorderDt_Charges,0) + $vPurDtCharges, ".
									  " PorderDt_ChargesBase1 = ifNull(PorderDt_ChargesBase1,0) + $vPurDtChargesB1, ".
									  " PorderDt_ChargesBase2 = ifNull(PorderDt_ChargesBase2,0) + $vPurDtChargesB2  ".
									  " Where PorderDt_ID = ".$vPurDtId;
				}
				else {
					$querypurdtupd =  " UPDATE temp_Porderdt SET PorderDt_VatCharge = ifNull(PorderDt_VatCharge,0) + $vPurDtCharges, ".
									  " PorderDt_VatChargeBase1 = ifNull(PorderDt_VatChargeBase1,0) + $vPurDtChargesB1, ".
									  " PorderDt_VatChargeBase2 = ifNull(PorderDt_VatChargeBase2,0) + $vPurDtChargesB2  ".
									  " Where PorderDt_ID = ".$vPurDtId;
				}
				
				if (!updateData($connection, $querypurdtupd, true))
					$error  = mysql_error(); 
			

			} //End Loop Fo PurchasesDt Table
		
			//Update Purchase Charges
			$querypurupd =  " UPDATE temp_Porder SET ".
							" Porder_Charges = ifNull(Porder_Charges,0) + $vPurCharges, ".
							" Porder_ChargesBase1 = ifNull(Porder_ChargesBase1,0) + $vPurChargesB1, ".
							" Porder_ChargesBase2 = ifNull(Porder_ChargesBase2,0) + $vPurChargesB2,  ".
							" Porder_VatCharges = ifNull(Porder_VatCharges,0) + $vPurVatCharges, ".
							" Porder_VatChargesBase1 = ifNull(Porder_VatChargesBase1,0) + $vPurVatChargesB1, ".
							" Porder_VatChargesBase2 = ifNull(Porder_VatChargesBase2,0) + $vPurVatChargesB2  ".
							" Where Porder_ID = ".$PPurId;
							//" And Logged_Code = '".$PLoggedCode."' ";
									 
			if (!updateData($connection, $querypurupd, true))
				$error  = mysql_error(); 
					
			
			if ($vChgDistOption == 4 || $vChgDistOption == 5) {
				//Update Charges Table
				$querychgupd =  " UPDATE temp_purchaseordercharges SET Charges_Amount = $vChgAmt, ".
								" Charges_AmountBase1 = $vChgAmtB1, Charges_AmountBase2 = $vChgAmtB2  ".
								" Where Purchase_ID = ".$PPurId.
								" And Auto = ".$rowcharges[10];
						
				if (!updateData($connection, $querychgupd, true))
					$error  = mysql_error(); 
						
						
			}
			
			
		}		
	} //End Loop From TempCharges Table
		
	//echo 'error= '.$error; exit;
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalChargesOrder: '.$error;
	
	Return $error;
}


function Distribute_TotalChargesTr($PPurId, $connection, $PLoggedCode) {
	
	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 from setup ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	while($rowsetup=mysql_fetch_array($resultsetup)){
		extract($rowsetup);
	}

	
	$queryupd =  " UPDATE temp_transferdt SET transferdt_chargebase1 = 0, transferdt_chargebase2 = 0, transferdt_VATchargebase1 = 0, transferdt_VATchargebase2 = 0 ".
			     " Where transfer_ID = ".$PPurId;
			     //" And Logged_Code = '".$PLoggedCode."' ";
	//echo $queryupd;exit;
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
			

	$queryupd =  " UPDATE temp_transfer SET amountBase1 = 0, amountBase2 = 0 , amountVATBase1 = 0, amountVATBase2 = 0 ".
				 " Where transfer_ID = ".$PPurId;
				 //" And Logged_Code = '".$PLoggedCode."' ";
									 
	if (!updateData($connection, $queryupd, true))
		$error  = mysql_error(); 
					
			
			
			
	$querycharges = " Select Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, ifNull(Charges_Amount,0), ifNull(Charges_AmountBase1,0), ifNull(Charges_AmountBase2,0), ".
					" Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charges_isSubjToCharge, Auto ".
					" From temp_transfercharges ".
					" Where Transfer_id = ".$PPurId;
					//" And Logged_Code = '".$PLoggedCode."' ";

	$resultcharges=mysql_query($querycharges,$connection) or die(mysql_error());
	
	
		
	
	// Loop From TempCharges Table
	while($rowcharges=mysql_fetch_array($resultcharges)){
		$vPurNetTotal   = 0;
		$vPurNetTotalB1 = 0;
		$vPurNetTotalB2 = 0;
		$vTotalQty 	  = 0;
		$vTotalVolume = 0;
		
		$vPurCharges   = 0;
		$vPurChargesB1 = 0;
		$vPurChargesB2 = 0;
		$vPurVatCharges   = 0;
		$vPurVatChargesB1 = 0;
		$vPurVatChargesB2 = 0;
		
		//Distribution Option
		$vChgDistOption = $rowcharges[6];
		
		// Charges Amount Should Not Be Zero
		if ($rowcharges[3] > 0) {
		
			$querytotal = " select temp_transfer.transfer_ID, Temp_transfer.curencycode, sum(TransferDt_Quantity*transferdt_costbase1), sum(TransferDt_Quantity*transferdt_costbase2)
							from temp_transferdt
							inner join temp_transfer on temp_transfer.transfer_id = temp_transferdt.transfer_id 
							Where temp_transfer.transfer_ID = ".$PPurId." 
							group by temp_transfer.transfer_ID
							";
			
			//echo $querytotal;
			$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
			$rowstotal=mysql_fetch_array($resulttotal);
			
			
			if ($rowstotal[2] == $base1) 
				$vPurNetTotal   = $rowstotal[2];
			else 
				$vPurNetTotal   = $rowstotal[3];
			
			$vPurNetTotalB1 = $rowstotal[2];
			$vPurNetTotalB2 = $rowstotal[3];
		
			
			$vChgAmt   = $rowcharges[3];
			$vChgAmtB1 = $rowcharges[4];
			$vChgAmtB2 = $rowcharges[5];
			
			// If Charges Currency Differs From Purchase Currency
			if ($rowcharges[2] != $rowstotal[1]) {
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowcharges[2]."' )";
				$result = selectData($connection, $query);
				$ratefr = $result[0];
				
				$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$rowstotal[1]."' )";
				$result = selectData($connection, $query);
				$rateto = $result[0];
				
				$vChgAmt = ($vChgAmt*$ratefr)/$rateto;
			}
				
		
			$querypurdt = " Select transferdt.transferDt_ID,  ".
						  " (TransferDt_Quantity*if(curencycode='$base1',transferdt_costbase1, transferdt_costbase2)) As NetTotal, ".
						  " (TransferDt_Quantity*transferdt_costbase1) As NetTotalBase1, ".
						  " (TransferDt_Quantity*transferdt_costbase2) As NetTotalBase2, ".
						  " TransferDt_Quantity, if(curencycode='$base1',transferdt_chargebase1, transferdt_chargebase2) as ChargesAmnt, transferdt_chargebase1, transferdt_chargebase2,  ".
						  " curencycode ".
						  " From Temp_transferDt As transferdt  ".
						  " inner join temp_transfer on temp_transfer.transfer_id = transferdt. transfer_id ".
						  " Where transferdt.transfer_ID = ".$PPurId;
										   
			
			$resultpurdt=mysql_query($querypurdt,$connection) or die(mysql_error());
			$TotalRecords = mysql_num_rows($resultpurdt); 
			$CurRow = 0; // Count For Current Row In Loop Of PurchasesDt Table
			while($rowspurdt=mysql_fetch_array($resultpurdt)){
				
				$CurRow = $CurRow + 1;
				
				$vPurDtId         = '';
				$vPurDtNetTotal   = 0;
				$vPurDtNetTotalB1 = 0;
				$vPurDtNetTotalB2 = 0;
				$vPurDtQty 	  = 0;
				$vPurDtChgAmt   = 0;
				$vPurDtChgAmtB1 = 0;
				$vPurDtChgAmtB2 = 0;
				
				$vPurDtCharges   = 0;
				$vPurDtChargesB1 = 0;
				$vPurDtChargesB2 = 0;
				
				$vPurDtId         = $rowspurdt[0];
				$vPurDtNetTotal   = $rowspurdt[1];
				$vPurDtNetTotalB1 = $rowspurdt[2];
				$vPurDtNetTotalB2 = $rowspurdt[3];
				$vPurDtQty    = $rowspurdt[4];
				$vPurDtChgAmt   = $rowspurdt[5];
				$vPurDtChgAmtB1 = $rowspurdt[6];
				$vPurDtChgAmtB2 = $rowspurdt[7];
				
				//Calculation For PurchaseDt Charges
				
				$vPurDtCharges   = ($vPurDtNetTotal   / $vPurNetTotal  ) * $vChgAmt;
				$vPurDtChargesB1 = ($vPurDtNetTotalB1 / $vPurNetTotalB1) * $vChgAmtB1;
				$vPurDtChargesB2 = ($vPurDtNetTotalB2 / $vPurNetTotalB2) * $vChgAmtB2;
		
			
				
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$vPurCharges   = $vPurCharges   + $vPurDtCharges;
					$vPurChargesB1 = $vPurChargesB1 + $vPurDtChargesB1;
					$vPurChargesB2 = $vPurChargesB2 + $vPurDtChargesB2;
				} else {
					$vPurVatCharges   = $vPurVatCharges   + $vPurDtCharges;
					$vPurVatChargesB1 = $vPurVatChargesB1 + $vPurDtChargesB1;
					$vPurVatChargesB2 = $vPurVatChargesB2 + $vPurDtChargesB2;
				}
				
				//Add the difference between total charges amount and the sum of distributed amount to the last record in purchasesdt
				// to avoid differences due to rounding
				if ($CurRow == $TotalRecords) {
					$vPurDtCharges   = $vPurDtCharges   + ($vChgAmt   - $vPurCharges - $vPurVatCharges);
					$vPurDtChargesB1 = $vPurDtChargesB1 + ($vChgAmtB1 - $vPurChargesB1 - $vPurVatChargesB1);
					$vPurDtChargesB2 = $vPurDtChargesB2 + ($vChgAmtB2 - $vPurChargesB2 - $vPurVatChargesB2);
					
					//ChargesIsVat False
					if ($rowcharges[7] == 0) {
						$vPurCharges   = $vChgAmt;
						$vPurChargesB1 = $vChgAmtB1;
						$vPurChargesB2 = $vChgAmtB2;
					} else {
						$vPurVatCharges   = $vChgAmt;
						$vPurVatChargesB1 = $vChgAmtB1;
						$vPurVatChargesB2 = $vChgAmtB2;
					}
				} 
				//echo $vPurDtCharges.'-'.$vPurDtChargesB1.'-'.$vPurDtChargesB2,'<br>';exit;
				
				//ChargesIsVat False
				if ($rowcharges[7] == 0) {
					$querypurdtupd =  " UPDATE temp_transferdt SET  ".
									  " transferdt_chargebase1 = ifNull(transferdt_chargebase1,0) + round($vPurDtChargesB1,$DecimalBase1), ".
									  " transferdt_chargebase2 = ifNull(transferdt_chargebase2,0) + round($vPurDtChargesB2,$DecimalBase2)  ".
									  " Where transferDt_ID = ".$vPurDtId;
				}
				else {
					$querypurdtupd =  " UPDATE temp_transferdt SET  ".
									  " transferdt_VATchargebase1 = ifNull(transferdt_VATchargebase1,0) + round($vPurDtChargesB1,$DecimalBase1), ".
									  " transferdt_VATchargebase2 = ifNull(transferdt_VATchargebase2,0) + round($vPurDtChargesB2,$DecimalBase1)  ".
									  " Where transferDt_ID = ".$vPurDtId;
				} 
				//echo $querypurdtupd;echo "<br>";
				if (!updateData($connection, $querypurdtupd, true))
					$error  = mysql_error(); 
			

			} //End Loop Fo PurchasesDt Table
		
			//Update Purchase Charges
			$querypurupd =  " UPDATE temp_transfer SET ".
							" amountBase1 = ifNull(amountBase1,0) + round($vPurChargesB1,$DecimalBase1), ".
							" amountBase2 = ifNull(amountBase2,0) + round($vPurChargesB2,$DecimalBase2),  ".
							" amountVATBase1 = ifNull(amountVATBase1,0) + $vPurVatChargesB1, ".
							" amountVATBase2 = ifNull(amountVATBase2,0) + $vPurVatChargesB2  ".
							" Where transfer_ID = ".$PPurId;
								
			if (!updateData($connection, $querypurupd, true))
				$error  = mysql_error(); 
		}	
		
	} //End Loop From TempCharges Table
		
	//echo 'error= '.$error; exit;
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalCharges: '.$error;
	
	Return $error;
}



function Create_PurchaseJv($PPurId, $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_PurchaseAutoJv(".$PPurId.", 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_PurchaseAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_PurchaseJv: '.$error;

	Return $error;
	

}

function mround($number, $precision=0) { 
    
    $precision = ($precision == 0 ? 1 : $precision);    
    $pow = pow(10, $precision); 
    
    $ceil = ceil($number * $pow)/$pow; 
    $floor = floor($number * $pow)/$pow; 
    
    $pow = pow(10, $precision+1); 
    
    $diffCeil     = $pow*($ceil-$number); 
    $diffFloor     = $pow*($number-$floor)+($number < 0 ? -1 : 1); 
    
    if($diffCeil >= $diffFloor) return $floor; 
    else return $ceil; 
} 

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	$result = selectData($connection, $query);
	//echo $query; exit;
	Return	$result[0];

}

function ConvertCurrencyRate($FromCurr, $ToCurr, $FromDate, $Rate1, $Rate2, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', $Rate1, $Rate2, '', '', ifNull($Amount,0)),0) From Dual ";//echo $query;echo "<br>";
	$result = selectData($connection, $query);
	
	Return	$result[0];

}

function Get_CostPrice($PItemCode, $PItemCurr, $PCostMethod, $PDate, $PCurrCode, $PCurBase1, $PCurBase2, $connection) {

	$ItemCost = 0;
			
	if ($PCostMethod == 1) {
		$query = "SELECT ifNull(GetLastValuesFunc('".$PCurBase1."', '".$PCurBase2."', '".$PItemCode."'),0) From Dual ";
		$result = selectData($connection, $query);
		//echo $query;
		$ItemCost = $result[0];
		$ItemCost = ConvertCurrency($PItemCurr, $PCurrCode, insertMySQLDate($PDate), $ItemCost, $connection);
	}
	else if ($PCostMethod == 0) {
		$query = "SELECT ifNull(MeanCostCur('".$PItemCode."', '".insertMySQLDate($PDate)."', 1, '".$PCurBase1."', '".$PCurrCode."'),0) From Dual ";
		$result = selectData($connection, $query);
		//echo $query;
		$ItemCost = $result[0];
	}

	Return	$ItemCost;
}

function Get_RawMaterialCost($PItemCode, $PDate, $PCurrCode, $connection) {

	$ItemCost = 0;
			
	$query = "SELECT ifNull(GetRawMaterialCost('".$PItemCode."', '".insertMySQLDate($PDate)."', '".$PCurrCode."'),0) From Dual ";
	$result = selectData($connection, $query);
	//echo $query;
	$ItemCost = $result[0];

	Return	$ItemCost;
}

function Create_AssembleJv($PPrdId, $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_AssembleAutoJv(".$PPrdId.", 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_AssembleAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_AssembleJv: '.$error;

	Return $error;
	

}


function Create_AdjustmentJv($PAdjId, $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_AdjustmentAutoJv(".$PAdjId.", 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_AdjustmentAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_AdjustmentJv: '.$error;

	Return $error;
	

}

function Create_ProductionJv($PPrdId, $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_ProductionAutoJv(".$PPrdId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) ";
	$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_ProductionAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_ProductionJv: '.$error;

	Return $error;
	

}

function Create_ChargesJv($PChgId, $DbName, $DbLabel, $UserAccount, $UserName, $PBelengsToGroup) {
	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_ChargesAutoJv(".$PChgId.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', $PBelengsToGroup, @id) ";
	$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_ChargesAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_ChargesJv: '.$error;

	Return $error;
	

}

?>
