<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_IMINQ';
$path_to_root = "../../..";

include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/allocation_cart.inc");
include_once($path_to_root . "/includes/session.inc");


include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/kvcodes.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/gl_db.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/gl_ui.inc");
add_access_extensions();
global $payment_person_types;
if(!defined('PT_BKTRANS'))
		define('PT_BKTRANS',count_array($payment_person_types)+1);
if(!defined('PT_JOUENTRY'))
		define('PT_JOUENTRY',count_array($payment_person_types)+2);
$js = "";

if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(1000, 500);
//add_js_file('payalloc.js');
$js .=" 
function kv_allocate_all(doc){
	var amount = get_amount('amount'+doc);
	var unallocated = get_amount('un_allocated'+doc);
	var original_amount = get_amount('original_amount');
	var left_to_allocate = get_amount('left_to_allocate');
	var total = get_amount('amount');
	var left = 0;
	var left_from_original = 0;

	total -=  (amount-unallocated);
	left -= (amount-unallocated);
	left_from_original =original_amount-total;
	amount = unallocated;
	if(left_from_original >=0){
		if(left<0) {
			total  += left;
			amount += left;
			left = 0;
		}
	}else{
		amount +=original_amount-total;
		total  += original_amount-total;
		left=0;
	}

	price_format('amount'+doc, amount, user.pdec);
	price_format('amount', total, user.pdec);
	JsHttpRequest.request(\"_amount_update\", document.forms.kv_unallocated);
}
function kv_allocate_none(doc){
	amount = get_amount('amount'+doc);
	total = get_amount('amount');
	price_format('amount'+doc, 0, user.pdec);
	price_format('amount', total-amount, user.pdec);
	JsHttpRequest.request(\"_amount_update\", document.forms.kv_unallocated);
}

function focus_alloc(i) {
    save_focus(i);
	i.setAttribute('_last', get_amount(i.name));
}

function blur_alloc(i) {
		var change = get_amount(i.name);
		var last_amount = i.getAttribute('_last', get_amount(i.name));
		var original_amount = get_amount('original_amount');
		var prev_total = get_amount('amount')-last_amount;
		//var left_to_allocate = get_amount('left_to_allocate')-last_amount;
		if( original_amount < prev_total+change)
			change = original_amount-prev_total;
		console.log(change+'_'+left_to_allocate);
		if (i.name != 'amount' && i.name != 'charge' && i.name != 'discount')
			change = Math.min(change, get_amount('maxval'+i.name.substr(6), 1))

		price_format(i.name, change, user.pdec);
		if (i.name != 'amount' && i.name != 'charge') {
			if (change<0) change = 0;
			change = change-i.getAttribute('_last');
			if (i.name == 'discount') change = -change;

			var total = get_amount('amount')+change;
			price_format('amount', total, user.pdec, 0);
			//console.log(total);
			price_format('total_allocated', total, user.pdec, true);
			price_format('left_to_allocate', original_amount-total, user.pdec, true);
			price_format('left_to_allocate', original_amount-total, user.pdec, 0);
		}

		//if(prev_total != total)
		//	JsHttpRequest.request('_amount_update', document.forms.kv_unallocated);
}
var kv_allocations = {
	'.amount': function(e) {
 		if(e.name == 'allocated_amount' || e.name == 'bank_amount')
 		{
  		  e.onblur = function() {
			var dec = this.getAttribute('dec');
			price_format(this.name, get_amount(this.name), dec);
		  };
 		} else {
			e.onblur = function() {
				blur_alloc(this);
			};
			e.onfocus = function() {
				focus_alloc(this);
			};
		}
	}
}

Behaviour.register(kv_allocations);
";
page(_($help_context = "Undefined Bank Transaction"), true, false, "", $js);

// page(_($help_context = "Undefined Bank Transaction"));

simple_page_mode(true);
if(isset($_GET['trans_no'])){
	$trans_no =$_GET['trans_no'];
	$_POST['trans_no'] =$_GET['trans_no'];
}
if(isset($_GET['trans_type'])){
	unset($_SESSION['pay_items']);
	unset($_SESSION['alloc']);
	$trans_type =$_GET['trans_type'];
	$_POST['trans_type'] =$_GET['trans_type'];
}
if(isset($_GET['ModifyPayment'])) {
	$_POST['ModifyPayment']="yes";
} elseif(isset($_GET['ModifyDeposit'])) {
	$_POST['ModifyDeposit']="yes";
}
//----------------------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------------

function line_start_focus() {
  	global 	$Ajax;
    unset($_POST['amount_misc']);
    unset($_POST['dimension_id']);
    unset($_POST['dimension2_id']);
    unset($_POST['LineMemo']);
  	$Ajax->activate('payment_table');
  	$Ajax->activate('footer');
  	set_focus('_code_id_edit');
}

function check_item_data()
{
	if (!check_num('amount_misc', 0))
	{
		display_error( _("The amount entered is not a valid number or is less than zero."));
		set_focus('amount_misc');
		return false;
	}
	if (isset($_POST['_ex_rate']) && input_num('_ex_rate') <= 0)
	{
		display_error( _("The exchange rate cannot be zero or a negative number."));
		set_focus('_ex_rate');
		return false;
	}

	return true;
}
function handle_new_item()
{

	global $Ajax;
	if (!check_item_data()){
		return;
	}
	

	if(input_num('amount_misc') ==0){

		if(input_num('left_to_allocate') !=0){
			$_POST['amount_misc']=input_num('left_to_allocate');
		}else{
			display_error("This bank transaction amount is already allocated !");
			return;
		}
	}
	if((input_num('left_to_allocate')-input_num('amount_misc')) <0){
		if(input_num('left_to_allocate') ==0){
			display_error("This bank transaction amount is already allocated !");
			return;
		}else{
			$_POST['amount_misc']=input_num('left_to_allocate');
		}
	}

	$amount =input_num('amount_misc');
	$amount = ($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ? 1:-1) * $amount;

	$_SESSION['pay_items']->add_gl_item($_POST['code_id'], $_POST['dimension_id'],
		$_POST['dimension2_id'], $amount, $_POST['LineMemo']);
	line_start_focus();
}

function handle_update_item()
{
	$subtotal =$_SESSION['pay_items']->gl_items_total();
	$before_amount =$_SESSION['pay_items']->gl_items[$_POST['Index']]->amount;
	$current_amount =input_num('amount_misc');
	$total_amount =input_num('amount');
	$original_amount=$_SESSION['pay_items']->original_amount;


	$left_to_allocate=abs(((abs($subtotal)-abs($before_amount))+abs($total_amount))-abs($original_amount));
	if(($left_to_allocate-$current_amount)<0){
		$_POST['amount_misc']=abs($before_amount);
	}
	$amount = ($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ? 1:-1) * input_num('amount_misc');
    if($_POST['UpdateItem'] != "" && check_item_data())
    {
    	$_SESSION['pay_items']->update_gl_item($_POST['Index'], $_POST['code_id'], 
    	    $_POST['dimension_id'], $_POST['dimension2_id'], $amount , $_POST['LineMemo']);
    }
	line_start_focus();
}
function handle_delete_item($id)
{
	$_SESSION['pay_items']->remove_gl_item($id);
	line_start_focus();
}

if (isset($_POST['AddItem']))
	handle_new_item();
if (isset($_POST['UpdateItem']))
	handle_update_item();

$id = find_submit('Delete');
if ($id != -1)
	handle_delete_item($id);





function journal_check_item_data()
{
	global $Ajax;

	if (!get_post('code_id')) {
   		display_error(_("You must select GL account."));
		set_focus('code_id');
   		return false;
	}
	if (is_subledger_account(get_post('code_id'))) {
		if(!get_post('person_id')) {
	   		display_error(_("You must select subledger account."));
   			$Ajax->activate('items_table');
			set_focus('person_id');
	   		return false;
	   	}
	}
	if (isset($_POST['dimension_id']) && $_POST['dimension_id'] != 0 && dimension_is_closed($_POST['dimension_id'])) 
	{
		display_error(_("Dimension is closed."));
		set_focus('dimension_id');
		return false;
	}

	if (isset($_POST['dimension2_id']) && $_POST['dimension2_id'] != 0 && dimension_is_closed($_POST['dimension2_id'])) 
	{
		display_error(_("Dimension is closed."));
		set_focus('dimension2_id');
		return false;
	}

	if (!(input_num('AmountDebit')!=0 ^ input_num('AmountCredit')!=0) )
	{
		display_error(_("You must enter either a debit amount or a credit amount."));
		set_focus('AmountDebit');
    		return false;
  	}

	if (strlen($_POST['AmountDebit']) && !check_num('AmountDebit', 0)) 
	{
    		display_error(_("The debit amount entered is not a valid number or is less than zero."));
		set_focus('AmountDebit');
    		return false;
  	} elseif (strlen($_POST['AmountCredit']) && !check_num('AmountCredit', 0))
	{
    		display_error(_("The credit amount entered is not a valid number or is less than zero."));
		set_focus('AmountCredit');
    		return false;
  	}
	
	if (!is_tax_gl_unique(get_post('code_id'))) {
   		display_error(_("Cannot post to GL account used by more than one tax type."));
		set_focus('code_id');
   		return false;
	}

	if (!$_SESSION["wa_current_user"]->can_access('SA_BANKJOURNAL') && is_bank_account($_POST['code_id'])) 
	{
		display_error(_("You cannot make a journal entry for a bank account. Please use one of the banking functions for bank transactions."));
		set_focus('code_id');
		return false;
	}

   	return true;
}

//-----------------------------------------------------------------------------------------------
function journal_line_start_focus() {
  global 	$Ajax;

  unset($_POST['Index']);
  
  unset($_POST['_code_id_edit'], $_POST['code_id'], $_POST['AmountDebit'], 
  	$_POST['AmountCredit'], $_POST['dimension_id'], $_POST['dimension2_id']);
  set_focus('_code_id_edit');
  $Ajax->activate('header');
}
function journal_handle_update_item()
{	 
    if($_POST['journalUpdateItem'] != "" && journal_check_item_data())
    {
    	if (input_num('AmountDebit') > 0)
    		$amount = input_num('AmountDebit');
    	else
    		$amount = -input_num('AmountCredit');
    	
		$_POST['left_to_allocate'] =$_POST['left_to_allocate']+$_SESSION['journal_items']->gl_items[$_POST['Index']]->amount;
    	if($_POST['left_to_allocate']<input_num('AmountDebit')){
		if($_POST['left_to_allocate'] !=0){
				$amount =$_POST['left_to_allocate'];
			}else{
				display_error("This bank transaction amount is already allocated !");
				return;
			}
		}
    	$_SESSION['journal_items']->update_gl_item($_POST['Index'], $_POST['code_id'], 
    	    $_POST['dimension_id'], $_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
    	unset($_SESSION['journal_items']->tax_info);
		journal_line_start_focus();
    }
}

//-----------------------------------------------------------------------------------------------

function journal_handle_delete_item($id)
{
	$_SESSION['journal_items']->remove_gl_item($id);
   	unset($_SESSION['journal_items']->tax_info);
	journal_line_start_focus();
}

//-----------------------------------------------------------------------------------------------

function journal_handle_new_item()
{
	if (!journal_check_item_data())
		return;
	if (input_num('AmountDebit') > 0)
		$amount = input_num('AmountDebit');
	else
		$amount = -input_num('AmountCredit');
	if($_POST['left_to_allocate']<input_num('AmountDebit')){
		if($_POST['left_to_allocate'] !=0){
			$amount =$_POST['left_to_allocate'];
		}else{
			display_error("This bank transaction amount is already allocated !");
			return;
		}
	}
	
	$_SESSION['journal_items']->add_gl_item($_POST['code_id'], $_POST['dimension_id'],
		$_POST['dimension2_id'], $amount, $_POST['LineMemo'], '', get_post('person_id'));
  	unset($_SESSION['journal_items']->tax_info);
	journal_line_start_focus();
}
function update_tax_info()
{

	if (!isset($_SESSION['journal_items']->tax_info) || list_updated('tax_category'))
		$_SESSION['journal_items']->tax_info = $_SESSION['journal_items']->collect_tax_info();
	foreach ($_SESSION['journal_items']->tax_info as $name => $value)
		if (is_array($value))
		{
			foreach ($value as $id => $amount)
			{
				$_POST[$name.'_'.$id] = price_format($amount);
			}
		} else
			$_POST[$name] = $value;
	$_POST['tax_date'] =$_SESSION['journal_items']->tran_date;
}
$joid = find_submit('journalDelete');
if ($joid != -1){
	journal_handle_delete_item($joid);
}

if (isset($_POST['journalAddItem'])) 
	journal_handle_new_item();

if (isset($_POST['journalUpdateItem'])) 
	journal_handle_update_item();
	
if (isset($_POST['journalCancelItemChanges']))
	journal_line_start_focus();



function create_cart($type, $trans_no)
{
	global $Refs;

	if (isset($_SESSION['pay_items']))
	{
		unset ($_SESSION['pay_items']);
	}

	$cart = new items_cart($type);
    $cart->order_id = $trans_no;

	if ($trans_no) {

		$bank_trans = db_fetch(get_bank_trans(ST_UNDEFINED, $trans_no));
		$_POST['bank_account'] = $bank_trans["bank_act"];
		$_POST['PayType'] = $bank_trans["person_type_id"];
		$cart->reference = $bank_trans["ref"];

		if ($bank_trans["person_type_id"] == PT_CUSTOMER)
		{
			$trans = get_customer_trans($trans_no, $type);	
			$_POST['person_id'] = $trans["debtor_no"];
			$_POST['PersonDetailID'] = $trans["branch_code"];
		}
		elseif ($bank_trans["person_type_id"] == PT_SUPPLIER)
		{
			$trans = get_supp_trans($trans_no, $type);
			$_POST['person_id'] = $trans["supplier_id"];
		}
		elseif ($bank_trans["person_type_id"] == PT_MISC)
			$_POST['person_id'] = $bank_trans["person_id"];
		elseif ($bank_trans["person_type_id"] == PT_QUICKENTRY)
			$_POST['person_id'] = $bank_trans["person_id"];
		else 
			$_POST['person_id'] = $bank_trans["person_id"];

		$cart->memo_ = get_comments_string(ST_UNDEFINED, $trans_no);
		$cart->tran_date = sql2date($bank_trans['trans_date']);
		$cart->original_amount = $bank_trans['amount'];
		$result = get_gl_trans(ST_UNDEFINED, $trans_no);
		if ($result) {
			while ($row = db_fetch($result)) {
				if (is_bank_account($row['account'])) {
					// date exchange rate is currenly not stored in bank transaction,
					// so we have to restore it from original gl amounts
					$ex_rate = $bank_trans['amount']/$row['amount'];
				} else {
					$cart->add_gl_item( $row['account'], $row['dimension_id'],
						$row['dimension2_id'], $row['amount'], $row['memo_']);
				}
			}
		}

		// apply exchange rate
		foreach($cart->gl_items as $line_no => $line)
			$cart->gl_items[$line_no]->amount *= $ex_rate;

	} else {
		$cart->reference = $Refs->get_next($cart->trans_type, null, $cart->tran_date);
		$cart->tran_date = new_doc_date();
		if (!is_date_in_fiscalyear($cart->tran_date))
			$cart->tran_date = end_fiscalyear();
	}

	$_POST['memo_'] = $cart->memo_;
	$_POST['ref'] = $cart->reference;
	$_POST['date_'] = $cart->tran_date;

	$_SESSION['pay_items'] = &$cart;
}

function create_journal_cart($type=0, $trans_no=0)
{
	global $Refs;

	if (isset($_SESSION['journal_items']))
	{
		unset ($_SESSION['journal_items']);
	}

	check_is_closed($type, $trans_no);
	$cart = new items_cart($type);
    $cart->order_id = $trans_no;

    $bank_trans = db_fetch(get_bank_trans(ST_UNDEFINED, $_POST['trans_no']));

	$cart->tran_date = $cart->doc_date = $cart->event_date = sql2date($bank_trans['trans_date']);
	if (!is_date_in_fiscalyear($cart->tran_date))
		$cart->tran_date = end_fiscalyear();
	$cart->reference = $Refs->get_next(ST_JOURNAL, null, $cart->tran_date);

	

	$cart->memo_=get_comments_string(ST_UNDEFINED, $_POST['trans_no']);
	// $cart->tran_date = $cart->doc_date = $cart->event_date == sql2date($bank_trans['trans_date']);
	$cart->original_amount = $bank_trans['amount'];


	$_POST['memo_'] = $cart->memo_;
	$_POST['ref'] = $cart->reference;
	$_POST['date_'] = $cart->tran_date;
	$_POST['event_date'] = $cart->event_date;
	$_POST['doc_date'] = $cart->doc_date;
	$_POST['currency'] = $cart->currency;
	$_POST['_ex_rate'] = exrate_format($cart->rate);
	$_POST['source_ref'] = $cart->source_ref;
	if (isset($cart->tax_info['net_amount']) || (!$trans_no && get_company_pref('default_gl_vat')))
		$_POST['taxable_trans'] = true;
	$_SESSION['journal_items'] = &$cart;
}
//for allocation
function customer_alloc(){
	if (get_post('customer_id')) { // first page call
		$_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT, 0, get_post('customer_id'));
	}
}
function supplier_alloc(){
	if (get_post('supplier_id')) { // first page call
		$_SESSION['alloc'] = new allocation(ST_SUPPAYMENT, 0, get_post('supplier_id'));
	}
}


function get_undifined_bank_trans($type, $trans_no=null, $person_type_id=null, $person_id=null)
{
	$sql = "SELECT bt.*, act.*

		FROM ".TB_PREF."bank_trans bt ,
			 ".TB_PREF."bank_accounts act
		WHERE act.id=bt.bank_act ";
	if (isset($type))
		$sql .= " AND bt.type=".db_escape($type);
	if (isset($trans_no))
		$sql .= " AND bt.trans_no = ".db_escape($trans_no);
	$sql .= " ORDER BY trans_date, bt.id";
	return db_query($sql, "query for bank transaction");
}


function check_trans()
{
	global $Refs, $systypes_array;

	$input_error = 0;

	if ($_SESSION['pay_items']->count_gl_items() < 1) {
		display_error(_("You must enter at least one payment line."));
		set_focus('code_id');
		$input_error = 1;
	}

	if ($_SESSION['pay_items']->gl_items_total() == 0.0) {
		display_error(_("The total bank amount cannot be 0."));
		set_focus('code_id');
		$input_error = 1;
	}

	$limit = get_bank_account_limit($_POST['bank_account'], $_POST['date_']);

	$amnt_chg = -$_SESSION['pay_items']->gl_items_total()-$_SESSION['pay_items']->original_amount;

	if ($limit !== null && floatcmp($limit, -$amnt_chg) < 0)
	{
		display_error(sprintf(_("The total bank amount exceeds allowed limit (%s)."), price_format($limit-$_SESSION['pay_items']->original_amount)));
		set_focus('code_id');
		$input_error = 1;
	}
	if ($trans = check_bank_account_history($amnt_chg, $_POST['bank_account'], $_POST['date_'])) {

		if (isset($trans['trans_no'])) {
			display_error(sprintf(_("The bank transaction would result in exceed of authorized overdraft limit for transaction: %s #%s on %s."),
				$systypes_array[$trans['type']], $trans['trans_no'], sql2date($trans['trans_date'])));
			set_focus('amount');
			$input_error = 1;
		}	
	}
	if (!is_date($_POST['date_']))
	{
		display_error(_("The entered date for the payment is invalid."));
		set_focus('date_');
		$input_error = 1;
	}
	elseif (!is_date_in_fiscalyear($_POST['date_']))
	{
		display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
		set_focus('date_');
		$input_error = 1;
	} 

	if (get_post('PayType')==PT_CUSTOMER && (!get_post('customer_id') || !get_post('PersonDetailID'))) {
		display_error(_("You have to select customer and customer branch."));
		set_focus('person_id');
		$input_error = 1;
	} elseif (get_post('PayType')==PT_SUPPLIER && (!get_post('supplier_id'))) {
		display_error(_("You have to select supplier."));
		set_focus('person_id');
		$input_error = 1;
	}
	if (!db_has_currency_rates(get_bank_account_currency($_POST['bank_account']), $_POST['date_'], true))
		$input_error = 1;

	if (isset($_POST['settled_amount']) && in_array(get_post('PayType'), array(PT_SUPPLIER, PT_CUSTOMER)) && (input_num('settled_amount') <= 0)) {
		display_error(_("Settled amount have to be positive number."));
		set_focus('person_id');
		$input_error = 1;
	}
	return $input_error;
}

function check_customer_allocation()
{
	global $Refs;

	if (!get_post('customer_id'))
	{
		display_error(_("There is no customer selected."));
		set_focus('customer_id');
		return false;
	} 
	
	if (!get_post('PersonDetailID'))
	{
		display_error(_("This customer has no branch defined."));
		set_focus('BranchID');
		return false;
	} 
	
	// if (!isset($_POST['bank_trans_date']) || !is_date($_POST['bank_trans_date'])) {
	// 	display_error(_("The entered date is invalid. Please enter a valid date for the payment."));
	// 	set_focus('DateBanked');
	// 	return false;
	// } elseif (!is_date_in_fiscalyear($_POST['bank_trans_date'])) {
	// 	display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
	// 	set_focus('DateBanked');
	// 	return false;
	// }

	if (!check_num('amount', 0)) {
		display_error(_("The entered amount is invalid or negative and cannot be processed."));
		set_focus('amount');
		return false;
	}

	if (isset($_POST['charge']) && (!check_num('charge', 0) || $_POST['charge'] == $_POST['amount'])) {
		display_error(_("The entered amount is invalid or negative and cannot be processed."));
		set_focus('charge');
		return false;
	}
	if (isset($_POST['charge']) && input_num('charge') > 0) {
		$charge_acct = get_bank_charge_account($_POST['bank_account']);
		if (get_gl_account($charge_acct) == false) {
			display_error(_("The Bank Charge Account has not been set in System and General GL Setup."));
			set_focus('charge');
			return false;
		}	
	}

	if (@$_POST['discount'] == "") 
	{
		$_POST['discount'] = 0;
	}

	if (!check_num('discount')) {
		display_error(_("The entered discount is not a valid number."));
		set_focus('discount');
		return false;
	}

	if (input_num('original_amount') <= 0) {
		display_error(_("The balance of the amount and discount is zero or negative. Please enter valid amounts."));
		set_focus('discount');
		return false;
	}

	if (isset($_POST['bank_amount']) && input_num('bank_amount')<=0)
	{
		display_error(_("The entered payment amount is zero or negative."));
		set_focus('bank_amount');
		return false;
	}

	if (!db_has_currency_rates(get_customer_currency($_POST['customer_id']), $_POST['bank_trans_date'], true))
		return false;

	$_SESSION['alloc']->amount = input_num('amount');

	if (isset($_POST["TotalNumberOfAllocs"]))
		return check_allocations();
	else
		return true;
}
function check_supplier_allocation()
{
	global $Refs;

	if (!get_post('supplier_id')) 
	{
		display_error(_("There is no supplier selected."));
		set_focus('supplier_id');
		return false;
	} 
	
	if (@$_POST['amount'] == "") 
	{
		$_POST['amount'] = price_format(0);
	}

	if (!check_num('amount', 0))
	{
		display_error(_("The entered amount is invalid or less than zero."));
		set_focus('amount');
		return false;
	}

	if (isset($_POST['charge']) && !check_num('charge', 0)) {
		display_error(_("The entered amount is invalid or less than zero."));
		set_focus('charge');
		return false;
	}

	if (isset($_POST['charge']) && input_num('charge') > 0) {
		$charge_acct = get_bank_charge_account($_POST['bank_account']);
		if (get_gl_account($charge_acct) == false) {
			display_error(_("The Bank Charge Account has not been set in System and General GL Setup."));
			set_focus('charge');
			return false;
		}	
	}

	// if (@$_POST['discount'] == "") 
	// {
	// 	$_POST['discount'] = 0;
	// }

	// if (!check_num('discount', 0))
	// {
	// 	display_error(_("The entered discount is invalid or less than zero."));
	// 	set_focus('amount');
	// 	return false;
	// }

	//if (input_num('amount') - input_num('discount') <= 0) 
	// if (input_num('orginal_amount') <= 0) 
	// {
	// 	display_error(_("The total of the amount and the discount is zero or negative. Please enter positive values."));
	// 	set_focus('amount');
	// 	return false;
	// }

	if (isset($_POST['bank_amount']) && input_num('bank_amount')<=0)
	{
		display_error(_("The entered bank amount is zero or negative."));
		set_focus('bank_amount');
		return false;
	}


 //   	if (!is_date($_POST['bank_trans_date']))
 //   	{
	// 	display_error(_("The entered date is invalid."));
	// 	set_focus('DatePaid');
	// 	return false;
	// } 
	// elseif (!is_date_in_fiscalyear($_POST['bank_trans_date'])) 
	// {
	// 	display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
	// 	set_focus('DatePaid');
	// 	return false;
	// }

	$limit = get_bank_account_limit($_POST['bank_account'], $_POST['bank_trans_date']);

	if (($limit !== null) && (floatcmp($limit, input_num('amount')) < 0))
	{
		display_error(sprintf(_("The total bank amount exceeds allowed limit (%s)."), price_format($limit)));
		set_focus('amount');
		return false;
	}

	if (!db_has_currency_rates(get_supplier_currency($_POST['supplier_id']), $_POST['bank_trans_date'], true))
		return false;

	$_SESSION['alloc']->amount = -input_num('amount');

	if (isset($_POST["TotalNumberOfAllocs"]))
		return check_allocations();
	else
		return true;
}

function check_journal()
{
	$input_error = 0;

	if ($_SESSION['journal_items']->count_gl_items() < 1) {
		display_error(_("You must enter at least one journal line."));
		set_focus('code_id');
		$input_error = 1;
	}
	if (abs($_SESSION['journal_items']->gl_items_total()) > 0.001)
	{
		display_error(_("The journal must balance (debits equal to credits) before it can be processed."));
		set_focus('code_id');
		$input_error = 1;
	}

	if (!is_date($_POST['date_'])) 
	{
		display_error(_("The entered date is invalid."));
		set_focus('date_');
		$input_error = 1;
	} 
	elseif (!is_date_in_fiscalyear($_POST['date_'])) 
	{
		display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
		set_focus('date_');
		$input_error = 1;
	} 
	if (!is_date($_POST['event_date'])) 
	{
		display_error(_("The entered date is invalid."));
		set_focus('event_date');
		$input_error = 1;
	}
	if (!is_date($_POST['doc_date'])) 
	{
		display_error(_("The entered date is invalid."));
		set_focus('doc_date');
		$input_error = 1;
	}
	if (!check_reference($_POST['ref'], ST_JOURNAL, $_SESSION['journal_items']->order_id))
	{
   		set_focus('ref');
   		$input_error = 1;
	}
	if (get_post('currency') != get_company_pref('curr_default'))
		if (isset($_POST['_ex_rate']) && !check_num('_ex_rate', 0.000001))
		{
			display_error(_("The exchange rate must be numeric and greater than zero."));
			set_focus('_ex_rate');
    		$input_error = 1;
		}

	if (get_post('_tabs_sel') == 'tax')
	{
		if (!is_date($_POST['tax_date']))
		{
			display_error(_("The entered date is invalid."));
			set_focus('tax_date');
			$input_error = 1;
		} 
		elseif (!is_date_in_fiscalyear($_POST['tax_date']))
		{
			display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
			set_focus('tax_date');
			$input_error = 1;
		}
		// FIXME: check proper tax net input values, check sum of net values against total GL an issue warning
	}

	if (check_value('taxable_trans'))
	{
	 	if (!tab_visible('tabs', 'tax'))
	 	{
			display_warning(_("Check tax register records before processing transaction or switch off 'Include in tax register' option."));
			$_POST['tabs_tax'] = true; // force tax tab select
   			$input_error = 1;
		} else {
			$taxes = get_all_tax_types();
			$net_amount = 0;
			while ($tax = db_fetch($taxes))
			{
				$tax_id = $tax['id'];
				$net_amount += input_num('net_amount_'.$tax_id);
			}
			// in case no tax account used we have to guss tax register on customer/supplier used.
			if ($net_amount && !$_SESSION['journal_items']->has_taxes() && !$_SESSION['journal_items']->has_sub_accounts())
			{
				display_error(_("Cannot determine tax register to be used. You have to make at least one posting either to tax or customer/supplier account to use tax register."));
				$_POST['tabs_gl'] = true; // force gl tab select
   				$input_error = 1;
			}
		}
	}

	if ($input_error == 1)
		return false;
	else
		return true;
}






function can_process(){
	$input_error = 0;
	// if($_POST['left_to_allocate']!=0){
	// 	display_error("This bank transaction is not fully allocated !");
	// 	$input_error = 1;
	// }

	if($_POST['PayType'] ==PT_CUSTOMER && isset($_POST['ModifyDeposit'])){
		if(!check_customer_allocation()){
			$input_error = 1;
		}
	}elseif(($_POST['PayType'] ==PT_CUSTOMER && isset($_POST['ModifyPayment'])) ||($_POST['PayType'] ==PT_SUPPLIER && isset($_POST['ModifyDeposit']))){
		if(check_trans()){
			$input_error = 1;
		}
	}elseif($_POST['PayType'] ==PT_SUPPLIER && isset($_POST['ModifyPayment'])){
		if(!check_supplier_allocation()){
			$input_error = 1;
		}
	}elseif($_POST['PayType'] ==PT_JOUENTRY){
		if(!check_journal()){
			$input_error = 1;
		}
	}
	return $input_error;
}


if (isset($_POST['Process']) && !can_process())
{

	if($_POST['PayType']==PT_CUSTOMER && isset($_POST['ModifyDeposit'])){
		begin_transaction();
		$person_id =$_POST['customer_id'];
		new_doc_date($_POST['bank_trans_date']);

		$new_pmt = !$_SESSION['alloc']->trans_no;
		//Chaitanya : 13-OCT-2011 - To support Edit feature
		$_POST['ref'] = $Refs->get_next(ST_CUSTPAYMENT, null, array(
			'customer' => get_post('customer_id'), 'date' => get_post('bank_trans_date')));
		$payment_no = write_customer_payment($_SESSION['alloc']->trans_no, $_POST['customer_id'], $_POST['PersonDetailID'],
			$_POST['bank_account'], $_POST['bank_trans_date'], $_POST['ref'],
			input_num('original_amount'), input_num('discount'), get_comments_string(ST_UNDEFINED, $_POST['trans_no']), 0, input_num('charge'), input_num('amount'));
		$_SESSION['alloc']->trans_no = $payment_no;
		$_SESSION['alloc']->date_ = $_POST['bank_trans_date'];
		$_SESSION['alloc']->write();

		unset($_SESSION['alloc']);
		Update('bank_trans',array("type"=>ST_CUSTPAYMENT,"trans_no"=>$payment_no),array('imported'=>1,'reconciled'=>date2sql(Today())));
		Delete('bank_trans',array("type"=>ST_UNDEFINED,"trans_no"=>$_POST['trans_no']));
		Delete('comments', array('type' => ST_UNDEFINED, 'id' => $_POST['trans_no']));
		commit_transaction();
		display_notification("This Bank transaction successfully converted ");
		echo "<script type='text/javascript'>
		<!--
    window.open('','_parent',''); 
    window.close();
    -->
</script>"; 
	}elseif(($_POST['PayType']==PT_CUSTOMER && isset($_POST['ModifyPayment'])) ||($_POST['PayType']==PT_SUPPLIER && isset($_POST['ModifyDeposit'])) ||($_POST['PayType']==PT_MISC)){
		begin_transaction();
		if($_POST['PayType'] ==PT_CUSTOMER){
			$person_id =$_POST['customer_id'];
		}elseif($_POST['PayType'] ==PT_SUPPLIER){
			$person_id =$_POST['supplier_id'];
		}else{
			$person_id ="";
		}
		$_SESSION['pay_items'] = &$_SESSION['pay_items'];
		$new = $_SESSION['pay_items']->order_id = 0;

		add_new_exchange_rate(get_bank_account_currency(get_post('bank_account')), get_post('date_'), input_num('_ex_rate'));
		$trans = write_bank_transaction(
			$_SESSION['pay_items']->trans_type,0, $_POST['bank_account'],
			$_SESSION['pay_items'], $_POST['date_'],
			$_POST['PayType'], $person_id, get_post('PersonDetailID'),
			$_POST['ref'], $_POST['memo_'], true, input_num('settled_amount', null));

		$trans_type = $trans[0];
	   	$trans_no = $trans[1];
		new_doc_date($_POST['date_']);

		
		$_SESSION['pay_items']->clear_items();
		unset($_SESSION['pay_items']);

		Update('bank_trans',array("type"=>$trans_type,"trans_no"=>$trans_no),array('imported'=>1,'reconciled'=>date2sql(Today())));
		Delete('bank_trans',array("type"=>ST_UNDEFINED,"trans_no"=>$_POST['trans_no']));
		Delete('comments', array('type' => ST_UNDEFINED, 'id' => $_POST['trans_no']));
		
		commit_transaction();
		echo "<script type='text/javascript'>
		<!--
    window.open('','_parent',''); 
    window.close();
    -->
</script>"; 
	}elseif($_POST['PayType']==PT_SUPPLIER && isset($_POST['ModifyPayment'])){
		begin_transaction();

		$_POST['ref'] =$Refs->get_next(ST_SUPPAYMENT, null, 
    	array('supplier'=>get_post('supplier_id'), 'date'=>get_post('bank_trans_date')));

		$payment_id = write_supp_payment(0, $_POST['supplier_id'], $_POST['bank_account'],
		$_POST['bank_trans_date'], $_POST['ref'], input_num('original_amount'),	input_num('discount'), $_POST['memo_'], 
			input_num('charge'), input_num('bank_amount', input_num('amount')));
		new_doc_date($_POST['bank_trans_date']);

		$_SESSION['alloc']->trans_no = $payment_id;
		$_SESSION['alloc']->date_ = $_POST['bank_trans_date'];
		$_SESSION['alloc']->write();

		Update('bank_trans',array("type"=>ST_SUPPAYMENT,"trans_no"=>$payment_id),array('imported'=>1,'reconciled'=>date2sql(Today())));
		Delete('bank_trans',array("type"=>ST_UNDEFINED,"trans_no"=>$_POST['trans_no']));
		Delete('comments', array('type' => ST_UNDEFINED, 'id' => $_POST['trans_no']));
		commit_transaction();
		echo "<script type='text/javascript'>
		<!--
    window.open('','_parent',''); 
    window.close();
    -->
</script>"; 
	}elseif($_POST['PayType']==PT_BKTRANS){

		begin_transaction();

		$payment_no = get_next_trans_no(ST_BANKTRANSFER);
        $payment_type = ST_BANKTRANSFER;
        $payment_ref =  $Refs->get_next(ST_BANKTRANSFER, null, $_POST['bank_trans_date']); 
        $person_type = $person_id = 0;
       // $bank_charge_act = get_company_details('bank_charge_act');
        $bt  = db_fetch(get_bank_trans(ST_UNDEFINED, $_POST['trans_no']));
        $bta  =GetRow('bank_accounts', array('id' => $bt['bank_act']));
        $bto  =GetRow('bank_accounts', array('id' => $_POST['ToBankAccount']));
       // echo $_POST['BankTransAmount'].'--'.$_POST['BankCharges'];
        if($bt['amount'] < 0){
          $res = Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $_POST['ToBankAccount'], 'ref' => $payment_ref, 'trans_date' => date2sql($_POST['bank_trans_date']), 'amount' => $_POST['BankTransAmount'],'imported'=>1,'reconciled'=>date2sql(Today())));

        Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $_POST['FromBankAccount'], 'ref' => $payment_ref, 'trans_date' => date2sql($_POST['bank_trans_date']), 'amount' => -abs($_POST['BankTransAmount']),'imported'=>1,'reconciled'=>date2sql(Today())));

           Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['account_code'], 'amount' => ($bt['amount']-input_num($_POST['BankCharges'])), 'tran_date' => date2sql($_POST['bank_trans_date']) ,'memo_' => 'From '.$bta['bank_account_name'].' To '.$bto['bank_account_name']));

            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['account_code'], 'amount' => $_POST['BankTransAmount'], 'tran_date' => date2sql($_POST['bank_trans_date']), 'memo_' => 'From '.$bta['bank_account_name'].' To '.$bto['bank_account_name']));

           if($_POST['BankCharges'] > 0 ) 
            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['bank_charge_act'], 'amount' => $_POST['BankCharges'], 'tran_date' => $tran_date, 'memo_' => 'From '.$bta['bank_account_name'].' To '.$bto['bank_account_name']));
           
        } else {
          $res = Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $_POST['ToBankAccount'], 'ref' => $payment_ref, 'trans_date' => date2sql($_POST['bank_trans_date']), 'amount' => -abs($_POST['BankTransAmount']),'imported'=>1,'reconciled'=>date2sql(Today())));

          Insert('bank_trans', array('type' => $payment_type, 'trans_no'=>$payment_no, 'bank_act' => $_POST['FromBankAccount'], 'ref' => $payment_ref, 'trans_date' => date2sql($_POST['bank_trans_date']), 'amount' => $_POST['BankTransAmount'],'imported'=>1,'reconciled'=>date2sql(Today())));


          $_POST['BankTransAmount'] = -abs($_POST['BankTransAmount']);
           Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['account_code'], 'amount' => ($_POST['BankTransAmount']), 'tran_date' => date2sql($_POST['bank_trans_date']), 'memo_' => 'From '.$bto['bank_account_name'].' To '.$bta['bank_account_name']));

            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bta['account_code'], 'amount' => ($bt['amount']+input_num($_POST['BankCharges'])), 'tran_date' => date2sql($_POST['bank_trans_date']), 'memo_' => 'From '.$bto['bank_account_name'].' To '.$bta['bank_account_name']));

           if($_POST['BankCharges'] > 0 ) 
            Insert('gl_trans', array('type' => ST_BANKTRANSFER, 'type_no' => $payment_no, 'account' => $bto['bank_charge_act'], 'amount' => -abs($_POST['BankCharges']), 'tran_date' => date2sql($_POST['bank_trans_date']), 'memo_' => 'From '.$bto['bank_account_name'].' To '.$bta['bank_account_name']));

        }
		Delete('bank_trans',array("type"=>ST_UNDEFINED,"trans_no"=>$_POST['trans_no']));
		Delete('comments', array('type' => ST_UNDEFINED, 'id' => $_POST['trans_no']));
        commit_transaction();
        echo "<script type='text/javascript'>
		<!--
    window.open('','_parent',''); 
    window.close();
    -->
