<?php

session_start();

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

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

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


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

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2 from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


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


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='insertcharges' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SChgId' value='$SChgId'>
<input type='text' name='SChgDtId' value='$SChgDtId'>
<input type='text' name='SChgItemId' value='$SChgItemId'>

HERE;

$message='';

//Submit Record Mode

if ($mode == "submitrecord" || $mode == "loadcharges"){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if ($mode == "loadcharges") {
		$vChgDate         = $txtDate;
		$vChgRemark       = $txtRemark;
	} else {
		$vChgDate         = $PChgDate;
		$vChgRemark       = $PChgRemark;
	}
	
	
		
	//Insert Master Table
	if ($SChgId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$vChgId = get_nextsequence('Charges_Id','',$connection);
		fcommit();
			
		
		fbegin();
		$query = " INSERT INTO Temp_ChargesHD (Charges_Id, Charges_Reference, Charges_Date, Charges_Remark, Journal_Id, Journal_Type, Charges_Posted, ".
				 " Charges_BelongsToGroup, User_Account, Logged_Code ) ".
				 " VALUES ( ".$vChgId.", Null, '".insertMySQLDate($vChgDate)."', '".ereg_replace("'", "\'", trim($vChgRemark))."', Null, 'CH', 0, $FI_BelongsToGrp, ".
				 "          '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SChgId = $vChgId;
			$PChgId = $vChgId;
			fcommit();
			
		}else{
			$PChgId = "";
			$SChgId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Load Charges Details
	if ($SChgId != "" && $ErrorExists == 0 && $mode == "loadcharges"){
		$sub_query  = " Delete From Temp_ChargesDT Where Charges_Id = '".$SChgId."'";
		$sub_result = mysql_query($sub_query, $connection) or die(mysql_error());
		
		$sub_query = " Select Ledger_NumberDebit, Ledger_NumberCredit, Currency_Code,  Distribution_Method, Charges_isVat ".
					 " From PurchaseChargesSetup ";
	
		//echo $sub_query."<br>"; 
		$sub_result=mysql_query($sub_query, $connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
			fbegin();	
			$vChgDtId = get_nextsequence('ChargesDt_Id','',$connection);
			fcommit();
					
			$query = " INSERT INTO Temp_ChargesDT (ChargesDt_Id, Charges_Id, ChargesDt_DistOption, Currency_Code, ChargesDt_DebitAccount, ChargesDt_CreditAccount, ChargesDt_GenerateDebit, ChargesDt_isVat) ".
					 " VALUES (".$vChgDtId.", ".$SChgId.", ".$sub_rows[3].", '".$sub_rows[2]."', '".$sub_rows[0]."', '".$sub_rows[1]."', 0, '".$sub_rows[4]."' )";
			$result=mysql_query($query,$connection);
		
		}
	
	}
		
} 

else if ($mode == "distributecharges" && $SChgId != ""){

	$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];
	
	$message = DistributeCharges($SChgId, $base1, $base2, $rate_dt1, $rate_dt2, $connection);

}

else if ($mode == "editdetail" && $SChgId != "" && $SChgDtId != ""){
	$message  = '';
	
	$ErrorExists = 0;
	
	if(empty($txtGenDebit)) $txtGenDebit = 0;
	if(empty($txtIsVat))    $txtIsVat = 0;
	
						  
	$vDebitAcc    = $txtDebitAcc;
	$vCreditAcc   = $txtCreditAcc;
	$vCurrency    = $txtCurr;
	$vAmount      = $txtAmount;
	$vDistOption  = $txtOptions;
	$vGenDebit    = $txtGenDebit;
	$vIsVat       = $txtIsVat;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vCurrency."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vCurrency."' )";
	$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];		
	
			
	$vAmountB1 = ($vAmount*$rate_dt)/$rate_dt1;
	$vAmountB2 = ($vAmount*$rate_dt)/$rate_dt2;
	
	
	if ($SChgDtId != "" && $ErrorExists == 0){
		fbegin();
		$query = " UPDATE Temp_ChargesDt Set ".
				 " ChargesDt_DebitAccount = '".$vDebitAcc."', ".
				 " ChargesDt_CreditAccount = '".$vCreditAcc."', ".
				 " ChargesDt_DistOption = '".$vDistOption."', ".
				 " Currency_Code = '".$vCurrency."', ".
				 " ChargesDt_Total = ".$vAmount.", ".
				 " ChargesDt_TotalBase1 = ".$vAmountB1.", ".
				 " ChargesDt_TotalBase2 = ".$vAmountB2.", ".
				 " ChargesDt_GenerateDebit = $vGenDebit, ".
				 " ChargesDt_isVat = $vIsVat ".
				 " WHERE ChargesDt_Id = '".$SChgDtId."'";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			fcommit();
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
}


else if ($mode == "deletedetail" && $SChgId != "" && $SChgDtId != ""){
	$message  = '';
	
	fbegin();
	
	$query = " DELETE FROM Temp_ChargesDT ".
			 " WHERE ChargesDt_Id = '".$SChgDtId."'";
			
	if (!updateData($connection, $query, true)) {
		$message  = mysql_error();
		$ErrorExists = 1;
		frollback();
	}  
	else {
		fcommit();
	}

}


