<?php
/**********************************************************************
***********************************************************************/
//---------------------------------------------------------------------------------------------
function clear_dflt_curr_account($curr_code) {
	  $sql = "UPDATE ".TB_PREF."bank_accounts SET dflt_curr_act=0 WHERE bank_curr_code="
	  .db_escape($curr_code);
	  db_query($sql, "could not update default currency account");
}

function add_bank_account($account_code, $account_type, $bank_account_name,
	$bank_id, $bank_name, $bank_account_number, 
        $bank_address, $bank_curr_code, 
	$dflt_curr_act, $bank_charge_act, $printing_account_name, 
        $voucher_prefix, $internal)
{
    
	if($dflt_curr_act) 	// only one default account for any currency
	  clear_dflt_curr_account($bank_curr_code);

	$sql = "INSERT INTO ".TB_PREF."bank_accounts (
                        account_code, bank_id, 
                        bank_charge_act,account_type, 
                        bank_account_name, bank_name, 
                        bank_account_number, bank_address, 
                        bank_curr_code, dflt_curr_act,
                        printing_account_name, internal,
                        voucher_prefix)
            VALUES (".db_escape($account_code).", ".db_escape($bank_id).", "
                        .db_escape($bank_charge_act).", ".db_escape($account_type).", "
                        .db_escape($bank_account_name).", ".db_escape($bank_name).", "
                        .db_escape($bank_account_number).",".db_escape($bank_address).", "
                        .db_escape($bank_curr_code).", ".db_escape($dflt_curr_act).", "
                        .db_escape($printing_account_name).", ".db_escape($internal).", "
                        .db_escape($voucher_prefix).")";

	db_query($sql, "could not add a bank account for $account_code");
}

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

function update_bank_account($id, $account_code, $account_type, $bank_account_name, 
	$bank_id, $bank_name, $bank_account_number, 
        $bank_address, $bank_curr_code, 
        $dflt_curr_act, $bank_charge_act, $printing_account_name, 
        $voucher_prefix, $internal)
{
    
	if($dflt_curr_act) 	// only one default account for any currency
	  clear_dflt_curr_account($bank_curr_code);

	$sql = "UPDATE ".TB_PREF."bank_accounts	SET 
                    account_type = ".db_escape($account_type).",
                    account_code=".db_escape($account_code).",
                    bank_id = ".db_escape($bank_id).",
                    bank_charge_act=".db_escape($bank_charge_act).",    
                    bank_account_name=".db_escape($bank_account_name).", 
                    bank_name=".db_escape($bank_name).",
                    bank_account_number=".db_escape($bank_account_number).", 
                    bank_curr_code=".db_escape($bank_curr_code).",
                    bank_address=".db_escape($bank_address).",
                    dflt_curr_act=".db_escape($dflt_curr_act).", 
                    printing_account_name=".db_escape($printing_account_name).", 
                    internal=".db_escape($internal).", 
                    voucher_prefix=".db_escape($voucher_prefix)." 
            WHERE id = ".db_escape($id);

	db_query($sql, "could not update bank account for $account_code");
}

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

function delete_bank_account($id)
{
	$sql = "DELETE FROM ".TB_PREF."bank_accounts WHERE id=".db_escape($id);

	db_query($sql,"could not delete bank account for $id");
}


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

function get_bank_account($id)
{
	$sql = "SELECT * FROM ".TB_PREF."bank_accounts WHERE id=".db_escape($id);

	$result = db_query($sql, "could not retreive bank account for $id");

	return db_fetch($result);
}

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

function get_bank_accounts($show_inactive=false)
{
	$sql = "SELECT account.*, 
                    gl_account.account_name,
                    bank.value_name account_bank_name,
                    branch.branch_name 
            FROM ".TB_PREF."bank_accounts account 
                    INNER JOIN ".TB_PREF."chart_master gl_account ON 
                            account.account_code = gl_account.account_code 
                    LEFT JOIN ".TB_PREF."list_values bank ON 
                            account.bank_id = bank.id  
                    LEFT JOIN ".TB_PREF."bank_branches branch ON 
                            account.branch_id = branch.id  
            WHERE 1";
    
	if (!$show_inactive){
        $sql .= " AND !account.inactive";
    }
    
	$sql .= " ORDER BY account_code, bank_curr_code";

	return db_query($sql,"could not get bank accounts");
}

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