</script>"; 
        $msg = 'Bank Transfer registered Successfully'; //, 'res' => $res, 'amt' => $_POST['BankTransAmount']]);
    }elseif ($_POST['PayType']==PT_JOUENTRY) {
    	begin_transaction();
	    $cart = &$_SESSION['journal_items'];
		$new = $cart->order_id == 0;

		$cart->reference = $_POST['ref'];
		$cart->tran_date = $_POST['date_'];
		$cart->doc_date = $_POST['doc_date'];
		$cart->event_date = $_POST['event_date'];
		$cart->source_ref = $_POST['source_ref'];
		if (isset($_POST['memo_']))
			$cart->memo_ = $_POST['memo_'];

		$cart->currency = $_POST['currency'];
		if ($cart->currency != get_company_pref('curr_default'))
			$cart->rate = input_num('_ex_rate');

		if (check_value('taxable_trans'))
		{
			// complete tax register data
			$cart->tax_info['tax_date'] = $_POST['tax_date'];
			//$cart->tax_info['tax_group'] = $_POST['tax_group'];
			$taxes = get_all_tax_types();
			while ($tax = db_fetch($taxes))
			{
				$tax_id = $tax['id'];
				$cart->tax_info['net_amount'][$tax_id] = input_num('net_amount_'.$tax_id);
				$cart->tax_info['rate'][$tax_id] = $tax['rate'];
			}
		} else
			$cart->tax_info = false;
		$trans_no = write_journal_entries($cart);

	        // retain the reconciled status if desired by user
	        if (isset($_POST['reconciled'])
	            && $_POST['reconciled'] == 1) {
	            $sql = "UPDATE ".TB_PREF."bank_trans SET reconciled=".db_escape($_POST['reconciled_date'])
	                ." WHERE type=" . ST_JOURNAL . " AND trans_no=".db_escape($trans_no);

	            db_query($sql, "Can't change reconciliation status");
	        }

	    Update('bank_trans',array("type"=>ST_UNDEFINED,"trans_no"=>$_POST['trans_no']),array('type'=>ST_JOURNAL,'trans_no'=>$trans_no,'ref'=>$_POST['ref'],'reconciled'=>date2sql(Today())));
		commit_transaction();
		$cart->clear_items();
		new_doc_date($_POST['date_']);
    }
	

}