//Edit Charges Item 
else if ($mode == "edititem" && $SChgId != "" && $SChgItemId != ""){

	$ErrorExists = 0;
	
	if (empty($txtAmount))	 $txtAmount = 0;
	if (empty($txtVolume))   $txtVolume = 0;
	if (empty($txtPercent))  $txtPercent = 0;
		
	$vAmount   = $txtAmount;
	$vVolume   = $txtVolume;
	$vPercent  = $txtPercent;
	$vCurrCode = $txtCurr;
		
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vCurrCode."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vCurrCode."' )";
	$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];		
	
	$vAmountBase1 = ($vAmount*$rate_dt)/$rate_dt1;
	$vAmountBase2 = ($vAmount*$rate_dt)/$rate_dt2;
			
	$sub_query = " Select ifNull(Sum(ifNull(ChargesItems_Perc,0)),0) ".
				 " From Temp_ChargesItems ".
				 " Inner Join Temp_ChargesPurchases on Temp_ChargesPurchases.ChargesPurchases_Id = Temp_ChargesItems.ChargesPurchases_Id ".
				 " Where Temp_ChargesPurchases.Charges_Id = '".$SChgId."' ".
				 " And ChargesItems_Id != '".$SChgItemId."'";
	$sub_result = selectData($connection, $sub_query);
	$vTotalPerc = $sub_result[0] + $vPercent;
	
	if ($vTotalPerc > 100) {
		$ErrorExists = 1;
		$message = 'Total item charges percentage ('.$vTotalPerc.') should be less than or equal to 100.';	
	}
		
	if ($ErrorExists == 0) {
		fbegin();	
			
		$query = " UPDATE Temp_ChargesItems SET  ".
				 " ChargesItems_Volume = $vVolume, ChargesItems_Perc = $vPercent, ".
				 " ChargesItems_Amount = $vAmount, ChargesItems_AmountB1 = $vAmountBase1, ChargesItems_AmountB2 = $vAmountBase2 ".
				 " Where ChargesItems_Id = '".$SChgItemId."'";
								 
		//echo $query; exit;
		$result=mysql_query($query,$connection);
		if ($result){
			fcommit();
				
		}else{
			$message  = mysql_error(); 
			frollback();
		}				
	}
}


//Delete Raw Materials
else if ($mode == "deleteitem" && $SChgId != "" && $SChgItemId != ""){

	$AllowDelete = 1;
	$message  = '';
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		$ErrorExists    = 0;

		
		$querypack = " SELECT PurchasesDt.Item_CodePacked, PurchasesDt.Item_Code, ChargesItems.ChargesPurchases_Id ".
					 " FROM Temp_ChargesItems As ChargesItems ".
					 " Inner Join PurchasesDt on PurchasesDt.PurchaseDt_Id = ChargesItems.PurchaseDt_Id ".
					 " Where ChargesItems.ChargesItems_Id = '".$SChgItemId."'";
								   
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		$vChgPurID = $rowspack[2];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
			
			// Delete From TempChargesItems For Selected Record
			$query = " DELETE FROM Temp_ChargesItems ".
					 " WHERE ChargesItems_Id = '".$SChgItemId."'";
					 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select ChargesItems.ChargesItems_Id, PurchasesDt.Item_CodePacked, PurchasesDt.Item_Code  ".
					   " From Temp_ChargesItems As ChargesItems  ".
					   " Inner Join PurchasesDt on PurchasesDt.PurchaseDt_Id = ChargesItems.PurchaseDt_Id ".
					   " Inner Join Temp_ChargesPurchases As ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
					   " Where ChargesPurchases.Charges_Id = '".$SChgId."' ".
					   " And PurchasesDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
					
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vChgItemId =	$rowsdt[0];
					
				// Delete From TempChargesItems For Selected Record
				$query = " DELETE FROM Temp_ChargesItems ".
						 " WHERE ChargesItems_Id = '".$vChgItemId."'";
						 
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 && $vChgPurID != ""){ 
			//Check If All Items Are Deleted Then Delete The Record From Temp_ChargesPurchases
			
			$sub_query = " Select Count(*) From Temp_ChargesItems Where ChargesPurchases_Id = $vChgPurID ";
			//echo $sub_query; exit;
			$sub_result = selectData($connection, $sub_query);
			
			if ($sub_result[0] == 0) {
				$sub_query1 = " Delete From Temp_ChargesPurchases Where ChargesPurchases_Id = $vChgPurID ";
				$sub_result1 = mysql_query($sub_query1,$connection);
			}

		} // End If No Error Exists 
		
	
	} // End If No Constraints Found On Delete

	
}


