<?php
/**********************************************************************
***********************************************************************/


function display_bank_account_reconcile_header()
{
    start_table(TABLESTYLE_NOBORDER);
    start_row();
    bank_accounts_list_cells(_("Account:"), 'bank_account', null, true);

    bank_reconciliation_list_cells(_("Bank Statement:"), get_post('bank_account'),
            'bank_date', null, true, _("New"));
    end_row();
    end_table();
    
    
    $rec_header = array();

    if(is_date(sql2date($_POST['bank_date'])) && $_POST['bank_account'] > 0){
        $rec_header = get_bank_reconciliation_header($_POST['bank_account'], $_POST['bank_date']);  
        if(is_array($rec_header)){
            $_POST["beg_balance"] = price_format($rec_header["statement_beginning_balance"]);
            $_POST["end_balance"] = price_format($rec_header["statement_ending_balance"]);
        }
        
    }
    $result = get_max_reconciled(get_post('reconcile_date'), $_POST['bank_account']);

    if ($row = db_fetch($result)) {
            $_POST["reconciled"] = price_format($row["end_balance"]-$row["beg_balance"]);
//            $total = $row["total"];
            if(isset($_POST['bank_date']) && strlen($_POST['bank_date'] > 4)){
                $bank_date = sql2date($_POST['bank_date']);
            }
            else{
                $bank_date = get_post('reconcile_date');
            }
            $total = get_balance_before_for_bank_account($_POST['bank_account'], add_days($bank_date,1));
            if (!isset($_POST["beg_balance"])) { // new selected account/statement
                    $_POST["last_date"] = sql2date($row["last_date"]);
                    $_POST["beg_balance"] = price_format($row["beg_balance"]);
                    $_POST["end_balance"] = price_format($row["end_balance"]);
                    if (get_post('bank_date')) {
                            // if it is the last updated bank statement retrieve ending balance

                            $row = get_ending_reconciled($_POST['bank_account'], $_POST['bank_date']);
                            if($row) {
                                    $_POST["end_balance"] = price_format($row["ending_reconcile_balance"]);
                            }
                    }else{
                            $last_rec_header = get_last_bank_reconciliation_header($_POST['bank_account']);
                            if(is_array($last_rec_header)){
                                $_POST["beg_balance"] = price_format($last_rec_header['statement_ending_balance']);
                            }else{
                                $_POST["beg_balance"] = price_format(0);
                            }                    
                    }
            } 
    }

    echo "<hr>";

    div_start('summary');

    start_table(TABLESTYLE);
    $th = array(_("Reconcile Date"), _("Beginning<br>Balance"), 
            _("Ending<br>Balance"), _("Account<br>Total"),_("Reconciled<br>Amount"), _("Reconciliation<br>Difference"), _("Unreconciled<br>Transactions"));
    table_header($th);
    start_row();

    if(list_updated_date('bank_date')){
        $bank_date_ = sql2date($_POST['bank_date']);
        if(is_date($bank_date_)){
            $_POST['filter_date'] = $bank_date_;
        }
        else{
            $_POST['filter_date'] = Today();
        }
    }
    
    date_cells("", "reconcile_date", _('Date of bank statement to reconcile'), get_post('bank_date')=='', 0, 0, 0, null, true);

    amount_cells_ex("", "beg_balance", 15);
    //$_POST['beg_balance'] = input_num("beg_balance");
    //hidden("beg_balance", input_num("beg_balance"));
    //amount_decimal_cell(input_num("beg_balance"),"","beg_balance");

    amount_cells_ex("", "end_balance", 15);
    //$_POST['end_balance'] = input_num("end_balance");
    //hidden("end_balance", input_num("end_balance"));
    //amount_decimal_cell(input_num("end_balance"), "", "end_balance");

    $reconciled = input_num('reconciled');
    $difference = input_num("end_balance") - input_num("beg_balance") - $reconciled;

    amount_cell($total, false, '', "account_total");
    amount_cell($reconciled, false, '', "reconciled");
    amount_cell($difference, false, '', "difference");
    
    $rec_id = $unreconciled_total = 0;
    if(isset($rec_header['id']) && $rec_header['id'] > 0){
        if(strlen($rec_header['unreconciled_ids']) > 0){
            $unreconciled_total = get_statetment_unreconciled_total($rec_header['unreconciled_ids']);
        }
        
        $rec_id = $rec_header['id'];
    }
    
    
    if ($rec_id > 0) {
        $link = get_unreconciled_transactions_view_str($rec_id, number_format($unreconciled_total, 2));
        label_cell($link, '', 'unrectotal');
    } else {
        label_cell('', '', 'unrectotal');
    }
    
//    $link = get_reconciled_account_difference_view_str($rec_id, number_format($unreconciled_total, 2));
//    label_cell($link, '', 'recaccountdiff');
//    amount_cell($unreconciled_total, false, '', 'unrectotal');

    //hidden('account_balance', $total);
    //hidden('reconciled_total', $reconciled);
    //hidden('difference_total', $difference);
    //$_POST['account_balance'] = $total;
    //$_POST['reconciled_total'] = $reconciled;
    //$_POST['difference_total'] = $difference;

    end_row();
    end_table();
    div_end();
}