function get_bank_gl_account($id)
{
	$sql = "SELECT account_code FROM ".TB_PREF."bank_accounts WHERE id=".db_escape($id);

	$result = db_query($sql, "could not retreive bank account for $id");

	$bank_account = db_fetch($result);

	return $bank_account['account_code'];
}

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

function add_quick_entry($description, $type, $base_amount, $base_desc, $bal_type)
{
	$sql = "INSERT INTO ".TB_PREF."quick_entries (description, type, base_amount, base_desc, bal_type) 
	VALUES (".db_escape($description).", ".db_escape($type).", "
		.db_escape($base_amount).", ".db_escape($base_desc).", ".db_escape($bal_type).")";

	db_query($sql, "could not insert quick entry for $description");
}

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

function update_quick_entry($selected_id, $description, $type, $base_amount, $base_desc, $bal_type)
{
	$sql = "UPDATE ".TB_PREF."quick_entries	SET description = ".db_escape($description).",
		type=".db_escape($type).", base_amount=".db_escape($base_amount)
		.", base_desc=".db_escape($base_desc).", bal_type=".db_escape($bal_type)."
		WHERE id = ".db_escape($selected_id);

	db_query($sql, "could not update quick entry for $selected_id");
}

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

function delete_quick_entry($selected_id)
{
	$sql = "DELETE FROM ".TB_PREF."quick_entries WHERE id=".db_escape($selected_id);

	db_query($sql,"could not delete quick entry $selected_id");
}

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

function add_quick_entry_line($qid, $action, $dest_id, $amount, $dim, $dim2)
{
	$sql = "INSERT INTO ".TB_PREF."quick_entry_lines 
		(qid, action, dest_id, amount, dimension_id, dimension2_id) 
	VALUES 
		(".db_escape($qid).", ".db_escape($action).",".db_escape($dest_id).",
			".db_escape($amount).", ".db_escape($dim).", ".db_escape($dim2).")";

	db_query($sql, "could not insert quick entry line for $qid");
}

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

function update_quick_entry_line($selected_id, $qid, $action, $dest_id, $amount, $dim, $dim2)
{
	$sql = "UPDATE ".TB_PREF."quick_entry_lines SET qid = ".db_escape($qid)
		.", action=".db_escape($action).",
		dest_id=".db_escape($dest_id).", amount=".db_escape($amount)
		.", dimension_id=".db_escape($dim).", dimension2_id=".db_escape($dim2)." 
		WHERE id = ".db_escape($selected_id);

	db_query($sql, "could not update quick entry line for $selected_id");
}

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

function delete_quick_entry_line($selected_id)
{
	$sql = "DELETE FROM ".TB_PREF."quick_entry_lines WHERE id=".db_escape($selected_id);

	db_query($sql,"could not delete quick entry line $selected_id");
}
//---------------------------------------------------------------------------------------------


function has_quick_entries($type=null)
{
	$sql = "SELECT id FROM ".TB_PREF."quick_entries";
	if ($type != null)
		$sql .= " WHERE type=".db_escape($type);

	$result = db_query($sql, "could not retreive quick entries");
	return db_num_rows($result) > 0;
}

function get_quick_entries($type = null)
{
	$sql = "SELECT * FROM ".TB_PREF."quick_entries";
	if ($type != null)
		$sql .= " WHERE type=".db_escape($type);
	$sql .= " ORDER BY description";

	return db_query($sql, "could not retreive quick entries");
}

function get_quick_entry($selected_id)
{
	$sql = "SELECT * FROM ".TB_PREF."quick_entries WHERE id=".db_escape($selected_id);

	$result = db_query($sql, "could not retreive quick entry $selected_id");

	return db_fetch($result);
}	

function get_quick_entry_lines($qid)
{
	$sql = "SELECT ".TB_PREF."quick_entry_lines.*, ".TB_PREF."chart_master.account_name,
			".TB_PREF."tax_types.name as tax_name
		FROM ".TB_PREF."quick_entry_lines
		LEFT JOIN ".TB_PREF."chart_master ON
			".TB_PREF."quick_entry_lines.dest_id = ".TB_PREF."chart_master.account_code
		LEFT JOIN ".TB_PREF."tax_types ON
			".TB_PREF."quick_entry_lines.dest_id = ".TB_PREF."tax_types.id
		WHERE 
			qid=".db_escape($qid)." ORDER by id";

	return db_query($sql, "could not retreive quick entries");
}

function has_quick_entry_lines($qid)
{
	$sql = "SELECT id FROM ".TB_PREF."quick_entry_lines WHERE qid=".db_escape($qid);

	$result = db_query($sql, "could not retreive quick entries");
	return db_num_rows($result) > 0;
}

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

function get_quick_entry_line($selected_id)
{
	$sql = "SELECT * FROM ".TB_PREF."quick_entry_lines WHERE id=".db_escape($selected_id);

	$result = db_query($sql, "could not retreive quick entry for $selected_id");

	return db_fetch($result);
}

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

function get_max_reconciled($date, $bank_account)
{
	$date = date2sql($date);
	 // temporary fix to enable fix of invalid entries made in 2.2RC
	if ($date == 0) $date = INFINITE_END_DATE;

	$sql = "SELECT MAX(reconciled) as last_date,
			 SUM(IF(reconciled<='$date', amount, 0)) as end_balance,
			 SUM(IF(reconciled<'$date', amount, 0)) as beg_balance,
			 SUM(amount) as total
		FROM ".TB_PREF."bank_trans trans
		WHERE bank_act=".db_escape($bank_account); //." 
//                    AND trans_date <=".db_escape($date);
	//	." AND trans.reconciled IS NOT NULL";

	return db_query($sql,"Cannot retrieve reconciliation data");

}

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

function get_reconciled($date, $bank_account)
{
	$date = date2sql($date);
	 // temporary fix to enable fix of invalid entries made in 2.2RC
	if ($date == 0) $date = '0000-00-00';

	$sql = "SELECT MAX(reconciled) as last_date,
			 SUM(IF(reconciled<='$date', amount, 0)) as end_balance,
			 SUM(IF(reconciled<'$date', amount, 0)) as beg_balance,
			 SUM(amount) as total
		FROM ".TB_PREF."bank_trans trans
		WHERE bank_act=".db_escape($bank_account)." 
                    AND trans_date <=".db_escape($date);
	//	." AND trans.reconciled IS NOT NULL";

	return db_query($sql,"get_reconciled");

}

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

function get_ending_reconciled($bank_account, $bank_date)
{
	$sql = "SELECT ending_reconcile_balance
		FROM ".TB_PREF."bank_accounts WHERE id=".db_escape($bank_account)
		. " AND last_reconciled_date=".db_escape($bank_date);
	$result = db_query($sql,"Cannot retrieve last reconciliation");
	return db_fetch($result);
}

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

function get_statetment_reconciled_total($bank_account, $reconciled_date)
{
	$sql = "SELECT SUM(amount) reconciled_total,
                        COUNT(id) reconciled_rec_count 
                FROM ".TB_PREF."bank_trans 
                WHERE bank_act=".db_escape($bank_account). " AND 
                    reconciled=".db_escape(date2sql($reconciled_date));
        
	$result = db_query($sql,"get_statetment_reconciled_total");
	return db_fetch($result);
}

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

function get_statetment_unreconciled_total($unreconciled_ids)
{
	$sql = "SELECT SUM(amount) reconciled_total 
                FROM ".TB_PREF."bank_trans 
                WHERE id IN ($unreconciled_ids) ";
        
	$result = db_query($sql,"get_statetment_reconciled_total");
	return db_result_value($result, 'reconciled_total');
}

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


function get_sql_for_bank_account_reconcile($bank_account, $date)
{
	$sql = "SELECT	type, trans_no, ref, cheque_no, trans_date, 
				amount,	person_id, person_type_id, reconciled, id
		FROM ".TB_PREF."bank_trans
		WHERE ".TB_PREF."bank_trans.bank_act = ".db_escape($bank_account) . "
			AND (reconciled = ".db_escape(INFINITE_START_DATE)." OR reconciled = '0000-00-00' OR reconciled ='". date2sql($date) ."') 
                        AND amount != 0 
                        AND trans_date <= ".db_escape(date2sql($date))."  
		ORDER BY trans_date,".TB_PREF."bank_trans.id";
// or	ORDER BY reconciled desc, trans_date,".TB_PREF."bank_trans.id";
	return $sql;
}

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


function get_unreconciled_ids($bank_account, $reconcile_date_)
{
        $reconcile_date = date2sql($reconcile_date_);
        
	$sql = "SELECT	id
		FROM ".TB_PREF."bank_trans
		WHERE ".TB_PREF."bank_trans.bank_act = ".db_escape($bank_account) . "
			AND (reconciled = ".db_escape(INFINITE_START_DATE)." OR reconciled = '0000-00-00')
			AND (trans_date <= ".db_escape($reconcile_date)." )
		ORDER BY trans_date, id";
// or	ORDER BY reconciled desc, trans_date,".TB_PREF."bank_trans.id";
	return db_query($sql,"get_unreconciled_ids");
}

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

//function update_reconciled_values($reconcile_id, $reconcile_value, $reconcile_date, $end_balance, $bank_account,
//                                    $statement_beginning_balance, $statement_ending_balance)
//{
//    $user_id = $_SESSION['wa_current_user']->user;
//    $time = date('Y-m-d H:i:s');
//    
//	$sql = "UPDATE ".TB_PREF."bank_trans SET 
//                        reconciled = ".$reconcile_value."  
//                WHERE id=".db_escape($reconcile_id);
//
//  	db_query($sql, "Can't change reconciliation status");       
//        
//        //If the last record of a recociliation being removed then the header record will get deleted.
//        // update the bank account final values to latest considering future reconciliations too
//        $max_rec = get_max_reconciled(sql2date(INFINITE_END_DATE), $bank_account);
//        $sql2 = "UPDATE ".TB_PREF."bank_accounts SET 
//                    last_reconciled_date='".$max_rec['last_date']."',
//                    ending_reconcile_balance= ". db_escape($max_rec['$reconcile_date'])."
//            WHERE id=".db_escape($bank_account);
//        
//        
//            db_query($sql2,"Error updating reconciliation information");
//
//        $sql3 = "SELECT * 
//                FROM ".TB_PREF."bank_account_reconciliations 
//		WHERE account_id = ".db_escape($bank_account)." AND 
//                        reconciliation_date = ".db_escape(date2sql($reconcile_date));
//
//	$result = db_query($sql3, "could not retreive bank_account_reconciliations");
//        
//        
//        $sql5 = "SELECT 
//                        SUM(IF(amount > 0, amount, 0)) as debits,
//                        SUM(IF(amount < 0, amount, 0)) as credits 
//                FROM ".TB_PREF."bank_trans 
//                WHERE bank_act = ".db_escape($bank_account)." 
//                    AND  reconciled IS NULL 
//                    AND trans_date <= ".db_escape(date2sql($reconcile_date));
//
//	$result5 = db_query($sql5, "could not retreive bank_account_reconciliations");
//        $sum_row = db_fetch($result5);
//        
//        $rec_total_row = get_statetment_reconciled_total($bank_account, $reconcile_date);
//        $reconciled_amount = $rec_total_row['reconciled_total'];
//        $reconciled_rec_count = $rec_total_row['reconciled_rec_count'];
//        
//        if($reconciled_rec_count == 0){
//            $sql6 = "DELETE FROM ".TB_PREF."bank_account_reconciliations  
//                    WHERE account_id = ".db_escape($bank_account)." AND 
//                        reconciliation_date = ".db_escape(date2sql($reconcile_date));
//            db_query($sql6, "could not update bank_account_reconciliations");
//            
//            return array("success"=>true, "message"=>"");
//        }
//        
//        // save last reconcilation status (date, end balance)
//        $sql2 = "UPDATE ".TB_PREF."bank_accounts SET 
//                        last_reconciled_date='".date2sql($reconcile_date)."',
//                        ending_reconcile_balance=$end_balance
//                WHERE id=".db_escape($bank_account);
//        
//        
//        db_query($sql2,"Error updating reconciliation information");
//        
//        
////        $max_result = get_reconciled($reconcile_date, $bank_account);
////        $max_row = db_fetch($max_result);
////        if($max_row){
////            $account_balance = $max_row["total"];
////            $reconciled_amount = ($max_row["end_balance"]-$max_row["beg_balance"]);
////            $reconciled_difference = ($statement_ending_balance-$statement_beginning_balance) - $reconciled_amount;
////        }
////        else{
////            $account_balance = 0;
////            $reconciled_amount = 0;
////            $reconciled_difference = 0;
////        }
//
//        
//        $account_balance = get_balance_before_for_bank_account($bank_account, add_days($reconcile_date,1));
//        $reconciled_difference = ($statement_ending_balance-$statement_beginning_balance) - $reconciled_amount;
//        
//        $debits = round($sum_row['debits'],2);
//        $credits = -round($sum_row['credits'],2);
//        
//        $unrec_ids = get_unreconciled_transaction_ids_string($bank_account, $reconcile_date);
//        
//        if(db_num_rows($result) > 0){
//            $sql4 = "UPDATE ".TB_PREF."bank_account_reconciliations SET 
//                        statement_beginning_balance = ".db_escape($statement_beginning_balance).", 
//                        statement_ending_balance = ".db_escape($statement_ending_balance).", 
//                        account_balance = ".db_escape($account_balance).", 
//                        reconciled_amount = ".db_escape($reconciled_amount).", 
//                        reconciled_difference = ".db_escape($reconciled_difference).", 
//                        unreconciled_debits = ".db_escape($debits).", 
//                        unreconciled_credits = ".db_escape($credits).", 
//                        unreconciled_ids = ".db_escape($unrec_ids).", 
//                        updated_by = ".db_escape($user_id).", 
//                        updated_on = ".db_escape($time)." 
//                WHERE account_id = ".db_escape($bank_account)." AND 
//                        reconciliation_date = ".db_escape(date2sql($reconcile_date));
//        }
//        else{
//            $sql4 = "INSERT INTO ".TB_PREF."bank_account_reconciliations  
//                        (account_id, reconciliation_date,
//                        statement_beginning_balance, statement_ending_balance,
//                        account_balance, reconciled_amount, reconciled_difference,
//                        unreconciled_debits, unreconciled_credits, 
//                        unreconciled_ids,
//                        created_by, created_on) 
//                    VALUES (".db_escape($bank_account).", ".db_escape(date2sql($reconcile_date)).","
//                        .db_escape($statement_beginning_balance).",".db_escape($statement_ending_balance).","
//                        .db_escape($account_balance).",".db_escape($reconciled_amount).",".db_escape($reconciled_difference).","
//                        .db_escape($debits).",".db_escape($credits).","
//                        .db_escape($unrec_ids).","
//                        .db_escape($user_id).",".db_escape($time).")";
//        }
//        
//        db_query($sql4, "could not update bank_account_reconciliations");
//        
//        return array("success"=>true, "message"=>"");
//	
//}

function update_reconciled_values($reconcile_id, $reconcile_value, $reconcile_date, $end_balance, $bank_account,
                                    $statement_beginning_balance, $statement_ending_balance)
{
    $user_id = $_SESSION['wa_current_user']->user;
    $time = date('Y-m-d H:i:s');
    
	$sql = "UPDATE ".TB_PREF."bank_trans SET 
                        reconciled=".db_escape($reconcile_value)."  
                WHERE id=".db_escape($reconcile_id);

  	db_query($sql, "Can't change reconciliation status");       
        
        //If the last record of a recociliation being removed then the header record will get deleted.
        // update the bank account final values to latest considering future reconciliations too
        $max_rec_res = get_max_reconciled(sql2date(INFINITE_END_DATE), $bank_account);
        $max_rec = db_fetch($max_rec_res);
        $sql2 = "UPDATE ".TB_PREF."bank_accounts SET 
                    last_reconciled_date='".$max_rec['last_date']."',
                    ending_reconcile_balance= ". db_escape($max_rec['end_balance'])."
            WHERE id=".db_escape($bank_account);
        
        
            db_query($sql2,"Error updating reconciliation information");

        $sql3 = "SELECT * 
                FROM ".TB_PREF."bank_account_reconciliations 
		WHERE account_id = ".db_escape($bank_account)." AND 
                        reconciliation_date = ".db_escape(date2sql($reconcile_date));

	$result = db_query($sql3, "could not retreive bank_account_reconciliations");
        
        
        $sql5 = "SELECT 
                        SUM(IF(amount > 0, amount, 0)) as debits,
                        SUM(IF(amount < 0, amount, 0)) as credits 
                FROM ".TB_PREF."bank_trans 
                WHERE bank_act = ".db_escape($bank_account)." 
                    AND  reconciled = ".db_escape(INFINITE_START_DATE)." 
                    AND  trans_date <= ".db_escape(date2sql($reconcile_date));

	$result5 = db_query($sql5, "could not retreive bank_account_reconciliations");
        $sum_row = db_fetch($result5);
        
        $rec_total_row = get_statetment_reconciled_total($bank_account, $reconcile_date);
        $reconciled_amount = $rec_total_row['reconciled_total'];
            if ($reconciled_amount === null) {
                $reconciled_amount = 0;
            }
        $reconciled_rec_count = $rec_total_row['reconciled_rec_count'];
        
        if($reconciled_rec_count == 0){
            $sql6 = "DELETE FROM ".TB_PREF."bank_account_reconciliations  
                    WHERE account_id = ".db_escape($bank_account)." AND 
                        reconciliation_date = ".db_escape(date2sql($reconcile_date));
            db_query($sql6, "could not update bank_account_reconciliations");
            
            return array("success"=>true, "message"=>"");
        }
        
        // save last reconcilation status (date, end balance)
        $sql2 = "UPDATE ".TB_PREF."bank_accounts SET 
                        last_reconciled_date='".date2sql($reconcile_date)."',
                        ending_reconcile_balance=$end_balance
                WHERE id=".db_escape($bank_account);
        
        
        db_query($sql2,"Error updating reconciliation information");
        
        
//        $max_result = get_reconciled($reconcile_date, $bank_account);
//        $max_row = db_fetch($max_result);
//        if($max_row){
//            $account_balance = $max_row["total"];
//            $reconciled_amount = ($max_row["end_balance"]-$max_row["beg_balance"]);
//            $reconciled_difference = ($statement_ending_balance-$statement_beginning_balance) - $reconciled_amount;
//        }
//        else{
//            $account_balance = 0;
//            $reconciled_amount = 0;
//            $reconciled_difference = 0;
//        }

        
        $account_balance = get_balance_before_for_bank_account($bank_account, add_days($reconcile_date,1));
        $reconciled_difference = ($statement_ending_balance-$statement_beginning_balance) - $reconciled_amount;
        
        $debits = round($sum_row['debits'],2);
        $credits = -round($sum_row['credits'],2);
        
        $unrec_ids = get_unreconciled_transaction_ids_string($bank_account, $reconcile_date);
        
        if(db_num_rows($result) > 0){
            $sql4 = "UPDATE ".TB_PREF."bank_account_reconciliations SET 
                        statement_beginning_balance = ".db_escape($statement_beginning_balance).", 
                        statement_ending_balance = ".db_escape($statement_ending_balance).", 
                        account_balance = ".db_escape($account_balance).", 
                        reconciled_amount = ".db_escape($reconciled_amount).", 
                        reconciled_difference = ".db_escape($reconciled_difference).", 
                        unreconciled_debits = ".db_escape($debits).", 
                        unreconciled_credits = ".db_escape($credits).", 
                        unreconciled_ids = ".db_escape($unrec_ids).", 
                        updated_by = ".db_escape($user_id).", 
                        updated_on = ".db_escape($time)." 
                WHERE account_id = ".db_escape($bank_account)." AND 
                        reconciliation_date = ".db_escape(date2sql($reconcile_date));
        }
        else{
            $sql4 = "INSERT INTO ".TB_PREF."bank_account_reconciliations  
                        (account_id, reconciliation_date,
                        statement_beginning_balance, statement_ending_balance,
                        account_balance, reconciled_amount, reconciled_difference,
                        unreconciled_debits, unreconciled_credits, 
                        unreconciled_ids,
                        created_by, created_on) 
                    VALUES (".db_escape($bank_account).", ".db_escape(date2sql($reconcile_date)).","
                        .db_escape($statement_beginning_balance).",".db_escape($statement_ending_balance).","
                        .db_escape($account_balance).",".db_escape($reconciled_amount).",".db_escape($reconciled_difference).","
                        .db_escape($debits).",".db_escape($credits).","
                        .db_escape($unrec_ids).","
                        .db_escape($user_id).",".db_escape($time).")";
        }
        
        db_query($sql4, "could not update bank_account_reconciliations");
        
        return array("success"=>true, "message"=>"");
	
}

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

function get_default_bank_account($curr)
{
	/* default bank account is selected as first found account from:
		. default account in $curr if any
		. first defined account in $curr if any
		. default account in home currency
		. first defined account in home currency
	*/
	$home_curr = get_company_pref('curr_default');

	$sql = "SELECT b.*, b.bank_curr_code='$home_curr' as fall_back FROM "
		.TB_PREF."bank_accounts b"
		." WHERE b.bank_curr_code=".db_escape($curr)
		." OR b.bank_curr_code='$home_curr'
		ORDER BY fall_back, dflt_curr_act desc";

	$result = db_query($sql, "could not retreive default bank account");

	return db_fetch($result);
}

function get_default_customer_bank_account($cust_id)
{
	$sql = "SELECT curr_code FROM ".TB_PREF."debtors_master WHERE debtor_no=".db_escape($cust_id);
	$result = db_query($sql, "could not retreive default customer currency code");
	$row = db_fetch_row($result);
	$ba = get_default_bank_account($row[0]);
	return $ba['id'];
}

function get_default_supplier_bank_account($supplier_id)
{
	$sql = "SELECT curr_code FROM ".TB_PREF."suppliers WHERE supplier_id=".db_escape($supplier_id);
	$result = db_query($sql, "could not retreive default supplier currency code");
	$row = db_fetch_row($result);
	$ba = get_default_bank_account($row[0]);
	return $ba['id'];
}
//---------------------------------------------------------------------------------------------
//
//	This function returns current allowed bank payment limit, or null if limit is not set.
//	As of FA 2.3 check is done only on cash account, for which limit is bank amount as of the date selected.
//
function get_bank_account_limit($account, $date, $user=null)
{
//	$user = current_user();

    //Updated by Nalin on Sampath's request on 2018-10-29
    return null;
	$bankacc = get_bank_account($account);
	if ($bankacc['account_type'] != BT_CASH){
		return null;
        }
        else{
            return max(0, get_balance_before_for_bank_account($account, add_days($date,1))); // in case of manco made before the check was implemented
        }
}

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

function get_bank_account_unreconciled_balance($bank_account)
{
	$date = Today();
        $date = date2sql($date);

	$sql = "SELECT SUM(amount) balance 
                FROM ".TB_PREF."bank_trans 
                WHERE bank_act=".db_escape($bank_account)." 
                    AND trans_date <= ".db_escape($date);

	$result = db_query($sql,"get_bank_account_balance");
        
        $row = db_fetch($result);
        If(isset($row['balance'])){
            return $row['balance'];
        }
        else{
            return 0;
        }

}



function check_future_bank_reconciliations($bank_account, $reconcile_date)
{
     $sql = "SELECT COUNT(id) future_recs  
                FROM ".TB_PREF."bank_account_reconciliations 
		WHERE account_id = ".db_escape($bank_account)." AND 
                        reconciliation_date > ".db_escape(date2sql($reconcile_date));
     
     $result = db_query($sql, "check_future_bank_reconciliations");
     $future_recs = db_result_value($result, "future_recs");
     
     if($future_recs > 0){
         return true;
     }
     else{
         return false;
     }
}

function get_last_bank_reconciliation_header($bank_account)
{
     $sql = "SELECT *   
                FROM ".TB_PREF."bank_account_reconciliations 
		WHERE account_id = ".db_escape($bank_account)." 
                ORDER BY reconciliation_date DESC 
                LIMIT 1";
     
     $result = db_query($sql, "get_last_bank_reconciliation_header"); 
     return db_fetch($result);
}


function check_bank_account_voucher_prefix_duplications($id, $voucher_prefix) {
    $sql = "SELECT * 
            FROM ".TB_PREF."bank_accounts 
            WHERE voucher_prefix = ".db_escape($voucher_prefix);
    
        if ($id > 0) {
            $sql .= " AND id <> ".db_escape($id);
        }
    
	$result = db_query($sql, "check_bank_account_voucher_prefix_duplications");
	$row = db_fetch($result);
        
        if (is_array($row)) {
            return array('success' => false, 'message' => 'Voucher prefix cannot be duplicated. 
                                                           Entered voucher prefix already used in record #'.$row['id'].'.');
        } else {
            return array('success' => true, 'message' => '');
        }
}