else if ($mainmode == "loadpurchases" && $SChgId != "" && $SChgDtId != ""){

	$ErrorExists = 0;
	$InsertAllow = 1;

	
	$sub_query = " Select Distinct Purchase_Id From PurchasesDt ".
				 " Where PurchaseDt_ID In (".$SChgDtId.") ";
				 
	//echo $sub_query; exit;			 
	$sub_result=mysql_query($sub_query, $connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){
	
		$vPurchasesID = $sub_rows[0];
		
		$sub_query1 = " Select Distinct ChargesPurchases_Id From Temp_ChargesPurchases ".
					  " Where Purchase_Id = '".$vPurchasesID."' ".
					  " And Charges_Id = '".$SChgId."' ";
					 
		$sub_result1 = selectData($connection, $sub_query1);		 
		if ($sub_result1[0]	== "") {
			fbegin();	
			$vChgPurId = get_nextsequence('ChargesPurchases_Id','',$connection);
			fcommit();
				
			
			
			$query = " INSERT INTO Temp_ChargesPurchases (ChargesPurchases_Id, Charges_Id, Purchase_Id, ChargesPurchases_Closed, Logged_Code ) ".
					 " VALUES ( ".$vChgPurId.", ".$SChgId.", ".$vPurchasesID.", 0, '".$HTTP_SESSION_VARS['useraccount']."' )";
			
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
			
			if (!($result)) $ErrorExists = 1;
		} else {
			$vChgPurId = $sub_result1[0];
		}	
		
		if ($ErrorExists == 0 && $vPurchasesID != ""){
			$sub_query2 = " Select Purchase_Id, PurchaseDt_Id, Currency_Code, Purchasedt_ItemAccount ".
						  " From PurchasesDt ".
						  " Where PurchaseDt_ID In (".$SChgDtId.") ".
						  " And Purchase_ID = '".$vPurchasesID."'";
						
			$sub_result2=mysql_query($sub_query2, $connection) or die(mysql_error());
			while($sub_rows2=mysql_fetch_array($sub_result2)){
				fbegin();	
				$vChgItemsId = get_nextsequence('ChargesItems_Id','',$connection);
				fcommit();
		
				$query1 = " INSERT INTO Temp_ChargesItems (ChargesItems_Id, ChargesPurchases_Id, Purchase_Id, PurchaseDt_Id, ChargesItems_Volume, Currency_Code, ChargesItems_Perc, ".
						  " ChargesItems_ItemAccount, Logged_Code ) ".
						  " VALUES ( ".$vChgItemsId.", ".$vChgPurId.", ".$vPurchasesID.", ".$sub_rows2[1].", Null, '".$sub_rows2[2]."', 0, '".$sub_rows2[3]."', '".$HTTP_SESSION_VARS['useraccount']."' )";
		
				$result1=mysql_query($query1,$connection);
				
			}
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
}
	

//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SChgId != ''){

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Charges Is Posted
	$sub_query = "SELECT ifNull(Charges_Posted,0) As ChargesPosted FROM ChargesHD WHERE Charges_ID = '".$SChgId."'";
	$sub_result = selectData($connection, $sub_query);
	$ChgPosted = $sub_result[0];
	
	if ($ChgPosted == 1 ){
		$message  = 'Delete not allowed, transaction posted.';
		$AllowDelete = 0;
	}
	



	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
	    $sub_query = " Select Journal_Id From ChargesHD Where Charges_ID = '".$SChgId."'";
		$sub_result = selectData($connection, $sub_query);
		$vChgJournalID = $sub_result[0];
		if(empty($vChgJournalID)) $vChgJournalID = -1;
		
		
		$query = " DELETE FROM ChargesItemsDt ".
				 " WHERE ChargesItems_Id In (Select ChargesItems_Id From ChargesItems Where ChargesPurchases_Id In (Select ChargesPurchases_Id From ChargesPurchases Where Charges_Id = '".$SChgId."' )) ";
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
			
		$query = " DELETE FROM ChargesItems ".
				 " WHERE ChargesPurchases_Id In (Select ChargesPurchases_Id From ChargesPurchases Where Charges_Id = '".$SChgId."' ) ";
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		
		$query = " DELETE FROM ChargesPurchases ".
				 " WHERE Charges_Id = '".$SChgId."'";
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  
		
		$query = " DELETE FROM ChargesDT ".
				 " WHERE Charges_Id = '".$SChgId."'";
		if (!updateData($connection, $query, true))
			$message  = mysql_error();  

		$query = " DELETE FROM ChargesHD ".
				 " WHERE Charges_Id = '".$SChgId."'";
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 	
		
		if ($vChgJournalID != -1) {
				
			$query = " DELETE FROM Journal ".
					 " WHERE Journal_Id = ".$vChgJournalID;
					
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	

		}
		
	}
	
}