if(list_updated('PayType')){
	unset($_POST['amount']);

	unset($_SESSION['pay_items']);
	unset($_SESSION['alloc']);
	unset($_SESSION['journal_items']);

	if(get_post('PayType')==PT_SUPPLIER){

		$Ajax->activate('supplier_id');
		$Ajax->activate('header');
		unset($_POST['customer_id']);
	}
	if(get_post('PayType')==PT_CUSTOMER){
		$Ajax->activate('customer_id');
		unset($_POST['supplier_id']);
	}
	$Ajax->activate('header');
}

if(list_updated('customer_id')||list_updated('supplier_id')){
	if(list_updated('customer_id') && isset($_SESSION['alloc'])){
		$_SESSION['alloc']->set_person($_POST['customer_id'], PT_CUSTOMER);
		$_SESSION['alloc']->read();
		$_POST['memo_'] = $_POST['amount'] = $_POST['discount'] =$_POST['left_to_allocate'] = '';
	}
	$Ajax->activate('header');
}
if(list_updated('amount') ||list_updated('taxable_trans')||list_updated('code_id')){
	$Ajax->activate('header');
}


$payment=true;
$result = db_fetch(get_undifined_bank_trans($_POST['trans_type'], $_POST['trans_no']));
display_heading($help_context);
br();
div_start('header');
start_form(false,false,"","kv_unallocated");
start_outer_table(TABLESTYLE2, "width='90%'");


