<?php

session_start();
if($_SESSION['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($_SESSION['dbName'],$connection) or die("Could not find DB");

//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);
}
			
$Mode 		= $_GET["Mode"]; if ($Mode == ""){$Mode = $_POST["Mode"];}   
$ChgPurId 	= $_GET["ChgPurId"]; if ($ChgPurId == ""){$ChgPurId = $_POST["ChgPurId"];} 
$ChgAutoId	= $_GET["ChgAutoId"]; if ($ChgAutoId == ""){$ChgAutoId = $_POST["ChgAutoId"];} 

$txtLedgerNoDebit   		= $_GET["txtLedgerNoDebit"]; if ($txtLedgerNoDebit == ""){$txtLedgerNoDebit = $_POST["txtLedgerNoDebit"];} 
$txtLedgerNoCredit 			= $_GET["txtLedgerNoCredit"]; if ($txtLedgerNoCredit == ""){$txtLedgerNoCredit = $_POST["txtLedgerNoCredit"];} 
$txtChgIsVat 				= $_GET["txtChgIsVat"]; if ($txtChgIsVat == ""){$txtChgIsVat = $_POST["txtChgIsVat"];} 
$txtChgGenDebit    			= $_GET["txtChgGenDebit"]; if ($txtChgGenDebit == ""){$txtChgGenDebit = $_POST["txtChgGenDebit"];} 
$txtChgSubToCharge 			= $_GET["txtChgSubToCharge"]; if ($txtChgSubToCharge == ""){$txtChgSubToCharge = $_POST["txtChgSubToCharge"];} 
$txtpurchasecharges_remark 	= $_GET["txtpurchasecharges_remark"]; if ($txtpurchasecharges_remark == ""){$txtpurchasecharges_remark = $_POST["txtpurchasecharges_remark"];} 
$txtChgDistOption  			= $_GET["txtChgDistOption"]; if ($txtChgDistOption == ""){$txtChgDistOption = $_POST["txtChgDistOption"];} 
$txtChgCurrCode   			= $_GET["txtChgCurrCode"]; if ($txtChgCurrCode == ""){$txtChgCurrCode = $_POST["txtChgCurrCode"];} 
$txtChgAmount				= $_GET["txtChgAmount"]; if ($txtChgAmount == ""){$txtChgAmount = $_POST["txtChgAmount"];} 
$txtChargesCostcent_code	= $_GET["txtChargesCostcent_code"]; if ($txtChargesCostcent_code == ""){$txtChargesCostcent_code = $_POST["txtChargesCostcent_code"];} 
			

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

</head>
<body>
<form name='addcharges' method='post' action=''>
<input type='hidden' name='ChgAutoId' id='ChgAutoId' value='$ChgAutoId' size='10' maxlength='40'/>
<input type='hidden' name='ChgPurId' id='ChgPurId' value='$ChgPurId' size='10' maxlength='40'/>
<input type='hidden' name='Mode' id='Mode' value='$Mode' size='10' maxlength='40'/>		    
HERE;

if (($Mode == 'insert' || $Mode == 'edit') && $ChgPurId != ''){
	if (!isset($txtChgCurrCode))    $txtChgCurrCode = $base1;
		
		$query = " Select Purchase_ID, Currency_Code, Purchase_Rate, Purchase_RateBase1, Purchase_RateBase2, date_format(Purchase_Date,'%Y-%m-%d') ".
	         " From Temp_Purchases As Purchases ".
	         " Where Purchases.Purchase_ID = ".$ChgPurId." and (Currency_Code = '$txtChgCurrCode' or '$txtChgCurrCode' = '$base1' or '$txtChgCurrCode' = '$base2')";
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $numrows=mysql_num_rows($result);
	if($numrows >0){
	$rows=mysql_fetch_row($result);
	
	$rate_dt = $rows[2];
	$rate_dt2 = $rows[4];
	$vPurDate = $rows[5];
	if ($txtChgCurrCode == $base1) {
		$rate_dt1 = 1;
		$rate_dt = 1;
	}
	else $rate_dt1 = 0;
	
	if ($txtChgCurrCode == $base2) {
		$rate_dt2 = $rows[4];
		//$rate_dt = 1;
		$rate_dt =  $rows[4];
	}
	
	
	$txtChgAmountBase1    = ConvertCurrencyRate($txtChgCurrCode, $base1, $vPurDate, $rate_dt, $rate_dt1, $txtChgAmount, $connection);
	$txtChgAmountBase2    = ConvertCurrencyRate($txtChgCurrCode, $base2, $vPurDate, $rate_dt, $rate_dt2, $txtChgAmount, $connection); 
	
	} else{ 
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtChgCurrCode."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtChgCurrCode."' )";
		$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];	
		
		$txtChgAmountBase1 = ($txtChgAmount*$rate_dt)/$rate_dt1;
		$txtChgAmountBase2 = ($txtChgAmount*$rate_dt)/$rate_dt2;
	}

}
	
