<?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>.
***********************************************************************/
function display_gl_cash_header(&$order)
{
	global $Ajax;
	if($order->trans_type == ST_CASH_PAYMENT){
            $payment = true;
            $list_codes_in = "'GL_TRANS_TYPE_CASH_PAYMENT'";
        }
	elseif($order->trans_type == ST_CASH_RECEIPT){
            $payment = false;
            $list_codes_in = "'GL_TRANS_TYPE_CASH_RECEIPT'";
        }
        else{
            $list_codes_in = "''";
        }

	$customer_error = false;
	div_start('pmt_header');

	start_outer_table(TABLESTYLE2, "width='90%'"); // outer table

	table_section(1);
	
                date_row(_("Date:"), 'date_', '', true, 0, 0, 0, null, true);

                ref_row(_("Reference:"), 'ref', '', $order->reference, false, $order->trans_type, get_post('date_'));

	table_section(2, "33%");

                if (!isset($_POST['PayType']))
                {
                        if (isset($_GET['PayType']))
                                $_POST['PayType'] = $_GET['PayType'];
                        else
                                $_POST['PayType'] = "";
                }
                if (!isset($_POST['person_id']))
                {
                        if (isset($_GET['PayPerson']))
                                $_POST['person_id'] = $_GET['PayPerson'];
                        else
                                $_POST['person_id'] = "";
                }
                if (isset($_POST['_PayType_update'])) {
                        $_POST['person_id'] = '';
                        $Ajax->activate('pmt_header');
                        $Ajax->activate('code_id');
                        $Ajax->activate('pagehelp');
                        $Ajax->activate('editors');
                        $Ajax->activate('footer');
                }
    
                payment_person_types_list_row( $payment ? _("Pay To:"):_("From:"),'PayType', $_POST['PayType'], true);
                
                switch ($_POST['PayType'])
                {
                        case PT_MISC :
                                text_row_ex($payment ?_("To the Order of:"):_("Name:"),'person_id', 40, 50);
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_MISC'", null, 'Select a gl trans type', true);

                                break;
                        case PT_SUPPLIER :
                                supplier_list_row(_("Supplier:"), 'person_id', null, false, true, false, true);
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_SUPPLIER'", null, 'Select a gl trans type', true);
                                break;
                        case PT_CUSTOMER :
                                customer_list_row(_("Customer:"), 'person_id', null, false, true, false, true);

                                if (db_customer_has_branches($_POST['person_id']))
                                {
                                        customer_branches_list_row(_("Branch:"), $_POST['person_id'], 'PersonDetailID', null, false, true, true, true);
                                }
                                else
                                {
                                        $_POST['PersonDetailID'] = ANY_NUMERIC;
                                        hidden('PersonDetailID');
                                }
                                $trans = get_customer_habit($_POST['person_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."));
                                }
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_CUSTOMER'", null, 'Select a gl trans type', true);
                                break;

                        case PT_QUICKENTRY :
                                quick_entries_list_row(_("Type").":", 'person_id', null, ($payment ? QE_PAYMENT : QE_DEPOSIT), true);
                                $qid = get_quick_entry(get_post('person_id'));
                                if (list_updated('person_id')) {
                                        unset($_POST['totamount']); // enable default
                                        $Ajax->activate('footer');
                                        $Ajax->activate('totamount');
                                }
                                amount_row($qid['base_desc'].":", 'totamount', price_format($qid['base_amount']),
                                         null, "&nbsp;&nbsp;".submit('go', _("Go"), false, false, true));
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_QUICKENTRY'", null, 'Select a gl trans type', true);
                                break;
                                
                        case PT_EMPLOYEE :
                                group_companies_list_row("Company:", 'person_id', null, false, true);
                                if (list_updated('group_company_code')) {
                                        $Ajax->activate('person_id');
                                }
                                group_company_employee_ids_simple_list_row(_("Employee:"), 'PersonDetailID', get_post('person_id'),null, false);    
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_EMPLOYEE'", null, 'Select a gl trans type', true);

                                break;	
                                
                        case PT_FLOAT :
                                $txt = $order->trans_type == ST_CASH_PAYMENT ? "Receiving Into Float:" : "Paying From Float:";
                                petty_cash_floats_list_row($txt, 'person_id', null, 'Select a float');
                                filtered_value_list_row('GL Trans Type:', 'gl_trans_type_id', $list_codes_in, "'PT_FLOAT'", null, 'Select a gl trans type', true);
                                break;	
                                
                                        

        
                }

	table_section(3, "33%");

//                if (!$order->order_id && !get_post('bank_account'))
//                {
//                        if ($_POST['PayType'] == PT_CUSTOMER)
//                                $_POST['bank_account'] = get_default_customer_bank_account($_POST['person_id']);
//                        elseif ($_POST['PayType'] == PT_SUPPLIER)	
//                                $_POST['bank_account'] = get_default_supplier_bank_account($_POST['person_id']);
//                        else
//                                unset($_POST['bank_account']);
//                }		
    
        
                if (!isset_numeric_post('float_id') && isset($order->float_id)){
                    $_POST['float_id'] = $order->float_id;
                }
        
                $txt = $order->trans_type == ST_CASH_PAYMENT ? "Paying From Float:" : "Receiving Into Float:";
                petty_cash_floats_list_row($txt, 'float_id', null, 'Select float');
                
                $cash_act_code = get_company_pref("default_cash_act");
//                $cash_act_name = get_gl_account_formatted_name($cash_act_code);
//                label_row("From Cash Account:", $cash_act_name);
                hidden('cash_act_code', $cash_act_code);
                
//                bank_accounts_list_row( $payment ? _("From:") : _("Into:"), 'bank_account', null, true);
//                if ($payment){
//                        bank_balance_row($_POST['bank_account']);
//                }
//
//                $bank_currency = get_bank_account_currency($_POST['bank_account']);
//
//                exchange_rate_display(get_company_currency(), $bank_currency, $_POST['date_']);

	end_outer_table(1); // outer table

	div_end();
        
	if ($customer_error)
	{
		end_form();
		end_page();
		exit;
	}
}
//---------------------------------------------------------------------------------

function display_gl_cash_items($title, &$order)
{
	global $path_to_root;

	$dim = get_company_pref('use_dimension');
	$colspan = ($dim == 2 ? 4 : ($dim == 1 ? 3 : 2));
	display_heading($title);

    div_start('items_table');
	start_table(TABLESTYLE, "width='95%'");

	if ($dim == 2)
		$th = array(_("Account Code"), _("Account Description"), _("Dimension")." 1",
			_("Dimension")." 2", _("Amount"), _("Memo"), "");
	elseif ($dim == 1)
		$th = array(_("Account Code"), _("Account Description"), _("Dimension"),
			_("Amount"), _("Memo"), "");
	else
		$th = array(_("Account Code"), _("Account Description"),
			_("Amount"), _("Memo"), "");

	if (count($order->gl_items)) $th[] = '';

	table_header($th);
	$k = 0;  //row colour counter

	$id = find_submit('Edit');
	foreach ($order->gl_items as $line => $item)
	{
		if ($id != $line)
		{
    		alt_table_row_color($k);

			label_cell($item->code_id);
			label_cell($item->description);
    		if ($dim >= 1)
				label_cell(get_dimension_string($item->dimension_id, true));
    		if ($dim > 1)
				label_cell(get_dimension_string($item->dimension2_id, true));
			if ($order->trans_type == ST_CASH_RECEIPT)
				amount_cell(-$item->amount);
			else		
				amount_cell($item->amount);
			label_cell($item->reference);

			edit_button_cell("Edit$line", _("Edit"),
				_('Edit document line'));
			delete_button_cell("Delete$line", _("Delete"),
				_('Remove line from document'));
    		end_row();
		}
		else
		{
			gl_edit_item_controls($order, $dim, $line);
		}
	}

	if ($id == -1)
		gl_edit_item_controls($order, $dim);

	if ($order->count_gl_items())
		label_row(_("Total"), number_format2(abs($order->gl_items_total()), user_price_dec()),"colspan=" . $colspan . " align=right", "align=right",3);

    end_table();
	div_end();
}

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

function gl_edit_item_controls(&$order, $dim, $Index=null)
{
	global $Ajax;
	$payment = $order->trans_type == ST_BANKPAYMENT;

	start_row();
	$id = find_submit('Edit');
	if ($Index != -1 && $Index == $id)
	{
		$item = $order->gl_items[$Index];
		$_POST['code_id'] = $item->code_id;
		$_POST['dimension_id'] = $item->dimension_id;
		$_POST['dimension2_id'] = $item->dimension2_id;
		$_POST['amount'] = price_format(abs($item->amount));
		$_POST['description'] = $item->description;
		$_POST['LineMemo'] = $item->reference;

		hidden('Index', $id);
	    $Ajax->activate('items_table');
	}
	else
	{
		if(isset($_POST['_code_id_update'])) {
			    $Ajax->activate('code_id');
		}
		if (list_updated('PayType') || list_updated('person_id'))
		{
			if ($_POST['PayType'] == PT_CUSTOMER)
			{
				$acc = get_branch_accounts($_POST['PersonDetailID']);
				$_POST['code_id'] = $acc['receivables_account'];
			}
			elseif ($_POST['PayType'] == PT_SUPPLIER)
			{
				$acc = get_supplier_accounts($_POST['person_id']);
				$_POST['code_id'] = $acc['payable_account'];
				$_POST['dimension_id'] = isset($acc['dimension_id']) ? $acc['dimension_id'] : 0;
				$_POST['dimension2_id'] = isset($acc['dimension2_id']) ? $acc['dimension2_id'] : 0;
			}
			else {
				$_POST['code_id'] =
					get_company_pref($payment ? 'default_cogs_act':'default_inv_sales_act');
			}
			$Ajax->activate('dimension_id');
			$Ajax->activate('dimension2_id');
		}
	}
	echo gl_all_accounts_list('code_id', null, false, true);
	if ($dim >= 1)
		dimensions_list_cells(null, 'dimension_id', null, true, " ", false, 1);
	else
		hidden('dimension_id', 0);
	if ($dim > 1)
		dimensions_list_cells(null, 'dimension2_id', null, true, " ", false, 2);
	else
		hidden('dimension2_id', 0);

	amount_cells(null, 'amount');
	text_cells_ex(null, 'LineMemo', 35, 255);

	if ($id != -1)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
 		set_focus('amount');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
	}

	end_row();
}


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