table_section(1);
label_row('Account Name',($result['account_name'])?$result['account_name']:_("Undefined"));
label_row('Reference',($result['ref'])?$result['ref']:_("Undefined"));
label_row('Entry Date',sql2date($result['trans_date']));

table_section(2);
label_row('Account No',($result['account_no'])?$result['account_no']:_("Undefined"));
label_row(($result['amount'] <0)?_('Out'):_('In'),number_format(abs($result['amount']),3));
label_row('Description',get_comments_string($_POST['trans_type'], $_POST['trans_no']));
end_outer_table(1);


start_outer_table(TABLESTYLE2, "width='90%'");
table_section(1);
if(isset($_POST['PayType']) && $_POST['PayType']==PT_BKTRANS && isset($_POST['ModifyDeposit'])){
	label_row('To ',($result['bank_account_name'])?$result['bank_account_name']:_("Undefined"));
}else{
	label_row('From ',($result['bank_account_name'])?$result['bank_account_name']:_("Undefined"));
}
table_section(2);


function kv_payment_person_types_list($name, $selected_id=null, $submit_on_change=false)
{
	global $payment_person_types;
	$items = array();
	$new_payment_person_types=$payment_person_types;

	$new_payment_person_types[PT_BKTRANS]="Bank Transfer";
	$new_payment_person_types[PT_JOUENTRY]="Journal Entry";
	foreach ($new_payment_person_types as $key=>$type)
	{
		if ($key == PT_MISC ||$key == PT_CUSTOMER||$key == PT_SUPPLIER||$key == PT_JOUENTRY||$key == PT_BKTRANS)
			$items[$key] = $type;
	}		
	return array_selector($name, $selected_id, $items, 
		array( 'select_submit'=> $submit_on_change ) );
}