if ($Mode == 'insert' && $ChgPurId != '') {
	$ErrorExists = 0;
	$txtChargesCostcent_code = "".$txtChargesCostcent_code;
	
	if ($txtLedgerNoDebit != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNoDebit."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Debit Account.';
		}
	}
	if ($txtLedgerNoCredit != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNoCredit."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check Credit Account.';
		}
	}
	if ($txtChargesCostcent_code != '') {
		$sub_query = " Select Count(Costcent_code) From costcent ".
					 " Where Costcent_code = '".$txtChargesCostcent_code."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check Costcent Code.';
		}
	}
	
	if ($ErrorExists == 0){
	
		if (empty($txtChgIsVat))	    $txtChgIsVat = 0;
		if (empty($txtChgGenDebit))	    $txtChgGenDebit = 0;
		if (empty($txtChgSubToCharge))  $txtChgSubToCharge = 0;
			
	
		
		
		fbegin();
		$query = " INSERT INTO temp_purchasecharges (Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, ".
				 " Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charges_isSubjToCharge, purchasecharges_remark, ChargesCostcent_code, Logged_Code ) ".
				 " VALUES ($ChgPurId, '".$txtLedgerNoDebit."', '".$txtLedgerNoCredit."', '".$txtChgCurrCode."', $txtChgAmount, $txtChgAmountBase1, ".
				 " $txtChgAmountBase2, $txtChgDistOption, $txtChgIsVat, $txtChgGenDebit, $txtChgSubToCharge,'".ereg_replace("'", "\'", trim($txtpurchasecharges_remark))."', ".
				 " '".ereg_replace("'", "\'", trim($txtChargesCostcent_code))."', '".$_SESSION['useraccount']."' ) ";
		//echo $query; exit;
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
			
			$result = Distribute_TotalCharges($ChgPurId, $connection, $_SESSION['useraccount']);
		}else{
			$message  = mysql_error(); 
			frollback();
		}			
	}
}

else if ($Mode == 'edit' && $ChgAutoId != '' && $ChgPurId != '') {
	
	$ErrorExists = 0;
	
	if ($txtLedgerNoDebit != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNoDebit."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Debit Account.';
		}
	}
	if ($txtLedgerNoCredit != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNoCredit."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check Credit Account.';
		}
	}
	
	if ($ErrorExists == 0){
	
		if (empty($txtChgIsVat))		$txtChgIsVat = 0;
		if (empty($txtChgGenDebit))		$txtChgGenDebit = 0;
		if (empty($txtChgSubToCharge))	$txtChgSubToCharge = 0;
			
		
		fbegin();
		$query = " UPDATE temp_purchasecharges SET ".
				 " Ledger_NumberDebit = '".$txtLedgerNoDebit."', Ledger_NumberCredit = '".$txtLedgerNoCredit."',  ".
				 " Currency_code = '".$txtChgCurrCode."', Charges_Amount = $txtChgAmount, Charges_AmountBase1 = $txtChgAmountBase1, Charges_AmountBase2 = $txtChgAmountBase2, ".
				 " Charges_distoption = $txtChgDistOption, Charges_isVat = $txtChgIsVat, Charges_GenerateDebit = $txtChgGenDebit, Charges_isSubjToCharge =  $txtChgSubToCharge ".
				 " ,purchasecharges_remark= '".ereg_replace("'", "\'", trim($txtpurchasecharges_remark))."', ChargesCostcent_code =  '".ereg_replace("'", "\'", trim($txtChargesCostcent_code))."' ".
				 " WHERE Auto = ".$ChgAutoId.
				 " AND Purchase_id = ".$ChgPurId;
				 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
		//echo $query; exit;
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
			
			$result = Distribute_TotalCharges($ChgPurId, $connection, $_SESSION['useraccount']);
		}else{
			$message  = mysql_error(); 
			frollback();
		}			
	}
	
}

