#!/usr/bin/perl



sub get_client_saldo {

	my ($oper_id,$client_id) = @_;

        my ($first_balance,$first_balance_date,$currency) = $dbh->selectrow_array("SELECT first_balance,first_balance_date,currency_type FROM base_clients WHERE oper_id='$oper_id' AND client_id='$client_id'");

        my $sql = "SELECT sum(bill_sum*(SELECT base_currency_history.rate FROM base_currency_history WHERE base_currency_history.currency_from = bill_bills.currency_type  AND base_currency_history.currency_to = '$currency'  AND base_currency_history.date <= bill_bills.bill_date  order by base_currency_history.date desc limit 1)) FROM bill_bills WHERE bill_type='invoice' AND oper_id='$oper_id' AND client_id='$client_id' AND bill_date >='$first_balance_date' ";

        my ($bk_saldo_bills ) = $dbh->selectrow_array($sql);


        $sql = "SELECT sum(payment_sum*(SELECT base_currency_history.rate FROM base_currency_history WHERE base_currency_history.currency_from = payment_payments.currency_type  AND base_currency_history.currency_to = '$currency'  AND base_currency_history.date <= payment_payments.income_date   order by base_currency_history.date desc limit 1)) FROM payment_payments WHERE oper_id='$oper_id' AND client_id='$client_id' AND income_date >='$first_balance_date'  ";

        my ($bk_saldo_payments ) = $dbh->selectrow_array($sql);


	#print "first_balance=$first_balance\nbk_saldo_payments=$bk_saldo_payments\nbk_saldo_bills=$bk_saldo_bills\n";

        my $bk_balance=$first_balance + $bk_saldo_payments - $bk_saldo_bills;

	return $bk_balance;
}

1;