function kv_payment_person_types_list_cells($label, $name, $selected_id=null, $related=null)
{
	if ($label != null)
		echo "<td>$label</td>\n";
	echo "<td>";
	echo kv_payment_person_types_list($name, $selected_id, $related);
	echo "</td>\n";
}

function kv_payment_person_types_list_row($label, $name, $selected_id=null, $related=null)
{
	echo "<tr><td class='label'>$label</td>";
	kv_payment_person_types_list_cells(null, $name, $selected_id, $related);
	echo "</tr>\n";
}



kv_payment_person_types_list_row(  _("Select"),"PayType", get_post('PayType'), true);
    switch ($_POST['PayType'])
    {
		case PT_MISC :
			table_section(3);
    		text_row_ex($payment ?_("To the Order of:"):_("Name:"),
				 'person_id', 40, 50);
    		break;
		case PT_SUPPLIER :
			table_section(3);
    		supplier_list_row(_("Supplier:"), 'supplier_id', null, false, true, false, true);
    		break;
		case PT_CUSTOMER :
			table_section(3);
    		customer_list_row(_("Customer:"), 'customer_id', null, false, true, false, true);

        	if (db_customer_has_branches($_POST['customer_id']))
        	{
        		// table_section(4);
        		customer_branches_list_row(_("Branch:"), $_POST['customer_id'], 
					'PersonDetailID', null, false, true, true, true);
        	}
        	else
        	{
				$_POST['PersonDetailID'] = ANY_NUMERIC;
        		hidden('PersonDetailID');
        	}
        	$trans = get_customer_habit($_POST['customer_id']); // take care of customers on hold
        	if ($trans['dissallow_invoices'] != 0)
        	{
        		if ($payment)
        		{
        			$customer_error = true;
					display_error(_("This customer account is on hold."));
        		}
        		else
					display_warning(_("This customer account is on hold."));
        	}
    		break;

		case PT_JOUENTRY :
			table_section(3);
			check_row(_('Include in tax register:'), 'taxable_trans', null, true);
			break;	
    }