//Delete Record Mode From Temp Tables
else if ($mode == "" && $mainmode == "deletepending" && $SChgId != ''){
	
	// Delete From Temp Tables For Selected Record
	$query = " DELETE FROM Temp_ChargesItemsDt ".
			 " WHERE ChargesItems_Id In (Select ChargesItems_Id From Temp_ChargesItems Where ChargesPurchases_Id In (Select ChargesPurchases_Id From Temp_ChargesPurchases Where Charges_Id = '".$SChgId."' )) ";
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
		
	$query = " DELETE FROM Temp_ChargesItems ".
			 " WHERE ChargesPurchases_Id In (Select ChargesPurchases_Id From Temp_ChargesPurchases Where Charges_Id = '".$SChgId."' ) ";
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
	
	$query = " DELETE FROM Temp_ChargesPurchases ".
			 " WHERE Charges_Id = '".$SChgId."'";
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error(); 
	  
	
	$query = " DELETE FROM Temp_ChargesDT ".
			 " WHERE Charges_Id = '".$SChgId."'";
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error();   

		
	$query = " DELETE FROM Temp_ChargesHD ".
			 " WHERE Charges_Id = '".$SChgId."'";
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error();   
		

}

//Search Mode	
else if($mainmode == "search" && $SChgId != ''){
	
	$ErrorExists = 0;
	$message  = '';
	

	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_ChargesHD (Charges_ID, Charges_Reference, Charges_Date, Charges_Remark, Journal_Type, Journal_Id, ".
			 " Charges_Posted, Charges_BelongsToGroup, User_Account, Logged_Code ) ".
			 " SELECT Charges_ID, Charges_Reference, Charges_Date, Charges_Remark, Journal_Type, Journal_Id, ".
			 " Charges_Posted, Charges_BelongsToGroup, User_Account, '".$HTTP_SESSION_VARS['useraccount']."' ".
			 " FROM ChargesHD ".
			 " WHERE Charges_Id = '".$SChgId."'";
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}
			
	//echo $message.$query; exit;				 
		
	if ($ErrorExists == 0) {
	
		$query = " INSERT INTO Temp_ChargesDT (ChargesDt_Id, Charges_Id, ChargesDt_DistOption, ChargesDt_DebitAccount, ChargesDt_CreditAccount,  ".
				 " Currency_Code, ChargesDt_Total, ChargesDt_TotalBase1, ChargesDt_TotalBase2, ChargesDt_GenerateDebit, ChargesDt_isVat) ".
				 " SELECT ChargesDt_Id, Charges_Id, ChargesDt_DistOption, ChargesDt_DebitAccount, ChargesDt_CreditAccount,  ".
				 " Currency_Code, ChargesDt_Total, ChargesDt_TotalBase1, ChargesDt_TotalBase2, ChargesDt_GenerateDebit, ChargesDt_isVat ".
				 " FROM ChargesDT ".
				 " WHERE Charges_Id = '".$SChgId."'";
				 
		if (!updateData($connection, $query, true))
			$message  = mysql_error();
			
		
		$query = " INSERT INTO Temp_ChargesPurchases (ChargesPurchases_Id, Charges_Id, Purchase_Id, ChargesPurchases_Closed, Logged_Code ) ".
				 " SELECT ChargesPurchases_Id, Charges_Id, Purchase_Id, ChargesPurchases_Closed, '".$HTTP_SESSION_VARS['useraccount']."'  ".
				 " FROM ChargesPurchases ".
				 " WHERE Charges_Id = '".$SChgId."'";
		
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 


		$query = " INSERT INTO Temp_ChargesItems (ChargesItems_Id, ChargesPurchases_Id, Purchase_Id, PurchaseDt_Id, ChargesItems_Volume, ".
				 " Currency_Code, ChargesItems_Amount, ChargesItems_AmountB1, ChargesItems_AmountB2, ChargesItems_Perc, ChargesItems_ItemAccount, ".
				 " Logged_Code ) ".
				 " SELECT ChargesItems_Id, ChargesItems.ChargesPurchases_Id, ChargesItems.Purchase_Id, PurchaseDt_Id, ChargesItems_Volume, ".
				 " Currency_Code, ChargesItems_Amount, ChargesItems_AmountB1, ChargesItems_AmountB2, ChargesItems_Perc, ChargesItems_ItemAccount, ".
				 " '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " FROM ChargesItems ".
				 " Inner Join ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
				 " WHERE ChargesPurchases.Charges_Id = '".$SChgId."' ";
		
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 


		$query = " INSERT INTO Temp_ChargesItemsDt (ChargesItemsDt_Id, ChargesItems_Id, ChargesItemsDt_DebitAccount, ChargesItemsDt_CreditAccount, ".
				 " Currency_Code, ChargesItemsDt_Amount, ChargesItemsDt_AmountB1, ChargesItemsDt_AmountB2) ".
				 " SELECT ChargesItemsDt_Id, ChargesItemsDt.ChargesItems_Id, ChargesItemsDt_DebitAccount, ChargesItemsDt_CreditAccount, ".
				 " ChargesItemsDt.Currency_Code, ChargesItemsDt_Amount, ChargesItemsDt_AmountB1, ChargesItemsDt_AmountB2 ".
				 " FROM ChargesItemsDt ".
				 " Inner Join ChargesItems on ChargesItemsDt.ChargesItems_Id = ChargesItems.ChargesItems_Id ".
				 " Inner Join ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
				 " WHERE ChargesPurchases.Charges_Id = '".$SChgId."' ";
	
		if (!updateData($connection, $query, true))
			$message  = mysql_error();	

		  
	}  
	
	
}