else if ($Mode == 'delete' && $ChgAutoId != '' && $ChgPurId != '') {
	fbegin();
	
	$query = " DELETE from temp_purchasecharges ".
	         " WHERE Auto = ".$ChgAutoId.
			 " AND Purchase_id = ".$ChgPurId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	
	$result=mysql_query($query,$connection);
		
	if ($result){
		fcommit();
		
		$result = Distribute_TotalCharges($ChgPurId, $connection, $_SESSION['useraccount']);
	}else{
		$message  = mysql_error(); 
		frollback();
	}			

}

else if ($Mode == 'loadfromaccount' && $ChgPurId != '') {
	$query = " SELECT Purchasecharges.Auto As Charges_Id, Purchasecharges.Purchase_id, Purchasecharges.Ledger_NumberDebit, Purchasecharges.Currency_code, ".
			 " Purchases.Costcent_code, Purchases.Purchase_Date  ".
			 " FROM Temp_Purchasecharges as Purchasecharges ".
			 " Inner Join Temp_Purchases as Purchases on Purchasecharges.Purchase_Id = Purchases.Purchase_Id  ".
			 " WHERE Purchasecharges.Purchase_id = ".$ChgPurId;

	$result=mysql_query($query,$connection) or die(mysql_error());		
	while($rows=mysql_fetch_array($result)){		 
		$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance ".
						" FROM journaldt  ".
						" Inner join journal on journal.journal_id = journaldt.journal_id ".
						" Left outer Join CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
						" where journaldt.ledger_number = '".$rows[2]."' ".
						" and CstJour.costcent_code = '".$rows[4]."' ".
						" and journal.journal_type != 'PI' ";
			//echo $querybalance; exit;			
		$resultbalance = selectData($connection, $querybalance);
		$vBalance = $resultbalance[0];
		if (empty($vBalance)) $vBalance = 0;
		
		$vChgAmount		 = 0;
		$vChgAmountBase1 = 0;
		$vChgAmountBase2 = 0;
		
		$vChgAmount		 = ConvertCurrency($base1, $rows[3], $rows[5], $vBalance, $connection);
		$vChgAmountBase1 = $vBalance;
		$vChgAmountBase2 = ConvertCurrency($base1, $base2, $rows[5], $vBalance, $connection);
		
		$sub_query = " UPDATE Temp_Purchasecharges SET ".
					 " Charges_Amount = $vChgAmount, Charges_AmountBase1 = $vChgAmountBase1, Charges_AmountBase2 = $vChgAmountBase2 ".
					 " WHERE Auto = ".$rows[0].
					 " AND Purchase_id = ".$ChgPurId;
		//echo $sub_query; exit;
		$sub_result=mysql_query($sub_query,$connection);
	}
	
	$result = Distribute_TotalCharges($ChgPurId, $connection, $_SESSION['useraccount']);

}


$message = ereg_replace(' ','%20',$message);
header ("Location: Form_PurchaseCharges.php?txtChgPurId=".$ChgPurId."&message=".$message);


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

HERE;

?>