<?php

namespace FAAPI;

$path_to_root = "../..";

include_once ($path_to_root . "/gl/includes/db/gl_db_currencies.inc");
// include_once($path_to_root . "/gl/includes/db/gl_db_rates.inc");
include_once ($path_to_root . "/includes/banking.inc");

class Dashboard {

    public function default_dashboard() {
        $info = Array();
        $begin = begin_month(Today());
        $begin1 = date2sql($begin);
        $today1 = date2sql(Today());
        $sql = "SELECT SUM(amount) AS total, c.class_name, c.ctype FROM
		" . TB_PREF . "gl_trans," . TB_PREF . "chart_master AS a, " . TB_PREF . "chart_types AS t, 
		" . TB_PREF . "chart_class AS c WHERE
		account = a.account_code AND a.account_type = t.id AND t.class_id = c.cid
		AND IF(c.ctype > 3, tran_date >= '$begin1', tran_date >= '0000-00-00') 
		AND tran_date <= '$today1' GROUP BY c.cid ORDER BY c.cid";
        $result = db_query($sql, "Dashboard Transactions could not be calculated");
        $i = 0;
        while ($myrow = db_fetch($result)) {
            if ($myrow['ctype'] > 3) {
                $info[] = array("description" => ($myrow['class_name']), "value1" => ($myrow['total']),"value2"=>$myrow['ctype'],"type"=>"");
            }
        }

        $response['items'] = $info;
        $response['incomplete_results'] = FALSE;
        $response['total_count'] = count($info);
        api_success_response(json_encode($response));
    }
    
    public function bank_summary() {
        $info = Array();
        $start_date = Today();
        $end_date = Today();
        if(!empty($_GET['start_date'])){
            $start_date = $_GET['start_date'];
        }
        if(!empty($_GET['end_date'])){
            $end_date = $_GET['end_date'];
        }
        $start_date = date2sql($start_date);
        $end_date = date2sql($end_date);
        $bank_accounts = get_bank_accounts();
        while($bank = db_fetch($bank_accounts)){
            $sql = "SELECT SUM(amount) Total FROM ".TB_PREF."bank_trans WHERE trans_date between '$start_date' AND '$end_date' "
                    . "AND amount > 0 AND bank_act=". db_escape($bank['id'])." GROUP BY bank_act";
            $result1 = db_query($sql);
            $debit = db_fetch($result1);
            
            $sql = "SELECT SUM(amount) Total FROM ".TB_PREF."bank_trans WHERE trans_date between '$start_date' AND '$end_date' "
                    . "AND amount < 0 AND bank_act=". db_escape($bank['id'])." GROUP BY bank_act";
            $result2 = db_query($sql);
            $credit = db_fetch($result2);
            $info[] = array("description" => ($bank['bank_account_name']), "value1" => ($debit['Total']),"value2"=>$credit['Total'],"type"=>"","param1"=>'');
            //die(json_encode($info));
        }
        $response['items'] = $info;
        $response['incomplete_results'] = FALSE;
        $response['total_count'] = count($info);
        api_success_response(json_encode($response));
    }

}