//Post Mode	
else if($mode == "post" && $SChgId != ''){  

	$vChgDate    = $txtDate;
	$vChgRemark  = $txtRemark;
	
	
    $SaveAllow   = 1;
	$ErrorExists = 0;
	
	//Redistribute Charges Before Saving
	$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];
		
	$message = DistributeCharges($SChgId, $base1, $base2, $rate_dt1, $rate_dt2, $connection);
		
		
	/*$sub_query = " Select Count(*) ".
				 " From Temp_ChargesDT ".
				 " Where ifNull(ChargesDt_TotalBase1,0) != 0 ".
				 " And ifNull(ChargesDt_DistOption,1) != 5  ".
				 " And Charges_Id = '".$SChgId."'";
	$sub_result = selectData($connection, $sub_query);			 
	if ($sub_result[0] == 0) {
		$ErrorExists = 1;
		$message = 'Save not allowed. Please fill in Charges Amount(s).';	
	}*/
	
	if ($ErrorExists == 0) {
		
		//Check For Each ChargesDtAmount Should Be Equal To Sum Of All ItemsChargesDt Amount
		$sub_query = " Select ChargesDt_DebitAccount, ChargesDt_CreditAccount, ChargesDt_DistOption, ifNull(ChargesDt_TotalBase1,0) ".
					 " From Temp_ChargesDT ".
					 " Where ifNull(ChargesDt_TotalBase1,0) != 0 ".
					 " And ifNull(ChargesDt_DistOption,1) != 5  ".
					 " And Charges_Id = '".$SChgId."'";
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());			  
		while($sub_row=mysql_fetch_array($sub_result)){
			$vChargesDtDebit  = $sub_row[0];
			$vChargesDtCredit = $sub_row[1];
			$vChargesDtTotal  = $sub_row[3];
			
			$sub_query1 = " Select Sum(ifNull(ChargesItemsDt_AmountB1,0)) ".
						  " From Temp_ChargesItemsDt As ChargesItemsDt ".
						  " Inner Join Temp_ChargesItems As ChargesItems on ChargesItems.ChargesItems_Id = ChargesItemsDt.ChargesItems_Id ".
						  " Inner Join Temp_ChargesPurchases As ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
						  " Where ChargesPurchases.Charges_Id = '".$SChgId."' ".
						  " And ChargesItemsDt_DebitAccount = '".$vChargesDtDebit."' ".
						  " And ChargesItemsDt_CreditAccount = '".$vChargesDtCredit."' ";
						 
			$sub_result1 = selectData($connection, $sub_query1);
			$vChargesItemsDtAmount = $sub_result1[0];	
			
			if (Round($vChargesItemsDtAmount,0) != Round($vChargesDtTotal,0)) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Distributed Charges.';	
				
				break;
			}
		}
				
		
		//Check For Each ChargesDtAmount Should Be Equal To Sum Of All ItemsCharges Amount If Option Detail Amount
		$sub_query = " Select ChargesDt_DebitAccount, ChargesDt_CreditAccount, ChargesDt_DistOption, ifNull(ChargesDt_TotalBase1,0) ".
					 " From Temp_ChargesDT ".
					 " Where ifNull(ChargesDt_TotalBase1,0) != 0 ".
					 " And ifNull(ChargesDt_DistOption,1) = 5  ".
					 " And Charges_Id = '".$SChgId."'";
					 
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());			  
		while($sub_row=mysql_fetch_array($sub_result)){
			$vChargesDtDebit  = $sub_row[0];
			$vChargesDtCredit = $sub_row[1];
			$vChargesDtTotal  = $sub_row[3];
			
			$sub_query1 = " Select Sum(ifNull(ChargesItems_AmountB1,0)), Sum(ifNull(ChargesItemsDt_AmountB1,0)) ".
						  " From Temp_ChargesItemsDt As ChargesItemsDt ".
						  " Inner Join Temp_ChargesItems As ChargesItems on ChargesItems.ChargesItems_Id = ChargesItemsDt.ChargesItems_Id ".
						  " Inner Join Temp_ChargesPurchases As ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
						  " Where ChargesPurchases.Charges_Id = '".$SChgId."' ".
						  " And ChargesItemsDt_DebitAccount = '".$vChargesDtDebit."' ".
						  " And ChargesItemsDt_CreditAccount = '".$vChargesDtCredit."' ";
						 
			$sub_result1 = selectData($connection, $sub_query1);
			$vChargesItemsAmount   = $sub_result1[0];
			$vChargesItemsDtAmount = $sub_result1[1];
			
			if ((Round($vChargesItemsAmount,0) != Round($vChargesDtTotal,0)) || (Round($vChargesItemsAmount,0) != Round($vChargesItemsDtAmount,0))) {
				$ErrorExists = 1;
				$message = 'Save not allowed. Please check for Distributed Charges option (Detailed Amount).';	
				
				break;
			}
		}
		
		//Check User Access For Date Modification/ Lock Period
		$MainCompanyName=explode('_',$HTTP_SESSION_VARS['dbName']);

		$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
					" From ".$HTTP_SESSION_VARS['dbLabel'].".ListUserDir  ".
					" Where Usercode='".$HTTP_SESSION_VARS['useraccount']."' ".
					" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
					" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
					  
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		$rowsperiod = mysql_num_rows($sub_result);

		while($sub_rows=mysql_fetch_array($sub_result)){
			extract($sub_rows);
		}	
		
		$ExceedLockPeriod = 0;
		if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
			if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($vPrdDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
			if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($vPrdDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
		}
		//echo $sub_query;exit;
	}

	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
	
		$query = " UPDATE Temp_ChargesHD SET ".
				 " Charges_Date = '".insertMySQLDate($vChgDate)."' , ".
				 " Charges_Remark = '".ereg_replace("'", "\'", trim($vChgRemark))."' ".
				 " WHERE Charges_ID = '".$SChgId."'";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			
			$query = "Select Count(*) From Temp_ChargesHD where Charges_ID = '".$SChgId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
				
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempCharges('".$SMode."', ".$SChgId.", '".$HTTP_SESSION_VARS['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
					
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT Charges_Reference FROM ChargesHD WHERE Charges_ID = $SChgId ";
					$result  = selectData($connection, $query);
					$vChgRef = $result[0];
					
								
					if (($vChgRef == '') ){
						//($vOldProjCode != $vProjectCode && $Module_ReferenceByProject == 1) ||
						//($vOldCostCentCode != $vCostCentCode && $Module_ReferenceByCostcenter == 1)){
							
						//if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						//else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						//else $vProjCostCent = '';
							
						fbegin();
						$vChgRef = get_nextsequence('Charges_Reference',$vProjCostCent,$connection);	
						fcommit();
							
						$query = " UPDATE ChargesHD SET ".
								 " Charges_Reference = $vChgRef ".
								 " WHERE Charges_ID = $SChgId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
					}

					if ($Module_PostToJournal == 1)	
						$message = Create_ChargesJv($SChgId, $HTTP_SESSION_VARS['dbName'], $HTTP_SESSION_VARS['dbLabel'], $HTTP_SESSION_VARS['useraccount'], $HTTP_SESSION_VARS['username'], $FI_BelongsToGrp); 
						
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempCharges Function'; 
					frollback();
				}
			
			}
			
		} else{
			$message  = mysql_error(); 
			frollback();
		}	
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllow == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';			
			
		frollback();
	}	
}


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