end_outer_table(1);


if(get_post('PayType')==PT_MISC){
	include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/gl_bank_ui.inc");
	if(!isset($_SESSION['pay_items'])){
		if(isset($_POST['ModifyPayment'])) {
			create_cart(ST_BANKPAYMENT, $_POST['trans_no']);
		}else if(isset($_POST['ModifyDeposit'])) {
			create_cart(ST_BANKDEPOSIT, $_POST['trans_no']);
		}
	}
	if(!isset($_POST['bank_account']))
    		$_POST['bank_account']=$result['bank_act'];
	    hidden('bank_account',$_POST['bank_account']);
	div_start("payment_table");
	start_table(TABLESTYLE2, "width='90%'");
	start_row();
	echo "<td>";
	display_gl_items($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ?
		_("Payment Items"):_("Deposit Items"), $_SESSION['pay_items']);
	gl_options_controls($_SESSION['pay_items']);
	echo "</td>";
	end_row();
	end_table(1);
	div_end();
}elseif(get_post('PayType')==PT_CUSTOMER){
	if(isset($_POST['ModifyDeposit'])) {
		if(!isset($_POST['bank_account']))
    		$_POST['bank_account']=$result['bank_act'];
	    hidden('bank_account',$_POST['bank_account']);

		customer_alloc();
		div_start('alloc_tbl');
		show_allocatable(true);
		div_end();
	} else if(isset($_POST['ModifyPayment'])) {
		include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/gl_bank_ui.inc");
		if(!isset($_SESSION['pay_items']))
			create_cart(ST_BANKPAYMENT, $_POST['trans_no']);

		if(!isset($_POST['bank_account']))
    		$_POST['bank_account']=$result['bank_act'];
	    hidden('bank_account',$_POST['bank_account']);
		div_start("payment_table");
		start_table(TABLESTYLE2, "width='90%'");
		start_row();
		echo "<td>";
		display_gl_items(_("Customer Credit"), $_SESSION['pay_items']);
		gl_options_controls($_SESSION['pay_items']);
		echo "</td>";
		end_row();
		end_table(1);
		div_end();
	}
	
}elseif(get_post('PayType')==PT_SUPPLIER){
	
	include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/gl_bank_ui.inc");
	if(isset($_POST['ModifyDeposit'])) {
		if(!isset($_POST['bank_account']))
    		$_POST['bank_account']=$result['bank_act'];
    	hidden('bank_account',$_POST['bank_account']);

		if(!isset($_SESSION['pay_items']))
			create_cart(ST_BANKDEPOSIT, $_POST['trans_no']);

		div_start("payment_table");
		start_table(TABLESTYLE2, "width='90%'");
		start_row();
		echo "<td>";
		display_gl_items(_("Supplier Credit"), $_SESSION['pay_items']);

		gl_options_controls($_SESSION['pay_items']);
		echo "</td>";
		end_row();
		end_table(1);
		div_end();

	} else if(isset($_POST['ModifyPayment'])) {
		if(!isset($_POST['bank_account']))
    		$_POST['bank_account']=$result['bank_act'];
    	if(!isset($_POST['memo_']))
    		$_POST['memo_']=get_comments_string($_POST['trans_type'], $_POST['trans_no']);

	    hidden('bank_account',$_POST['bank_account']);
	    hidden('memo_',$_POST['memo_']);
		supplier_alloc();
		div_start('alloc_tbl');
		show_allocatable(true);
		div_end();
	}
	
}elseif(get_post('PayType')==PT_JOUENTRY){
	include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/gl_journal_ui.inc");
	if (!isset($_SESSION['journal_items']))
		create_journal_cart();
	tabbed_content_start('tabs', array(
		'gl' => array(_('&GL postings'), true),
		'tax' => array(_('&Tax register'), check_value('taxable_trans')),
	));

	hidden('date_',$_POST['date_']);
	hidden('doc_date',$_POST['doc_date']);
	hidden('event_date',$_POST['event_date']);
	hidden('source_ref',$_POST['source_ref']);
	hidden('currency',$_POST['currency']);
	switch (get_post('_tabs_sel')) {
		default:
		case 'gl':
			start_table(TABLESTYLE2, "width='90%'", 10);
			start_row();
			echo "<td>";
			display_gl_items(_("Rows"), $_SESSION['journal_items']);
			gl_options_controls();
			echo "</td>";
			end_row();
			end_table(1);
			break;

		case 'tax':
			hidden('left_to_allocate',$_POST['left_to_allocate']);
			update_tax_info();
			br();
			display_heading(_("Tax register record"));
			br();
			start_table(TABLESTYLE2, "width=40%");
			date_row(_("VAT date:"), 'tax_date', '', "colspan='3'");
			//tax_groups_list_row(_("Tax group:"), 'tax_group');
			end_table(1);

			start_table(TABLESTYLE2, "width=60%");
			table_header(array(_('Name'), _('Input Tax'), _('Output Tax'), _('Net amount')));
			$taxes = get_all_tax_types();
			while ($tax = db_fetch($taxes))
			{
				start_row();
				label_cell($tax['name'].' '.$tax['rate'].'%');
				amount_cell(input_num('tax_in_'.$tax['id']));
				amount_cell(input_num('tax_out_'.$tax['id']));

				amount_cells(null, 'net_amount_'.$tax['id']);
				end_row();
			}
			end_table(1);
			break;
	};
}
elseif(get_post('PayType')==PT_BKTRANS){
		start_outer_table(TABLESTYLE2);

	table_section(1);
	if(isset($_POST['ModifyPayment'])){
	   bank_accounts_list_row(_("To Account:"), 'ToBankAccount', null, true);
    }elseif(isset($_POST['ModifyDeposit'])){
    	 bank_accounts_list_row(_("From Account:"), 'ToBankAccount', null, true);
    }
    
    // if(isset($_POST['ModifyPayment'])){
	   //  if(!isset($_POST['FromBankAccount']))
	    	$_POST['FromBankAccount']=$result['bank_act'];
	    hidden('FromBankAccount',$_POST['FromBankAccount']);
    // }elseif(isset($_POST['ModifyDeposit'])){
    // 	 if(!isset($_POST['ToBankAccount']))
	   //  	$_POST['ToBankAccount']=$result['bank_act'];
	   //  hidden('ToBankAccount',$_POST['ToBankAccount']);
    // }

	if (!isset($_POST['DatePaid'])) { // init page
		$_POST['DatePaid'] = new_doc_date();
		if (!is_date_in_fiscalyear($_POST['DatePaid']))
			$_POST['DatePaid'] = end_fiscalyear();
	}
    ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_BANKTRANSFER, null, get_post('DatePaid')), false, ST_BANKTRANSFER,
    	array('date' => get_post('DatePaid')));

	$from_currency = get_bank_account_currency($_POST['FromBankAccount']);
	$to_currency = get_bank_account_currency($_POST['ToBankAccount']);
	if(!isset($_POST['BankTransAmount'])){
		$_POST['BankTransAmount']=abs($result['amount']);
	}
	hidden('BankTransAmount',$_POST['BankTransAmount']);
	hidden('left_to_allocate',0);
	if ($from_currency != "" && $to_currency != "" && $from_currency != $to_currency) 
	{
		label_row(_("Amount:"), price_format($_POST['BankTransAmount']));
		// amount_row(_("Amount:"), 'amount', null, null, $from_currency);
		amount_row(_("Bank Charge:"), 'BankCharges', null, null, $from_currency);

		amount_row(_("Incoming Amount:"), 'target_amount', null, '', $to_currency, 2);
	} 
	else 
	{

		// amount_row(_("Amount:"), 'amount');
		label_row(_("Amount:"), price_format($_POST['BankTransAmount']));
		amount_row(_("Bank Charge:"), 'BankCharges');
	}

    textarea_row(_("Memo:"), 'memo_', null, 40,4);

	end_outer_table(1); // outer table
}


if(isset($_POST['ModifyDeposit']))
	hidden('ModifyDeposit',$_POST['ModifyDeposit']);

if(isset($_POST['ModifyPayment']))
	hidden('ModifyPayment',$_POST['ModifyPayment']);

if(!isset($_POST['original_amount']))
	$_POST['original_amount'] =price_format(abs($result['amount']));

hidden('original_amount',$_POST['original_amount']);

if(!isset($_POST['bank_trans_date']))
	$_POST['bank_trans_date'] =sql2date($result['trans_date']);
hidden('bank_trans_date',$_POST['bank_trans_date']);

if(isset($_POST['date_']))
	hidden('date_',$_POST['date_']);
if(isset($_POST['ref']))
	hidden('ref',$_POST['ref']);

hidden('trans_type',$_POST['trans_type']);
hidden('trans_no',$_POST['trans_no']);
submit_center_first('Update', _("Update"), '', null);
submit_center_last('Process', isset($_POST['ModifyPayment']) ?
	_("Process Payment"):_("Process Deposit"), '', 'default');
end_form();
div_end();
end_page();