function gl_options_controls($order)
{
	div_start('footer');
	echo "<br><table align='center'>";

	$type = get_post('PayType');
//	$bank_curr = get_bank_account_currency(get_post('bank_account'));
        $company_curr = get_company_pref('curr_default');
	$person_curr = $type == PT_CUSTOMER ? get_customer_currency(get_post('person_id')) 
		: ($type == PT_SUPPLIER ? get_supplier_currency(get_post('person_id')) : $company_curr);

	if ($person_curr != $company_curr)
	{
		$_POST['settled_amount'] =
			price_format(abs($order->gl_items_total() / get_exchange_rate_from_to($company_curr, $person_curr, get_post('date_'))));
		amount_row($type == PT_CUSTOMER ? _("Settled AR Amount:") :  _("Settled AP Amount:"),
			 'settled_amount', null, null, $person_curr, user_price_dec());
	}
	textarea_row(_("Memo"), 'memo_', null, 50, 3);

  	echo "</table>";
  	div_end();
}


function check_cash_trans($name)
{
	global $Refs, $systypes_array;

	$input_error = 0;
        
        if(!($_POST['float_id'] > 0)){
                $txt = $_SESSION[$name]->trans_type == ST_CASH_PAYMENT ? "paying from" : "receiving into";
                display_error("Please select $txt float.");
                set_focus("float_id");
                $input_error = 1;      
        }
        
        $float = get_petty_cash_float_line($_POST['float_id']);
        $cash_act_code = $float['account_code'];        
        if(!(strlen($cash_act_code) > 2)){
                display_error(_("No gl account attached to the selected float."));
//		set_focus('code_id');
		$input_error = 1;
        }

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

	if ($_SESSION[$name]->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[$name]->gl_items_total()-$_SESSION[$name]->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[$name]->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;
//		}	
//	}
        
	$msg = reference_exists($_POST['ref'], $_SESSION[$name]->trans_type, $_SESSION[$name]->order_id);
	if($msg){
                display_error($msg); 
		set_focus('ref');
		$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;
	} 

        
        $msg = is_accounting_period_open($_POST['date_']);
	if ($msg['success'] !== true)
	{
		display_error($msg['message']);
		set_focus('date_');
		$input_error = 1;
	}
        
//	if (get_post('PayType')==PT_CUSTOMER && (!get_post('person_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('person_id'))) {
//		display_error(_("You have to select supplier."));
//		set_focus('person_id');
//		$input_error = 1;
//	}
        
        $pay_type = get_post('PayType');
        switch ($pay_type) {
            case PT_CUSTOMER:
                if (!(get_post('person_id') > 0) || !(get_post('PersonDetailID') > 0)) {
                    display_error(_("You have to select customer and customer branch."));
                    set_focus('person_id');
                    $input_error = 1;
                }
                break;

            case PT_SUPPLIER:
                if (!(get_post('person_id') > 0)) {
                    display_error(_("You have to select supplier."));
                    set_focus('person_id');
                    $input_error = 1;
                }
                break;
             
            case PT_FLOAT:
                if (!(get_post('person_id') > 0)) {
                    $txt = $_SESSION[$name]->trans_type == ST_CASH_PAYMENT ? "receiving into" : "paying from";
                    display_error(_("You have to select $txt float."));
                    set_focus('person_id');
                    $input_error = 1;
                }
	}
        
        if (! ($_POST['gl_trans_type_id'] > 0)) {
            display_error(_("Please select a gl tranaction type."));
            set_focus('gl_trans_type_id');
            $input_error = 1;
	}
        
        if (get_post('PayType')==PT_CUSTOMER && (!get_post('person_id') || !get_post('PersonDetailID'))) {
                $currency = get_customer_currency(get_post('person_id'), get_post('PersonDetailID'));
	} elseif (get_post('PayType')==PT_SUPPLIER && (!get_post('person_id'))) {
                $currency = get_supplier_currency(get_post('person_id'));
	}else{
                $currency = get_company_pref('curr_default');
        }  
        
        
	if (!db_has_currency_rates($currency, $_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_cash_item_data()
{
    
	if (!check_num('amount', 0))
	{
		display_error( _("The amount entered is not a valid number or is less than zero."));
		set_focus('amount');
		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 cash_line_start_focus() {
  	global 	$Ajax;

    unset($_POST['amount']);
    unset($_POST['dimension_id']);
    unset($_POST['dimension2_id']);
    unset($_POST['LineMemo']);
  	$Ajax->activate('items_table');
  	$Ajax->activate('footer');
  	set_focus('_code_id_edit');
}

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

function handle_update_cash_item($name)
{
	$amount = ($_SESSION[$name]->trans_type==ST_CASH_PAYMENT ? 1:-1) * input_num('amount');
    if($_POST['UpdateItem'] != "" && check_cash_item_data())
    {
    	$_SESSION[$name]->update_gl_item($_POST['Index'], $_POST['code_id'], 
    	    $_POST['dimension_id'], $_POST['dimension2_id'], $amount , $_POST['LineMemo']);
    }
	cash_line_start_focus();
}


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

function handle_delete_cash_item($name, $id)
{
	$_SESSION[$name]->remove_gl_item($id);
	cash_line_start_focus();
}

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

function handle_new_cash_item($name)
{
	if (!check_cash_item_data())
		return;
	$amount = ($_SESSION[$name]->trans_type==ST_CASH_PAYMENT ? 1:-1) * input_num('amount');

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

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

function create_cash_cart($name, $type, $trans_no)
{
	global $Refs;

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

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

	if ($trans_no > 0) {
                $bank_trans = get_pre_gl_adjustment_transaction_header($type, $trans_no);
                if(!isset_numeric_post('float_id')){
                    $_POST['float_id'] = $bank_trans["float_id"];
                }
                $float = get_petty_cash_float_line($_POST['float_id']);
                $_POST['cash_act_code'] = $float["account_code"];
                $_POST['PayType'] = $bank_trans["person_type_id"];
                $cart->reference = $bank_trans["reference"];
                $_POST['gl_trans_type_id'] = $bank_trans["gl_trans_type_id"];
                $_POST['header_total_amount'] = $bank_trans["amount"];

                if ($bank_trans["person_type_id"] == PT_CUSTOMER) {	
                    $_POST['person_id'] = $bank_trans["person_id"]; // person_id
                    $_POST['PersonDetailID'] = $bank_trans["person_detail_id"];//person_detail_id
                } elseif ($bank_trans["person_type_id"] == PT_SUPPLIER) {
                    $_POST['person_id'] = $bank_trans["person_id"]; // person_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"];
                }
                elseif ($bank_trans["person_type_id"] == PT_EMPLOYEE) {	
                    $_POST['person_id'] = $bank_trans["person_id"]; // person_id
                    $_POST['PersonDetailID'] = $bank_trans["person_detail_id"];//person_detail_id
                }
                else 
                    $_POST['person_id'] = $bank_trans["person_id"];

//                $cart->memo_ = get_comments_string($type, $trans_no);
                $cart->memo_ = $bank_trans["comment"];
                $cart->tran_date = sql2date($bank_trans['tran_date']);//tran_date

                $cart->original_amount = $bank_trans['amount'];
                $result = get_pre_gl_trans($type, $trans_no);
                $ex_rate = 1;
                if ($result) {
                    while ($row = db_fetch($result)) {
                        if ($type == ST_CASH_PAYMENT && $row['amount'] < 0) {
                            continue;
                        } elseif ($type == ST_CASH_RECEIPT && $row['amount'] > 0) {
                            continue;
                        }

                        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'];
                            $cart->add_gl_item($row['account'], $row['dimension_id'], $row['dimension2_id'], $row['amount'], $row['memo_']);
                        } 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[$name] = &$cart;
}

function process_cash_transaction($name, $approve=false)
{
        $float = get_petty_cash_float_line($_POST['float_id']);
        $cash_act_code = $float['account_code'];
        
	begin_transaction();

	$_SESSION[$name] = &$_SESSION[$name];
	$new = $_SESSION[$name]->order_id == 0;

        if (get_post('PayType')==PT_CUSTOMER && (!get_post('person_id') || !get_post('PersonDetailID'))) {
                $currency = get_customer_currency(get_post('person_id'), get_post('PersonDetailID'));
	} elseif (get_post('PayType')==PT_SUPPLIER && (!get_post('person_id'))) {
                $currency = get_supplier_currency(get_post('person_id'));
	}else{
                $currency = get_company_pref('curr_default');
        } 
        
        
        $trans = write_pre_gl_adjustment_transaction($_SESSION[$name]->trans_type, $_SESSION[$name]->order_id, $cash_act_code,
                                                    $_SESSION[$name], $_POST['date_'], $_POST['PayType'], $_POST['person_id'], 
                                                    get_post('PersonDetailID', 0), $_POST['ref'], $_POST['memo_'], $currency, input_num('_ex_rate'),
                                                    $_POST['float_id'], $_POST['gl_trans_type_id']);
       
        
        if (isset($trans['message'])) {
            cancel_transaction();
            return $trans;
        }
        
        $trans_type = $trans[0];
        $trans_no = $trans[1];
            
        if($approve){
            add_new_exchange_rate($currency, get_post('date_'), input_num('_ex_rate'));

            $trans = write_gl_transaction(
                    $_SESSION[$name]->trans_type, $trans_no, $cash_act_code,
                    $_SESSION[$name], $_POST['date_'],
                    $_POST['PayType'], $_POST['person_id'], get_post('PersonDetailID',0),
                    $_POST['ref'], $_POST['memo_'], $currency, input_num('_ex_rate'), input_num('settled_amount', null), $_POST['float_id'], 
                    $_POST['gl_trans_type_id']);

            $total_amount = $_SESSION[$name]->gl_items_total();
            if($_SESSION[$name]->trans_type == ST_CASH_PAYMENT){
                $total_amount = -abs($total_amount);
            }
            elseif($_SESSION[$name]->trans_type == ST_CASH_RECEIPT){
                $total_amount = abs($total_amount);
            }
            
            add_to_petty_cash_float($_SESSION[$name]->trans_type, $trans_no, $_POST['float_id'], $total_amount, $_POST['date_']);
            
            $n = update_pre_gl_adjustment_approved($trans_type, $trans_no);
            
            if($n != 1){
                cancel_transaction();
                return array($trans_type, $trans_no, 
                            'message' => 'This transaction is already approved.');
            }
        }
        
        commit_transaction();
        
	new_doc_date($_POST['date_']);

	$_SESSION[$name]->clear_items();
	unset($_SESSION[$name]);

	return $trans;

//	if ($new)
//		meta_forward($_SERVER['PHP_SELF'], $trans_type==ST_CASH_PAYMENT ? "AddedPay=$trans_no" : "AddedDep=$trans_no");
//	else
//		meta_forward($_SERVER['PHP_SELF'], $trans_type==ST_CASH_PAYMENT ? "UpdatedRec=$trans_no" : "UpdatedRec=$trans_no");

}