if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Charges.php?actionmode=".$mode."&mainaction=".$mainmode."&PrChgId=".$SChgId."&PrChgRef=".$vChgRef."&message=".$message);
	else
		header ("Location: ./Form_Charges.php?actionmode=submitrecord&mainaction=".$mainmode."&txtChgId=".$SChgId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_ChargesSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_ChargesSearchPending.php");
else if ($mode == "deletedetail")		
	header ("Location: ./Form_Charges.php?actionmode=".$mode."&mainaction=".$mainmode."&txtChgId=".$SChgId."&message=".$message);	
else if ($mode == "editdetail")		
	header ("Location: ./Form_ChargesDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PChgId=".$SChgId."&PChgDtId=".$SChgDtId."&message=".$message);
else if ($mode == "edititem")		
	header ("Location: ./Form_ChargesItems.php?actionmode=".$mode."&mainaction=".$mainmode."&PChgId=".$SChgId."&PChgItemId=".$SChgItemId."&message=".$message);
else if ($mode == "deleteitem")		
	header ("Location: ./Form_Charges.php?actionmode=".$mode."&mainaction=".$mainmode."&txtChgId=".$SChgId."&message=".$message);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_ChargesSearch.php?PMode=1");	
else if ($mode == "loadcharges" )		
	header ("Location: ./Form_Charges.php?actionmode=".$mode."&mainaction=".$mainmode."&txtChgId=".$SChgId."&message=".$message);	
else if ($mode == "" && $mainmode == "loadpurchases" )			
	header ("Location: ./Form_Charges_LoadPurchases.php?PMode=1&actionmode=".$mode."&mainaction=".$mainmode."&PChgId=".$SChgId."&message=".$message);
else if ($mode == "distributecharges" )		
	header ("Location: ./Form_Charges.php?actionmode=".$mode."&mainaction=".$mainmode."&txtChgId=".$SChgId."&message=".$message);	


function DistributeCharges($PId, $PBase1, $PBase2, $PRate1, $PRate2, $connection) {
	
	$query = " DELETE FROM Temp_ChargesItemsDt ".
			 " WHERE ChargesItems_Id In (Select ChargesItems_Id From Temp_ChargesItems Where ChargesPurchases_Id In (Select ChargesPurchases_Id From Temp_ChargesPurchases Where Charges_Id = '".$PId."' )) ";
			
	if (!updateData($connection, $query, true))
		$error  = mysql_error(); 
			

			
			
	$querycharges = " Select ChargesDt_Id, ChargesDt_DebitAccount, ChargesDt_CreditAccount, Currency_Code, ifNull(ChargesDt_Total,0), ".
					" ifNull(ChargesDt_TotalBase1,0), ifNull(ChargesDt_TotalBase2,0), ChargesDt_DistOption ".
					" From Temp_ChargesDT ".
					" Where Charges_ID = '".$PId."'";

	$resultcharges=mysql_query($querycharges,$connection) or die(mysql_error());
	
	
	// Loop From TempChargesDT Table
	while($rowcharges=mysql_fetch_array($resultcharges)){
	
		$vPurTotalAmt    = 0;
		$vPurTotalAmtB1  = 0;
		$vPurTotalAmtB2  = 0;
		$vPurTotalQty 	 = 0;
		$vPurTotalVolume = 0;
		
		$vChgDtID     = $rowcharges[0];
		$vChgDebit    = $rowcharges[1];
		$vChgCredit   = $rowcharges[2];
		$vChgCurr     = $rowcharges[3];
		$vChgAmt      = $rowcharges[4];
		$vChgAmtB1    = $rowcharges[5];
		$vChgAmtB2    = $rowcharges[6];
		$vDistOption  = $rowcharges[7];
		
		if ($vDistOption == 5) {
			$vChgAmt      = 0;
			$vChgAmtB1    = 0;
			$vChgAmtB2    = 0;
		}
		
		// Charges Amount Should Not Be Zero
		if ((($vDistOption == 1 || $vDistOption == 2 || $vDistOption == 3 || $vDistOption == 4) && $vChgAmt > 0) || 
			 ($vDistOption == 5 && 1 == 1)){
		
			$sub_query = " Select Sum((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountAmount,0)) As TotalAmount, ".
						 " Sum((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_PriceBase1,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountBase1,0)) As TotalAmountB1, ".
						 " Sum((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_PriceBase2,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountBase2,0)) As TotalAmountB1, ".
						 " Sum(ifNull(PurchasesDt.PurchaseDt_Quantity,0)) As TotalQuantity, Sum(ifNull(ChargesItems.ChargesItems_Volume,0)) As TotalVolume ".
						 " From Temp_ChargesItems As ChargesItems  ".
						 " Inner Join Temp_ChargesPurchases As ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
						 " Inner Join PurchasesDt on PurchasesDt.PurchaseDt_Id = ChargesItems.PurchaseDt_Id ".
						 " Where ChargesPurchases.Charges_ID = '".$PId."' ";
			
			//echo $sub_query;exit;
			$sub_result = selectData($connection, $sub_query);
			
			$vPurTotalAmt    = $sub_result[0];
			$vPurTotalAmtB1  = $sub_result[1];
			$vPurTotalAmtB2  = $sub_result[2];
			$vPurTotalQty 	 = $sub_result[3];
			$vPurTotalVolume = $sub_result[4];
			
			
			$sub_query1 = " Select PurchasesDt.PurchaseDt_ID, PurchasesDt.Currency_Code, ".
						  " ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_Price,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountAmount,0)) As TotalAmount, ".
						  " ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_PriceBase1,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountBase1,0)) As TotalAmountB1, ".
						  " ((ifNull(PurchaseDt_Quantity,0)*ifNull(PurchaseDt_PriceBase2,0)*(1 - ifNull(PurchaseDt_DiscountPer,0)/100)) - ifNull(PurchaseDt_DiscountBase2,0)) As TotalAmountB1, ".
						  " ifNull(PurchasesDt.PurchaseDt_Quantity,0) As TotalQuantity, ifNull(ChargesItems.ChargesItems_Volume,0) As TotalVolume, ifNull(ChargesItems.ChargesItems_Perc,0) As TotalPerc, ".
						  " ifNull(ChargesItems.ChargesItems_Amount,0) As TotalChgAmt, ifNull(ChargesItems.ChargesItems_AmountB1,0) As TotalChgAmtB1, ifNull(ChargesItems.ChargesItems_AmountB2,0) As TotalChgAmtB2, ".
						  " ChargesItems.ChargesItems_Id  ".
						  " From Temp_ChargesItems As ChargesItems  ".
						  " Inner Join Temp_ChargesPurchases As ChargesPurchases on ChargesPurchases.ChargesPurchases_Id = ChargesItems.ChargesPurchases_Id ".
						  " Inner Join PurchasesDt on PurchasesDt.PurchaseDt_Id = ChargesItems.PurchaseDt_Id ".
						  " Where ChargesPurchases.Charges_ID = '".$PId."' ";
						  
			//echo $sub_query1; exit;
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());
			$TotalRecords = mysql_num_rows($sub_result1); 
			$CurRow = 0; // Count For Current Row In Loop Of PurchasesDt Table
			while($sub_rows1=mysql_fetch_array($sub_result1)){
				$CurRow = $CurRow + 1;
				
				$vPurDtId         = '';
				$vPurDtNetTotal   = 0;
				$vPurDtNetTotalB1 = 0;
				$vPurDtNetTotalB2 = 0;
				$vPurDtChgPerc	  = 0;
				$vPurDtQty 	      = 0;
				$vPurDtVolume     = 0;
				
				$vPurDtChargesB1  = 0;
				$vPurDtChargesB2  = 0;
				
				$vPurDtId         = $sub_rows1[0];
				$vPurDtCurr       = $sub_rows1[1];
				$vPurDtNetTotal   = $sub_rows1[2];
				$vPurDtNetTotalB1 = $sub_rows1[3];
				$vPurDtNetTotalB2 = $sub_rows1[4];
				$vPurDtQty  	  = $sub_rows1[5];
				$vPurDtVolume	  = $sub_rows1[6];
				$vPurDtChgPer     = $sub_rows1[7];
				$vPurDtChgAmt     = $sub_rows1[8];
				$vPurDtChgAmtB1   = $sub_rows1[9];
				$vPurDtChgAmtB2   = $sub_rows1[10];
				$vChgItemsId      = $sub_rows1[11];
				
				//Calculation For PurchaseDt Charges
				if ($vDistOption == 1) {
					//$vPurDtCharges   = ($vPurDtNetTotal   / $vPurTotalAmt  ) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtNetTotalB1 / $vPurTotalAmtB1) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtNetTotalB2 / $vPurTotalAmtB2) * $vChgAmtB2;
				}
				else if ($vDistOption == 2)
				{ 
					//$vPurDtCharges   = ($vPurDtQty / $vPurTotalQty) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtQty / $vPurTotalQty) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtQty / $vPurTotalQty) * $vChgAmtB2;
				}
				else if ($vDistOption == 4 && $vPurTotalVolume > 0)
				{
					//$vPurDtCharges   = ($vPurDtVolume / $vPurTotalVolume) * $vChgAmt;
					$vPurDtChargesB1 = ($vPurDtVolume / 100) * $vChgAmtB1;
					$vPurDtChargesB2 = ($vPurDtVolume / 100) * $vChgAmtB2;
				}
				else if ($vDistOption == 3 && $vPurDtChgPer != 0)
				{ 
					//$vPurDtCharges   = (($vPurDtNetTotal   * $vPurDtChgPer) / 100);
					$vPurDtChargesB1 = (($vChgAmtB1 * $vPurDtChgPer) / 100);
					$vPurDtChargesB2 = (($vChgAmtB2 * $vPurDtChgPer) / 100);
					
					//$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					//$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					//$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				else if ($vDistOption == 5 && $vPurDtChgAmtB1 != 0)
				{ 
					//$vPurDtCharges   = $vPurDtChgAmt;
					$vPurDtChargesB1 = $vPurDtChgAmtB1;
					$vPurDtChargesB2 = $vPurDtChgAmtB2;
					
					//$vChgAmt   = $vChgAmt   + $vPurDtCharges;
					$vChgAmtB1 = $vChgAmtB1 + $vPurDtChargesB1;
					$vChgAmtB2 = $vChgAmtB2 + $vPurDtChargesB2;
				}
				
			
				if ($vPurDtChargesB1 != "") {
					fbegin();	
					$vChgItemDtId = get_nextsequence('ChargesItemsDt_Id','',$connection);
					fcommit();
					
					$query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPurDtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPurDtCurr."' )";
					$result = selectData($connection, $query);
					$PRate  = $result[0];
					
					$vPurDtCharges = ($vPurDtChargesB1*$PRate1)/$PRate;
				
					$sub_query3 = " Insert Into Temp_ChargesItemsDt (ChargesItemsDt_Id, ChargesItems_Id, ChargesItemsDt_DebitAccount, ChargesItemsDt_CreditAccount, ".
								  " Currency_Code, ChargesItemsDt_Amount, ChargesItemsDt_AmountB1, ChargesItemsDt_AmountB2)  ".
								  " Values (".$vChgItemDtId.", ".$vChgItemsId.", '".$vChgDebit."', '".$vChgCredit."', '".$vPurDtCurr."', $vPurDtCharges, $vPurDtChargesB1, $vPurDtChargesB2 )";
					//echo $sub_query3; exit;
					$sub_result3 = mysql_query($sub_query3,$connection);
				}
				
			} //End Loop For PurchasesDt Table
		
	
			
			if ($vDistOption == 5) {
				$query  = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vChgCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vChgCurr."' )";
				$result = selectData($connection, $query);
				$PRate  = $result[0];
					
				$vChgAmt = ($vChgAmtB1*$PRate1)/$PRate;
					
				//Update Charges Table
				$sub_query4 = " UPDATE Temp_ChargesDT SET ChargesDt_Total = $vChgAmt, ".
							  " ChargesDt_TotalBase1 = $vChgAmtB1, ChargesDt_TotalBase2 = $vChgAmtB2  ".
							  " Where Charges_Id = '".$PId."' ".
							  " And ChargesDt_Id = '".$vChgDtID."'";
										 
				if (!updateData($connection, $sub_query4, true))
					$error  = mysql_error(); 
						
						
			}
			
			
		}		
	} //End Loop From TempChargesDT Table
		
	//echo 'error= '.$error; exit;
	if ($error != '')
	   $error = 'Error In Function DistributeCharges: '.$error;
	
	Return $error;
}





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

HERE;


?>