function display_bank_account_reconciliation_details()
{
    $sql = get_sql_for_bank_account_reconcile($_POST['bank_account'], get_post('reconcile_date'));

$act = get_bank_account($_POST["bank_account"]);
display_heading($act['bank_account_name']." - ".$act['bank_curr_code']);

	$cols =
	array(
		_("Type") => array('fun'=>'systype_name', 'ord'=>''),
		_("#") => array('fun'=>'trans_view', 'ord'=>''),
		_("Reference"), 
                _("Cheque No"),
		_("Date") => 'date',
		_("Debit") => array('align'=>'right', 'fun'=>'fmt_debit'), 
		_("Credit") => array('align'=>'right','insert'=>true, 'fun'=>'fmt_credit'), 
	    _("Person/Item") => array('fun'=>'fmt_person'), 
		array('insert'=>true, 'fun'=>'gl_view'),
		"X"=>array('insert'=>true, 'fun'=>'rec_checkbox')
	   );
	$table =& new_db_pager('trans_tbl', $sql, $cols, null, null, 50);

	$table->width = "90%";
	display_db_pager($table);
}

function can_commit_bank_reconciliation($reconcile_id, $reconcile_date_)
{
//    if(check_future_bank_reconciliations($reconcile_id, $reconcile_date_)){
//        $msg = "There are bank reconciliations created after ".$reconcile_date_.". This bank reconciliation can not be updated.";
//        display_error($msg);
//        return false;
//    }
    
    return true;
}

function change_tpl_flag($reconcile_id)
{
	global	$Ajax;

	if (!check_date() 
		&& check_value("rec_".$reconcile_id)){ // temporary fix
		return false;
        }
        
        if(!can_commit_bank_reconciliation($_POST['bank_account'], get_post('reconcile_date'))){
            return;
        }

	if (get_post('bank_date')=='')	// new reconciliation
		$Ajax->activate('bank_date');

	$_POST['bank_date'] = date2sql(get_post('reconcile_date'));
//	$reconcile_value = check_value("rec_".$reconcile_id) 
//						? (($_POST['bank_date'])) : '';
        $reconcile_value = check_value("rec_".$reconcile_id) ? $_POST['bank_date'] : INFINITE_START_DATE;
	
        $statement_beginning_balance = input_num('beg_balance');
        $statement_ending_balance = input_num('end_balance');   
        
        begin_transaction();
        
	$urv_msg = update_reconciled_values($reconcile_id, $reconcile_value, $_POST['reconcile_date'],
                    input_num('end_balance'), $_POST['bank_account'],
                    $statement_beginning_balance, $statement_ending_balance);

		
	$Ajax->activate('account_total');
	$Ajax->activate('reconciled');
	$Ajax->activate('difference');
	$Ajax->activate('unrectotal');
	$Ajax->activate('recaccountdiff');
        
                
        if($urv_msg['success'] === true){
            commit_transaction();
            return $urv_msg;
        }
        else{
            cancel_transaction();
        }
	
	
}


function get_unreconciled_transaction_ids_string($bank_account, $reconcile_date_)
{
    $a = array();
    
    $result = get_unreconciled_ids($bank_account, $reconcile_date_);
    while ($row = db_fetch($result)) {
        $a[] = $row['id'];
    } 
    
    $s = implode(",",$a);
    return $s;
}