<?php

class Report {

    private $year_id;
    private $year_id_actual;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
        $this->year_id = Session::getCurrentYearID();
        $this->year_id_actual = Session::getCurrentYearIDActual();
        $this->permissions = Session::getPermissionsObject();
    }

    public function setData($data) {
        $this->info = $data;

        return $this;
    }

    public function retrieveInv($back_up = false) {
        $data = array();
        $query = $this->db->query('SELECT
                                            Customer_Name AS Name,
                                            Customer_ID AS ID
                                    FROM  
                                            tbl_customers
                                    WHERE
                                        Status_ID = 1
                ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    public function retrieveInvByCus($cus_id, $back_up = false) {
        $data = array();
        $cond = $back_up ? '' : ' and is_actual = 0';
        $query = $this->db->query('SELECT
                                            Invoice_Net_Total-Invoice_Paid_Amount-Return_Invoice_Total AS Unpaid,
                                            Invoice_Due_Date,
                                            Invoice_ID,
                                            Invoice_Currency
                                        FROM 
                                            tbl_invoices 
                                        WHERE 
                                            Invoice_Status != 2 
                                            AND Invoice_Due_Date < CURRENT_DATE AND Customer_ID = "' . $cus_id . '"

                    ' . $cond);
        while ($row = $this->db->assoc($query)) {
            //            if ($back_up) {
            //                $query2 = $this->db->query('SELECT
            //                                                Net_Total-Paid_Amount-Return_Total AS Unpaid,
            //                                                Due_Date AS Invoice_Due_Date,
            //                                                Currency_ID AS Invoice_Currency,
            //                                                Purchase_Invoice_ID AS Invoice_ID
            //                                            FROM 
            //                                                tbl_mgt_logs_backups 
            //                                            WHERE 
            //                                                Purchase_Invoice_ID = "' . $row['Invoice_ID'] . '"
            //                                            AND 
            //                                                Is_Purchase = 0
            //
            //                        ');
            //                $row2 = $this->db->assoc($query2);
            //                if (count($row2) > 0) {
            //                    $row = $row2;
            //                }
            //            }
            $data[] = $row;
        }
        //        if ($back_up) {
        //            $query3 = $this->db->query('SELECT
        //                                            Net_Total-Paid_Amount-Return_Total AS Unpaid,
        //                                            Due_Date AS Invoice_Due_Date,
        //                                            Currency_ID AS Invoice_Currency,
        //                                            Purchase_Invoice_ID AS Invoice_ID
        //                                        FROM 
        //                                            tbl_mgt_logs_backups 
        //                                        WHERE  
        //                                            (Net_Total-Paid_Amount-Return_Total) > 0 
        //                                        AND 
        //                                            Due_Date < CURRENT_DATE 
        //                                        AND 
        //                                            Customer_Supplier_ID = "' . $cus_id . '"
        //                                        AND 
        //                                            Is_Purchase = 0
        //                                        AND 
        //                                            Purchase_Invoice_ID = 0
        //
        //                ');
        //            while ($row3 = $this->db->assoc($query3))
        //                $data[] = $row3;
        //        }
        return $data;
    }

    public function retrievePurchases($back_up = false) {
        $data = array();

        $query = $this->db->query('SELECT
                                                                                    Supplier_Name AS Name,
                                                                                    Supplier_ID AS ID
                                                                            FROM  
                                                                                    tbl_stock_suppliers
                                                                            WHERE
                                            Status_ID = 1
                    ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    public function retrievePurchaseBySupplier($supp_id, $back_up = false) {
        $data = array();
        $cond = $back_up ? '' : ' and is_actual = 0';
        $query = $this->db->query('SELECT
                                            Purchase_Net_Total-Purchase_Paid_Amount-Return_Purchase_Total AS Unpaid,
                                            Purchase_Due_Date AS Invoice_Due_Date,
                                            Currency_ID AS Invoice_Currency,
                                            Purchase_ID AS Invoice_ID
                                        FROM 
                                            tbl_inventory_purchases 
                                        WHERE 
                                            (Purchase_Net_Total-Purchase_Paid_Amount-Return_Purchase_Total) > 0 AND Purchase_Due_Date < CURRENT_DATE AND Supplier_ID = "' . $supp_id . '"

                    ' . $cond);
        while ($row = $this->db->assoc($query)) {
            //            if ($back_up) {
            //                $query2 = $this->db->query('SELECT
            //                                                Net_Total-Paid_Amount-Return_Total AS Unpaid,
            //                                                Due_Date AS Invoice_Due_Date,
            //                                                Currency_ID AS Invoice_Currency,
            //                                                Purchase_Invoice_ID AS Invoice_ID
            //                                            FROM 
            //                                                tbl_mgt_logs_backups 
            //                                            WHERE 
            //                                                Purchase_Invoice_ID = "' . $row['Invoice_ID'] . '"
            //                                            AND 
            //                                                Is_Purchase = 1
            //
            //                        ');
            //                $row2 = $this->db->assoc($query2);
            //                if (count($row2) > 0) {
            //                    $row = $row2;
            //                }
            //            }
            $data[] = $row;
        }
        //        if ($back_up) {
        //            $query3 = $this->db->query('SELECT
        //                                            Net_Total-Paid_Amount-Return_Total AS Unpaid,
        //                                            Due_Date AS Invoice_Due_Date,
        //                                            Currency_ID AS Invoice_Currency,
        //                                            Purchase_Invoice_ID AS Invoice_ID
        //                                        FROM 
        //                                            tbl_mgt_logs_backups 
        //                                        WHERE  
        //                                            (Net_Total-Paid_Amount-Return_Total) > 0 
        //                                        AND 
        //                                            Due_Date < CURRENT_DATE 
        //                                        AND 
        //                                            Customer_Supplier_ID = "' . $supp_id . '"
        //                                        AND 
        //                                            Is_Purchase = 1
        //                                        AND 
        //                                            Purchase_Invoice_ID = 0
        //
        //                ');
        //            while ($row3 = $this->db->assoc($query3))
        //                $data[] = $row3;
        //        }
        return $data;
    }

    public function unagedInvoices($id, $is_purchase, $back_up = false) {
        $cond = $back_up ? '' : ' and is_actual = 0';
        $total_upaid = 0.0;
        if ($is_purchase == 1) {
            $query = $this->db->query('SELECT
                                            Purchase_Net_Total-Purchase_Paid_Amount-Return_Purchase_Total AS Unpaid,
                                            Currency_ID AS Invoice_Currency,
                                            Purchase_ID AS Invoice_ID
                                        FROM 
                                            tbl_inventory_purchases 
                                        WHERE 
                                            (Purchase_Net_Total-Purchase_Paid_Amount-Return_Purchase_Total) > 0 
                                            AND Purchase_Due_Date >= CURRENT_DATE AND Supplier_ID = "' . $id . '"

                    ' . $cond);
        } else {
            $query = $this->db->query('SELECT
                                            Invoice_Net_Total-Invoice_Paid_Amount-Return_Invoice_Total AS Unpaid,
                                            Invoice_ID,
                                            Invoice_Currency
                                        FROM 
                                            tbl_invoices 
                                        WHERE 
                                            Invoice_Status != 2 AND Invoice_Due_Date >= CURRENT_DATE
                                            AND Customer_ID = "' . $id . '"

                    ' . $cond);
        }
        while ($row = $this->db->assoc($query)) {
            if ($back_up) {
                //                $query2 = $this->db->query('SELECT
                //                                                Net_Total-Paid_Amount-Return_Total AS Unpaid,
                //                                                Currency_ID AS Invoice_Currency,
                //                                                Purchase_Invoice_ID AS Invoice_ID
                //                                            FROM 
                //                                                tbl_mgt_logs_backups 
                //                                            WHERE 
                //                                                Purchase_Invoice_ID = "' . $row['Invoice_ID'] . '"
                //                                            AND 
                //                                                Is_Purchase = 1
                //
                //                        ');
                //                $row2 = $this->db->assoc($query2);
                //                if (count($row2) > 0) {
                //                    $total_upaid += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Invoice_Currency'], $row2['Unpaid']);
                //                }
                //            } else
                $total_upaid += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Invoice_Currency'], $row['Unpaid']);
            }
            //        if ($back_up) {
            //            $query3 = $this->db->query('SELECT
            //                                            Net_Total-Paid_Amount-Return_Total AS Unpaid,
            //                                            Currency_ID AS Invoice_Currency,
            //                                            Purchase_Invoice_ID AS Invoice_ID
            //                                        FROM 
            //                                            tbl_mgt_logs_backups 
            //                                        WHERE  
            //                                            (Net_Total-Paid_Amount-Return_Total) > 0 
            //                                        AND 
            //                                            Due_Date < CURRENT_DATE 
            //                                        AND 
            //                                            Customer_Supplier_ID = "' . $id . '"
            //                                        AND 
            //                                            Is_Purchase = "' . $is_purchase . '"
            //                                        AND 
            //                                            Purchase_Invoice_ID = 0
            //
            //                ');
            //            while ($row3 = $this->db->assoc($query3))
            //                $total_upaid += CurrencyFactory::returnPriceInDefaultCurrencyValue($row3['Invoice_Currency'], $row3['Unpaid']);
        }
        return $total_upaid;
    }

    public function agingReport($supplier = false, $back_up = false) {
        $date = Date::getToday(); //to return the current date
        if ($supplier)
            $inv_data = self::retrievePurchases($back_up);
        else
            $inv_data = self::retrieveInv($back_up);
        $result = array();
        $total_unaged = 0.0;
        $total_m1 = 0.0;
        $total_m2 = 0.0;
        $total_m3 = 0.0;
        $total_m4 = 0.0;
        $total_more = 0.0;
        $total_balance = 0.0;
        for ($i = 0; $i < count($inv_data); $i++) {
            $f1 = '';
            $f2 = '';
            $f3 = '';
            $f4 = '';
            $f5 = '';
            //for loop on all invoices
            $final = array();
            if ($supplier) {
                //must finish from here add unpaid unaged to the array
                $unaged = self::unagedInvoices($inv_data[$i]['ID'], 1, $back_up);
                $cus_data = self::retrievePurchaseBySupplier($inv_data[$i]['ID'], $back_up); //returns all delayed inv to a definite supplier
            } else {
                $unaged = self::unagedInvoices($inv_data[$i]['ID'], 0, $back_up);
                $cus_data = self::retrieveInvByCus($inv_data[$i]['ID'], $back_up); //returns all delayed inv to a definite customer
            }
            $total_unaged += $unaged;
            $balance = $unaged;

            for ($j = 0; $j < count($cus_data); $j++) {
                $diff = date_diff(date_create($cus_data[$j]['Invoice_Due_Date']), date_create($date)); // to calculate the remaining                                                                                                              days from due date to now
                $due = $diff->format("%a");
                //if duedate have passed before now
                //m1,m2,m3,more just to know the period of latency
                $balance += CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                if ($due < 30) {
                    $m1 = CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                    $m2 = '';
                    $m3 = '';
                    $m4 = '';
                    $more = '';
                    $f1 += $m1;
                    $total_m1 += $m1;
                } else if ($due > 29 and $due < 60) {
                    $m1 = '';
                    $m2 = CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                    $m3 = '';
                    $m4 = '';
                    $more = '';
                    $f2 += $m2;
                    $total_m2 += $m2;
                } else if ($due > 59 and $due < 90) {
                    $m1 = '';
                    $m2 = '';
                    $m3 = CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                    $m4 = '';
                    $more = '';
                    $f3 += $m3;
                    $total_m3 += $m3;
                } else if ($due > 89 and $due < 120) {
                    $m1 = '';
                    $m2 = '';
                    $m3 = '';
                    $m4 = CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                    $more = '';
                    $f4 += $m4;
                    $total_m4 += $m4;
                } else {
                    $m1 = '';
                    $m2 = '';
                    $m3 = '';
                    $m4 = '';
                    $more = CurrencyFactory::returnPriceInDefaultCurrencyValue($cus_data[$j]['Invoice_Currency'], $cus_data[$j]['Unpaid']);
                    $f5 += $more;
                    $total_more += $more;
                }
            }
            $temp = array();
            if ($unaged > 0)
                $unaged = round($unaged, 3) . '->' . round(($unaged / $balance) * 100, 3) . '%';
            else
                $unaged = "0->0%";
            if ($f1 > 0)
                $f1 = round($f1, 3) . '->' . round(($f1 / $balance) * 100, 3) . '%';
            else
                $f1 = "0->0%";
            if ($f2 > 0)
                $f2 = round($f2, 3) . '->' . round(($f2 / $balance) * 100, 3) . '%';
            else
                $f2 = "0->0%";
            if ($f3 > 0)
                $f3 = round($f3, 3) . '->' . round(($f3 / $balance) * 100, 3) . '%';
            else
                $f3 = "0->0%";
            if ($f4 > 0)
                $f4 = round($f4, 3) . '->' . round(($f4 / $balance) * 100, 3) . '%';
            else
                $f4 = "0->0%";
            if ($f5 > 0)
                $f5 = round($f5, 3) . '->' . round(($f5 / $balance) * 100, 3) . '%';
            else
                $f5 = "0->0%";
            if ($balance > 0) {
                $dat = array('Current' => $unaged,
                    '<30' => $f1,
                    '<60' => $f2,
                    '<90' => $f3,
                    '<120' => $f4,
                    'More' => $f5
                );
                $merged = array_merge($temp, $dat);
                array_push($final, $merged);
                $add = array(
                    'Customer_ID' => $inv_data[$i]['ID'],
                    'Customer_Name' => ucwords($inv_data[$i]['Name']),
                    'Balance' => round($balance, 3)
                );
                $total_balance += $balance;
                $merge = array_merge($final, $add);
                array_push($result, $merge);
            }
        }
        if ($total_unaged > 0)
            $total_unaged = round($total_unaged, 3) . '->' . round(($total_unaged / $total_balance) * 100, 3) . '%';
        else
            $total_unaged = "0->0%";
        if ($total_m1 > 0)
            $total_m1 = round($total_m1, 3) . '->' . round(($total_m1 / $total_balance) * 100, 3) . '%';
        else
            $total_m1 = "0->0%";
        if ($total_m2 > 0)
            $total_m2 = round($total_m2, 3) . '->' . round(($total_m2 / $total_balance) * 100, 3) . '%';
        else
            $total_m2 = "0->0%";
        if ($total_m3 > 0)
            $total_m3 = round($total_m3, 3) . '->' . round(($total_m3 / $total_balance) * 100, 3) . '%';
        else
            $total_m3 = "0->0%";
        if ($total_m4 > 0)
            $total_m4 = round($total_m4, 3) . '->' . round(($total_m4 / $total_balance) * 100, 3) . '%';
        else
            $total_m4 = "0->0%";
        if ($total_more > 0)
            $total_more = round($total_more, 3) . '->' . round(($total_more / $total_balance) * 100, 3) . '%';
        else
            $total_more = "0->0%";

        $result ['Total_Balance'] = round($total_balance, 3);
        $result ['Total_Current'] = $total_unaged;
        $result ['Total_M1'] = $total_m1;
        $result ['Total_M2'] = $total_m2;
        $result ['Total_M3'] = $total_m3;
        $result ['Total_M4'] = $total_m4;
        $result ['Total_More'] = $total_more;

        return $result;
    }

    //    public function viewJVs($back_up = false) {
    //        $data = array();
    //        if ($back_up)
    //            $table = 'tbl_mgt_logs';
    //        else
    //            $table = 'tbl_accounting_transactions';
    //        $query = $this->db->query('SELECT Distinct JV_ID FROM ' . $table . ' ORDER BY JV_ID');
    //        while ($row = $this->db->assoc($query))
    //            $data[] = $row;
    //        return $data;
    //    }
    //    public function retrieveTransactionsByDate($from_date, $to_date, $from_jv, $to_jv, $back_up = false) {
    //        //this will return all transactions on this date and the total debit and total credit in the default currency
    //        $data = array();
    //        $condition = '';
    ////        if(!is_null($date))
    ////            $condition .= 'AND d.Transaction_Date = "' .$date.'"';
    //        if (!is_null($from_date) and ! is_null($to_date))
    //            $condition .= 'AND d.Transaction_Date >= "' . $from_date . '" AND d.Transaction_Date <= "' . $to_date . '"';
    //        if (!is_null($from_jv) and ! is_null($to_jv))
    //            $condition .= 'AND d.JV_ID >= "' . $from_jv . '" AND d.JV_ID <= "' . $to_jv . '"';
    //        $debit = 0;
    //        $credit = 0;
    //        $year_id = self::getYearID(substr($from_date, 0, 4));
    //        //we have to calculate them in this function since if in daily journal we are unsetting some elements some data will be lost, 
    //        //so this is the only way to keep the results
    //        $query = $this->db->query('SELECT 
    //                                        d.*,
    //                                        CONCAT(e.Employee_FirstName," ",e.Employee_MiddleName," ",e.Employee_LastName) AS Employee_Name,
    //                                        LEFT(d.Transaction_Type,1) as Type,
    //                                        c.Currency_Symbol
    //                                    FROM 
    //                                        tbl_accounting_transactions d 
    //                                    LEFT JOIN
    //                                        tbl_common_users u
    //                                    ON
    //                                        u.User_ID =  d.Logged_ID
    //                                    LEFT JOIN
    //                                        tbl_hrm_employee e
    //                                    ON
    //                                        e.Employee_ID =  u.Employee_ID
    //                                    LEFT JOIN 
    //                                        tbl_common_currency c
    //                                    ON 
    //                                        c.Currency_ID = d.Currency_ID
    //                                    WHERE 
    //                                        current_year_id = "' . $year_id . '" ' . $condition . '
    //                                    ORDER BY 
    //                                        d.Transaction_ID
    //                   ');
    //        while ($row = $this->db->assoc($query)) {
    //            $data[] = $row;
    //            if ($row['Transaction_Type'] == 'Debit')
    //                $debit += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Transaction_Amount']);
    //            else
    //                $credit += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Transaction_Amount']);
    //        }
    //        if ($back_up) {
    //            $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
    //            $query2 = $this->db->query('SELECT 
    //                                            d.*,
    //                                            CONCAT(e.Employee_FirstName," ",e.Employee_MiddleName," ",e.Employee_LastName) AS Employee_Name,
    //                                            LEFT(d.Transaction_Type,1) as Type,
    //                                            c.Currency_Symbol
    //                                        FROM 
    //                                            tbl_mgt_logs d 
    //                                        LEFT JOIN
    //                                            tbl_common_users u
    //                                        ON
    //                                            u.User_ID =  d.Logged_ID
    //                                        LEFT JOIN
    //                                            tbl_hrm_employee e
    //                                        ON
    //                                            e.Employee_ID =  u.Employee_ID
    //                                        LEFT JOIN 
    //                                            tbl_common_currency c
    //                                        ON 
    //                                            c.Currency_ID = d.Currency_ID
    //                                        WHERE 
    //                                            current_year_id = "' . $year_id_actual . '" ' . $condition . '
    //                                        ORDER BY 
    //                                            d.Transaction_ID
    //                       ');
    //            while ($row2 = $this->db->assoc($query2)) {
    //                $row2['JV_ID'] .= '-Actual';
    //                $data[] = $row2;
    //                if ($row2['Transaction_Type'] == 'Debit')
    //                    $debit += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'], $row2['Transaction_Amount']);
    //                else
    //                    $credit += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'], $row2['Transaction_Amount']);
    //            }
    //        }
    //        array_push($data, $debit, $credit);
    //        return $data;
    //    }
    //    public function retrieveDebits($date, $before = false) {
    //        $data = array();
    //        $condition = '';
    //        if ($before)
    //            $condition .= ' AND d.Transaction_Date < "' . $date . '"';
    //        else
    //            $condition .= ' AND d.Transaction_Date >= "' . $date . '"';
    //        $query = $this->db->query('SELECT 
    //										d.Transaction_Date,
    //										a.Account_Name,
    //										d.Transaction_Account,
    //										d.Currency_ID,
    //										d.Transaction_Amount AS Debit 
    //									FROM 
    //										tbl_accounting_transactions d 
    //									LEFT JOIN
    //										tbl_chart_of_accounts a
    //									ON
    //										a.Account_Code =  d.Transaction_Account
    //									WHERE 
    //										d.Transaction_Type = "Debit" ' . $condition . '
    //									order by (case when left(d.Transaction_Account, 5) not like "[^0-9]" then left(d.Transaction_Account, 5)
    //												   when left(d.Transaction_Account, 4) not like "[^0-9]" then left(d.Transaction_Account, 4)
    //												   when left(d.Transaction_Account, 3) not like "[^0-9]" then left(d.Transaction_Account, 3) 
    //												   when left(d.Transaction_Account, 2) not like "[^0-9]" then left(d.Transaction_Account, 2) 
    //												   when left(d.Transaction_Account, 1) not like "[^0-9]" then left(d.Transaction_Account, 1) 
    //											   end), d.Transaction_Account
    //									');
    //        while ($row = $this->db->assoc($query))
    //            $data[] = $row;
    //        return $data;
    //    }
    //    public function retrieveCredits($date, $before = false) {
    //        $data = array();
    //        $condition = '';
    //        if ($before)
    //            $condition .= ' AND c.Transaction_Date < "' . $date . '"';
    //        else
    //            $condition .= ' AND c.Transaction_Date >= "' . $date . '"';
    //        $query = $this->db->query('SELECT 
    //										c.Transaction_Date,
    //										a.Account_Name,
    //										c.Transaction_Account,
    //										c.Currency_ID,
    //										c.Transaction_Amount AS Credit
    //									FROM 
    //										tbl_accounting_transactions c
    //									LEFT JOIN
    //										tbl_chart_of_accounts a
    //									ON
    //										a.Account_Code =  c.Transaction_Account
    //									WHERE 
    //										c.Transaction_Type = "Credit" ' . $condition . '
    //									order by (case when left(c.Transaction_Account, 5) not like "[^0-9]" then left(c.Transaction_Account, 5)
    //												   when left(c.Transaction_Account, 4) not like "[^0-9]" then left(c.Transaction_Account, 4)
    //												   when left(c.Transaction_Account, 3) not like "[^0-9]" then left(c.Transaction_Account, 3) 
    //												   when left(c.Transaction_Account, 2) not like "[^0-9]" then left(c.Transaction_Account, 2) 
    //												   when left(c.Transaction_Account, 1) not like "[^0-9]" then left(c.Transaction_Account, 1) 
    //											   end), c.Transaction_Account
    //									');
    //        while ($row = $this->db->assoc($query))
    //            $data[] = $row;
    //        return $data;
    //    }
    //    public function retrieveTransactionsByCode($account_code, $from_date = null, $to_date = null) {
    //        $data = array();
    //        $condition = '';
    //        if (!is_null($from_date) and ! is_null($to_date))
    //            $condition .= ' AND t.Transaction_Date >= "' . $from_date . '" AND t.Transaction_Date<= "' . $to_date . '"';
    //        $query = $this->db->query('SELECT 
    //										t.Currency_ID,
    //										t.Transaction_Reference,
    //										t.Transaction_Type,
    //										t.Transaction_Amount,
    //										t.Transaction_Date, 
    //										t.Transaction_Description, 
    //										c.*
    //									FROM 
    //										tbl_accounting_transactions t
    //									LEFT JOIN 
    //										tbl_common_currency c
    //									ON 
    //										c.Currency_ID = t.Currency_ID
    //									WHERE 
    //										t.Transaction_Account = "' . $account_code . '" 
    //									ORDER BY 
    //										t.Transaction_Date 
    //									DESC');
    //        while ($row = $this->db->assoc($query)) {
    //            $data[] = $row;
    //        }
    //        return $data;
    //    }
    //    public function returnGeneralLedger($account_code) {
    //        $default = $this->db->query('SELECT 
    //									d.*,
    //									c.*
    //								FROM 
    //									tbl_default_currency d
    //								LEFT JOIN 
    //									tbl_common_currency c
    //								ON 
    //									c.Currency_ID = d.Currency_ID
    //								WHERE 
    //									d.id = 1 ');
    //        $default_row = $this->db->assoc($default);
    //        $default_currency = $default_row['Currency_Symbol'];
    //        $balance = 0;
    //        $sum_credit = 0;
    //        $sum_debit = 0;
    //        $arr = self::retrieveTransactionsByCode($account_code);
    //        for ($i = 0; $i < count($arr); $i++) {
    //            //$arr[$i]['Transaction_Amount'] = CurrencyFactory::returnPriceInDefaultCurrencyValue($arr[$i]['Currency_ID'],$arr[$i]['Transaction_Amount']);
    //            if ($arr[$i]['Transaction_Type'] == 'Credit') {
    //                $balance -= CurrencyFactory::returnPriceInDefaultCurrencyValue($arr[$i]['Currency_ID'], $arr[$i]['Transaction_Amount']);
    //                $sum_credit += CurrencyFactory::returnPriceInDefaultCurrencyValue($arr[$i]['Currency_ID'], $arr[$i]['Transaction_Amount']);
    //            } else {
    //                $balance += CurrencyFactory::returnPriceInDefaultCurrencyValue($arr[$i]['Currency_ID'], $arr[$i]['Transaction_Amount']);
    //                $sum_debit += CurrencyFactory::returnPriceInDefaultCurrencyValue($arr[$i]['Currency_ID'], $arr[$i]['Transaction_Amount']);
    //            }
    //            array_push($arr[$i], $balance);
    //        }
    //        $final_balance = array('Balance' => $balance,
    //            'Default_Currency' => $default_currency);
    //        $sum_d = array('Total_Debit' => $sum_debit);
    //        $sum_c = array('Total_Credit' => $sum_credit);
    //        $final = array_merge($sum_c, $sum_d, $final_balance);
    //        array_push($arr, $final);
    //        return json_encode($arr);
    //    }
    //    public function getTransactionsByJV($jv) {
    //        $data = array();
    //        $query = $this->db->query('SELECT 
    //										t.*,
    //										c.*,
    //										ch.Account_Name
    //									FROM 
    //										tbl_accounting_transactions t
    //									LEFT JOIN 
    //										tbl_common_currency c
    //									ON 
    //										c.Currency_ID = t.Currency_ID
    //									LEFT JOIN 
    //										tbl_chart_of_accounts ch
    //									ON 
    //										ch.Account_Code = t.Transaction_Account
    //									WHERE 
    //										t.JV_ID = "' . $jv . '"
    //				');
    //        while ($row = $this->db->assoc($query)) {
    //            $data[] = $row;
    //        }
    //        return $data;
    //    }

    public function returnBestCustomer($limit) {
        $data = array();
        $query = $this->db->query('SELECT 
                                                                                    c.Customer_Name AS Name,
                                                                                    i.Invoice_Net_Total - i.Return_Invoice_Total AS Net_Total,
                                                                                    i.Invoice_Currency AS Currency_ID,
                                                                                    i.Customer_ID AS ID
                                                                            FROM 
                                                                                    tbl_invoices i
                                                                            LEFT JOIN 
                                                                                    tbl_customers c
                                                                            ON 
                                                                                    c.Customer_ID = i.Customer_ID
                                    ');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        $result = self::returnTotalForAllSuppCust($data);
        rsort($result);
        $arr = array_slice($result, 0, $limit);
        return $arr;
    }

    public function returnBestSupplier($limit) {
        $data = array();
        $query = $this->db->query('SELECT 
                                                                                    s.Supplier_Name AS Name,
                                                                                    p.Purchase_Net_Total AS Net_Total,
                                                                                    p.Currency_ID,
                                                                                    p.Supplier_ID AS ID
                                                                            FROM 
                                                                                    tbl_inventory_purchases p
                                                                            LEFT JOIN 
                                                                                    tbl_stock_suppliers s
                                                                            ON 
                                                                                    s.Supplier_ID = p.Supplier_ID
                                    ');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        $result = self::returnTotalForAllSuppCust($data);
        rsort($result);
        $arr = array_slice($result, 0, $limit);
        return $arr;
    }

    private function returnTotalForAllSuppCust(array $data) {
        $count = count($data);
        $temp = array();
        $final = array();
        for ($i = 0; $i < $count; $i++) {
            $total = 0.0;
            if (array_key_exists($i, $data)) {
                $id = $data[$i]['ID'];
                $name = $data[$i]['Name'];
                $total += CurrencyFactory::returnPriceInDefaultCurrencyValue($data[$i]['Currency_ID'], $data[$i]['Net_Total']);

                for ($j = $i + 1; $j < $count; $j++)
                    if (array_key_exists($j, $data))
                        if ($data[$i]['ID'] == $data[$j]['ID']) {
                            $total += CurrencyFactory::returnPriceInDefaultCurrencyValue($data[$j]['Currency_ID'], $data[$j]['Net_Total']);
                            unset($data[$j]);
                        }
                $temp = array(
                    'Total' => $total,
                    'ID' => $id,
                    'Name' => ucwords($name)
                );

                array_push($final, $temp);
                unset($data[$i]);
                $name = '';
                $id = '';
                $temp = array();
            }
        }

        return $final;
    }

    //    public function viewTransactionsByFirstCode($first_code) {
    //        $data = array();
    //        $query = $this->db->query('SELECT 
    //                                       t.*,
    //                                       c.Currency_Symbol,
    //                                       a.Account_Name
    //                                    FROM 
    //                                        tbl_accounting_transactions t
    //                                    LEFT JOIN 
    //                                        tbl_common_currency c
    //                                    ON 
    //                                        t.Currency_ID = c.Currency_ID
    //                                    LEFT JOIN 
    //                                        tbl_chart_of_accounts a
    //                                    ON 
    //                                        t.Transaction_Account = a.Account_Code
    //                                    WHERE 
    //                                       LEFT(Transaction_Account,1) = "' . $first_code . '" 
    //                                    
    //                ');
    //        while ($row = $this->db->assoc($query))
    //            $data[] = $row;
    //        return $data;
    //    }
    //    public function viewClosingBalances() {
    //        for ($i=1; $i<8; $i++) {
    //            $data = self::viewTransactionsByFirstCode($i);
    //            $credit = 0.0;
    //            $debit  = 0.0;
    //            for ($j=0;$j<count($data);$j++) {
    //                $amount = CurrencyFactory::returnPriceInDefaultCurrencyValue($data[$j]['Currency_ID'],$data[$j]['Transaction_Amount']);
    //                if ($data[$j]['Transaction_Type'] == "Credit")
    //                    $credit += $amount;
    //                else
    //                    $debit += $amount;
    //
    //            }
    //            $amount_result = $debit - $credit;
    //            //if ($amount_result > 0)
    //                    //then result is balance and type is debit else type is credit and to be added to final array that contains the 7 accounts
    //                    //other data to be placed in the final array is currency id and account name
    //        }
    //    }                                            
    //    public function viewAccountsByDigits($num_digits, $group_num = null, $group_code = null, $min, $max, $year = null, $back_up = false, $from_month = null, $to_month = null, $from_date = null, $to_date = null, $opening_balance = 1, $actual_only = false) {
    //        $data = array();
    //        $condition = '';
    //        if (!is_null($from_month) and ! is_null($to_month))
    //            $condition .= ' AND MONTH(Transaction_Date) >= "' . $from_month . '" AND MONTH(Transaction_Date) <= "' . $to_month . '" ';
    //        if (!is_null($group_num) and ! is_null($group_code)) {
    //            $condition .= ' AND LEFT(Transaction_Account,' . $group_num . ') = "' . $group_code . '" ';
    //        } else {
    //            $condition .= ' AND LEFT(Transaction_Account,1) = "' . $min . '" ';
    //        }
    //
    //        if (!is_null($year))
    //            $condition .= ' AND YEAR(Transaction_Date) = "' . $year . '" ';
    //        if (!is_null($from_date) and ! is_null($to_date))
    //            $condition .= ' AND Transaction_Date >= "' . $from_date . '" AND Transaction_Date <= "' . $to_date . '" ';
    //        if ($opening_balance == 0)
    //            $condition .= ' AND JV_ID <> 1 ';
    //        if (!$actual_only) {
    //            $query = $this->db->query('SELECT 
    //                                            s.* 
    //                                        FROM 
    //                                            (SELECT 
    //                                                DISTINCT LEFT(Transaction_Account,' . $num_digits . ') AS Transaction_Account
    //                                            FROM 
    //                                                tbl_accounting_transactions 
    //                                            WHERE 
    //
    //                                                (LEFT(Transaction_Account,' . $num_digits . ') 
    //                                                    BETWEEN 
    //                                                        ' . $min . ' 
    //                                                    AND 
    //                                                        ' . $max . ')
    //                                             ' . $condition . '
    //                                            ORDER BY 
    //                                                LEFT(Transaction_Account,' . $num_digits . ') 
    //                                                ) s
    //                                        ORDER BY 
    //                                              Transaction_Account
    //                    ');
    //            while ($row = $this->db->assoc($query))
    //                $data[] = $row['Transaction_Account'];
    //        }
    //        if ($back_up) {
    //            $query2 = $this->db->query('SELECT 
    //                                            s.* 
    //                                        FROM 
    //                                            (SELECT 
    //                                                DISTINCT LEFT(Transaction_Account,' . $num_digits . ') AS Transaction_Account
    //                                            FROM 
    //                                                tbl_mgt_logs 
    //                                            WHERE 
    //                                                (LEFT(Transaction_Account,' . $num_digits . ') 
    //                                                    BETWEEN 
    //                                                        ' . $min . ' 
    //                                                    AND 
    //                                                        ' . $max . ')
    //                                            ' . $condition . '
    //                                            ORDER BY 
    //                                                LEFT(Transaction_Account,' . $num_digits . ')
    //                                            ) s
    //                                        ORDER BY 
    //                                              Transaction_Account
    //                    ');
    //            while ($row2 = $this->db->assoc($query2))
    //                $data[] = $row2['Transaction_Account'];
    //        }
    //        $unique_data = array_values(array_unique($data));
    //        return $unique_data;
    //    }

    public function viewExactAccounts($num_digits, $group_num = null, $group_code = null, $min, $max, $multi_accounts = null, $family_accs = null) {
        $data = array();
        $condition = '';

        // $condition.=' and Account_ID not in (select Parent_ID from tbl_chart_of_accounts) ';

        if (!is_null($group_num) and ! is_null($group_code)) {
            $condition .= ' AND LEFT(a.Account_Code,' . $group_num . ') = "' . $group_code . '" ';
        } else
            $condition .= ' AND LEFT(a.Account_Code,1) = "' . substr($min, 0, 1) . '" ';

        if (!empty($multi_accounts))
            $condition .= ' and a.Account_ID in (' . $multi_accounts . ') ';
        if (!empty($family_accs)) {
            $fam_accs = CommonACC::get_family_accs_by_id($family_accs);
            $condition .= ' and a.Account_ID in (' . $fam_accs . ') ';
        }

        $query = $this->db->query('SELECT 
                                            DISTINCT LEFT(a.Account_Code,' . $num_digits . ') AS Account_Code
                                        FROM tbl_chart_of_accounts a
                                        WHERE (LEFT(a.Account_Code,' . $num_digits . ') BETWEEN ' . $min . ' AND  ' . $max . ')
                                         ' . $condition . '
                                        ORDER BY CAST(Account_Code as char)
                        ');

        while ($row = $this->db->assoc($query))
            $data[] = $row['Account_Code'];
        //        }
        //        if ($back_up) {
        //
        //            $year_id_actual = $this->year_id_actual;
        ////            $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
        //            $query2 = $this->db->query('SELECT 
        //                                            s.* 
        //                                        FROM 
        //                                            (SELECT 
        //                                                DISTINCT LEFT(a.Account_Code,' . $select . ') AS Account_Code
        //                                            FROM 
        //                                                tbl_mgt_logs t 
        //                                                join tbl_chart_of_accounts a on t.Account_ID = a.Account_ID
        //                                            WHERE 
        //                                                current_year_id = "' . $year_id_actual . '"
        //                                            AND
        //                                                (LEFT(a.Account_Code,' . $num_digits . ') 
        //                                                    BETWEEN 
        //                                                        ' . $min . ' 
        //                                                    AND 
        //                                                        ' . $max . ')
        //                                            ' . $condition . '
        //                                            ORDER BY 
        //                                                LEFT(a.Account_Code,' . $num_digits . ')
        //                                            ) s
        //                                        ORDER BY 
        //                                              Account_Code
        //                    ');
        //            while ($row2 = $this->db->assoc($query2))
        //                $data[] = $row2['Account_Code'];
        //        }
        //        if (!is_null($group_num) and ! is_null($group_code)) {
        //            if (substr($min, 0, 1) == 6) {
        //                if ($group_num == 1) {
        //                    $data[] = "675";
        //                } else if ($group_num == 2) {
        //                    if ($group_code == 67)
        //                        $data[] = "675";
        //                }
        //                else if ($group_num >= 3) {
        //                    if ($group_code == 675)
        //                        $data[] = "675";
        //                }
        //            }
        //            if (substr($min, 0, 1) == 7) {
        //                if ($group_num == 1) {
        //                    $data[] = "775";
        //                } else if ($group_num == 2) {
        //                    if ($group_code == 77)
        //                        $data[] = "775";
        //                }
        //                else if ($group_num >= 3) {
        //                    if ($group_code == 775)
        //                        $data[] = "775";
        //                }
        //            }
        //        }
        //        else {
        //            if ($min == 6) {
        //                if ($num_digits == 2)
        //                    $data[] = "67";
        //                else if ($num_digits > 2)
        //                    $data[] = "675";
        //            }
        //            else if ($min == 7) {
        //                if ($num_digits == 2)
        //                    $data[] = "77";
        //                else if ($num_digits > 2)
        //                    $data[] = "775";
        //            }
        //        }
        //        $unique_data = array_values(array_unique($data));
        //        sort($unique_data, SORT_STRING);
        //        return $unique_data;
        //        echo"<pre>";
        //        print_r($data);
        return $data;
    }

    //    public function viewTransactionsByDigits(array $digits, $year = null, $main_len, $back_up = false, $currency_id = 0, $month = null, $from_month = null, $to_month = null, $from_date = null, $to_date = null, $opening_balance = 1, $actual_only = false) {
    //        if ($currency_id == 0)
    //            $currency_id = CurrencyFactory::getDefaultCurrency();
    //        $local_currency = CurrencyFactory::returnLocalCurrency();
    //        $data = array();
    //        $total_debit_account = 0.0;
    //        $total_credit_account = 0.0;
    //        $total = 0.0;
    //        $digits = array_values(array_filter($digits));
    //        for ($i = 0; $i < count($digits); $i++) {
    //            $condition = '';
    //            $total_debit = 0.0;
    //            $total_credit = 0.0;
    //            $balance = 0.0;
    //            $len = strlen($digits[$i]);
    //            if ($len < $main_len)
    //                $condition .= ' AND Transaction_Account = "' . $digits[$i] . '"';
    //            if (!is_null($year))
    //                $condition .= ' AND YEAR(Transaction_Date) = "' . $year . '"';
    //            if (!is_null($month))
    //                $condition .= ' AND MONTH(Transaction_Date) = "' . $month . '" ';
    //            if (!is_null($from_month) and ! is_null($to_month))
    //                $condition .= ' AND MONTH(Transaction_Date) >= "' . $from_month . '" AND MONTH(Transaction_Date) <= "' . $to_month . '"';
    //            if (!is_null($from_date) and ! is_null($to_date))
    //                $condition .= ' AND Transaction_Date >= "' . $from_date . '" AND Transaction_Date <= "' . $to_date . '" ';
    //            if ($opening_balance == 0)
    //                $condition .= ' AND JV_ID <> 1';
    //            if (!$actual_only) {
    //                $query = $this->db->query('SELECT 
    //                                                *
    //                                            FROM 
    //                                                tbl_accounting_transactions 
    //                                            WHERE 
    //                                                LEFT(Transaction_Account,' . $len . ') = "' . $digits[$i] . '"
    //
    //                        ' . $condition);
    //                while ($row = $this->db->assoc($query)) {
    //                    if ($row['Transaction_Type'] == 'Debit') {
    //
    //                        if ($currency_id == $local_currency) {
    //                            if ($row['Currency_ID'] == $local_currency) {
    //                                $total_debit += $row['Transaction_Amount'];
    //                                $balance += $row['Transaction_Amount'];
    //                            } else {
    //                                $total_debit += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                                $balance += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                            }
    //                        } else {
    //
    //                            $total_debit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                            $balance += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                        }
    //                    } elseif ($row['Transaction_Type'] == 'Credit') {
    //                        if ($currency_id == $local_currency) {
    //                            if ($row['Currency_ID'] == $local_currency) {
    //                                $total_credit += $row['Transaction_Amount'];
    //                                $balance -= $row['Transaction_Amount'];
    //                            } else {
    //                                $total_credit += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                                $balance -= CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                            }
    //                        } else {
    //                            $total_credit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                            $balance -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                        }
    //                    }
    //                }
    //            }
    //            if ($back_up) {
    //                $query2 = $this->db->query('SELECT 
    //                                                *
    //                                            FROM 
    //                                                tbl_mgt_logs 
    //                                            WHERE 
    //                                                LEFT(Transaction_Account,' . $len . ') = "' . $digits[$i] . '"
    //                                            
    //                        ' . $condition);
    //                while ($row2 = $this->db->assoc($query2)) {
    //                    if ($row2['Transaction_Type'] == 'Debit') {
    //                        if ($currency_id == $local_currency) {
    //                            if ($row2['Currency_ID'] == $local_currency) {
    //                                $total_debit += $row2['Transaction_Amount'];
    //                                $balance += $row2['Transaction_Amount'];
    //                            } else {
    //                                $total_debit += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                                $balance += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                            }
    //                        } else {
    //                            $total_debit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                            $balance += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                        }
    //                    } elseif ($row2['Transaction_Type'] == 'Credit') {
    //                        if ($currency_id == $local_currency) {
    //                            if ($row2['Currency_ID'] == $local_currency) {
    //                                $total_credit += $row2['Transaction_Amount'];
    //                                $balance -= $row2['Transaction_Amount'];
    //                            } else {
    //                                $total_credit += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                                $balance -= CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                            }
    //                        } else {
    //                            $total_credit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                            $balance -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                        }
    //
    //
    ////                        if($currency_id != 0) {
    ////                            $total_credit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                            $balance      -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                        }
    ////                        else {
    ////                            $total_credit += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                            $balance      -= CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                        }
    //                    }
    //                }
    //            }
    //            $total_debit_account += $total_debit;
    //            $total_credit_account += $total_credit;
    //            $total += $balance;
    //            $data[$i] = array('Account_Code' => $digits[$i],
    //                'Account_Name' => self::returnAccountName($digits[$i]),
    //                'Debit' => round($total_debit, 2),
    //                'Credit' => round($total_credit, 2),
    //                'Balance' => $balance
    ////                              'Balance'      => $balance >= 0 ? round($balance,2) : '('.ltrim(round($balance,2), '-').')'
    //            );
    //        }
    //
    //        $data['Debit_Per_Account'] = round($total_debit_account, 2);
    //        $data['Credit_Per_Account'] = round($total_credit_account, 2);
    //        $data['Balance_Per_Account'] = $total;
    ////        $data['Balance_Per_Account'] = $total >= 0 ? round($total,2) : '('.ltrim(round($total,2), '-').')';
    //        return $data;
    //    }
    //    public function generalLedger($code, $from_date, $to_date, $currency_id = 0, $type = "All") {
    //        $from_year = substr($from_date, 0, 4);
    //        $start_date = $from_year . "-01-01";
    //        $data = array();
    //
    //        $opening_balance = 0.0;
    //        $prev_balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $current_balance = 0.0;
    //        $all_balance = 0.0;
    //        if ($currency_id == 0)
    //            $currency_id = CurrencyFactory::getDefaultCurrency();
    //        $local_currency = CurrencyFactory::returnLocalCurrency();
    //        $balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $condition = '';
    //        if ($type == "Credit" or $type == "Debit")
    //            $condition .= ' AND Transaction_Type = "' . $type . '"';
    //        $query = $this->db->query('SELECT 
    //                                        *
    //                                    FROM 
    //                                        tbl_accounting_transactions 
    //                                    WHERE 
    //                                        Transaction_Account = "' . $code . '"
    //                                    AND 
    //                                        JV_ID = 1
    //                ' . $condition);
    //        while ($row = $this->db->assoc($query)) {
    //            if ($row['Currency_ID'] != $currency_id) {
    //                if ($row['Currency_ID'] != $local_currency)
    //                    $temp_amount_1 = CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                else
    //                    $temp_amount_1 = $row['Transaction_Amount'];
    //                $temp_amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($local_currency, $currency_id, $temp_amount_1);
    //            } else
    //                $temp_amount = $row['Transaction_Amount'];
    //            if ($row['Transaction_Type'] == 'Debit') {
    //                $opening_balance = $temp_amount;
    //                $all_balance += $temp_amount;
    //            } elseif ($row['Transaction_Type'] == 'Credit') {
    //                $opening_balance = $temp_amount * (-1);
    //                $all_balance -= $temp_amount;
    //            }
    //
    //            $data[] = array(
    //                "Transaction_Date" => $row['Transaction_Date'],
    //                "JV_ID" => $row['JV_ID'],
    //                "Transaction_Description" => $row['Transaction_Description'],
    //                "Opening_Balance" => $opening_balance,
    //                "Prev_Balance" => "0.00",
    //                "Debit" => "0.00",
    //                "Credit" => "0.00",
    //                "Current_Balance" => "0.00",
    //                "All_Balance" => $all_balance
    //            );
    //        }
    //
    //
    //        $query_prev = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_accounting_transactions 
    //                                        WHERE 
    //                                            Transaction_Account = "' . $code . '"
    //                                        AND 
    //                                            JV_ID <> 1
    //                                        AND 
    //                                            Transaction_Date >= "' . $start_date . '" 
    //                                        AND 
    //                                            Transaction_Date < "' . $from_date . '"
    //                                        ' . $condition . '
    //                                        ORDER BY 
    //                                            Transaction_Date
    //                    ');
    //        while ($row_prev = $this->db->assoc($query_prev)) {
    //            if ($row_prev['Currency_ID'] != $currency_id) {
    //                if ($row_prev['Currency_ID'] != $local_currency)
    //                    $temp_amount_1 = CurrencyFactory::returnExchangedValueByExchangedID($row_prev['Exchange_Rate_ID'], $row_prev['Transaction_Amount'], $row_prev['Currency_ID']);
    //                else
    //                    $temp_amount_1 = $row_prev['Transaction_Amount'];
    //                $temp_amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($local_currency, $currency_id, $temp_amount_1);
    //            } else
    //                $temp_amount = $row_prev['Transaction_Amount'];
    //            if ($row_prev['Transaction_Type'] == 'Debit') {
    //                $prev_balance += $temp_amount;
    //                $all_balance += $temp_amount;
    //            } elseif ($row_prev['Transaction_Type'] == 'Credit') {
    //                $prev_balance -= $temp_amount;
    //                $all_balance -= $temp_amount;
    //            }
    //
    //            $data[] = array(
    //                "Transaction_Date" => $row_prev['Transaction_Date'],
    //                "JV_ID" => $row_prev['JV_ID'],
    //                "Transaction_Description" => $row_prev['Transaction_Description'],
    //                "Opening_Balance" => $opening_balance,
    //                "Prev_Balance" => $prev_balance,
    //                "Debit" => "0.00",
    //                "Credit" => "0.00",
    //                "Current_Balance" => "0.00",
    //                "All_Balance" => $all_balance
    //            );
    //        }
    //
    //        $query_current = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_accounting_transactions 
    //                                        WHERE 
    //                                            Transaction_Account = "' . $code . '"
    //                                        AND 
    //                                            JV_ID <> 1
    //                                        AND 
    //                                            Transaction_Date >= "' . $from_date . '" 
    //                                        AND 
    //                                            Transaction_Date <= "' . $to_date . '"
    //                                        ' . $condition . '
    //                                        ORDER BY 
    //                                            Transaction_Date
    //                    ');
    //        while ($row_current = $this->db->assoc($query_current)) {
    //            if ($row_current['Currency_ID'] != $currency_id) {
    //                if ($row_current['Currency_ID'] != $local_currency)
    //                    $temp_amount_1 = CurrencyFactory::returnExchangedValueByExchangedID($row_current['Exchange_Rate_ID'], $row_current['Transaction_Amount'], $row_current['Currency_ID']);
    //                else
    //                    $temp_amount_1 = $row_current['Transaction_Amount'];
    //                $temp_amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($local_currency, $currency_id, $temp_amount_1);
    //            } else
    //                $temp_amount = $row_current['Transaction_Amount'];
    //            if ($row_current['Transaction_Type'] == 'Debit') {
    //                $current_balance += $temp_amount;
    //                $debits += $temp_amount;
    //                $all_balance += $temp_amount;
    //                $data[] = array(
    //                    "Transaction_Date" => $row_current['Transaction_Date'],
    //                    "JV_ID" => $row_current['JV_ID'],
    //                    "Transaction_Description" => $row_current['Transaction_Description'],
    //                    "Opening_Balance" => $opening_balance,
    //                    "Prev_Balance" => $prev_balance,
    //                    "Debit" => $temp_amount,
    //                    "Credit" => "0.00",
    //                    "Current_Balance" => $current_balance,
    //                    "All_Balance" => $all_balance
    //                );
    //            } elseif ($row_current['Transaction_Type'] == 'Credit') {
    //                $current_balance -= $temp_amount;
    //                $credits += $temp_amount;
    //                $all_balance -= $temp_amount;
    //                $data[] = array(
    //                    "Transaction_Date" => $row_current['Transaction_Date'],
    //                    "JV_ID" => $row_current['JV_ID'],
    //                    "Transaction_Description" => $row_current['Transaction_Description'],
    //                    "Opening_Balance" => $opening_balance,
    //                    "Prev_Balance" => $prev_balance,
    //                    "Debit" => "0.00",
    //                    "Credit" => $temp_amount,
    //                    "Current_Balance" => $current_balance,
    //                    "All_Balance" => $all_balance
    //                );
    //            }
    //        }
    //        $default = $this->db->query('SELECT
    //                                        Currency_Symbol
    //                                    FROM
    //                                        tbl_common_currency 
    //                                    WHERE 
    //                                        Currency_ID = "' . $currency_id . '" ');
    //        $default_row = $this->db->assoc($default);
    //        $row_current['Currency_Symbol'] = $default_row['Currency_Symbol'];
    //
    //        $data['Currency_Symbol'] = $row_current;
    //        $data['Total'] = array(
    //            "Opening_Balance" => $opening_balance,
    //            "Prev_Balance" => $prev_balance,
    //            "Debit" => $debits,
    //            "Credit" => $credits,
    //            "Current_Balance" => $current_balance,
    //            "All_Balance" => $all_balance
    //        );
    //
    //        return $data;
    //    }
    //    public function trialBalanceByDigits($options) {
    ////public function trialBalanceByDigits($num_digits, $group_num, $from_date = null, $to_date = null, $active = 0, $back_up = false, $currency_id = 0, $opening_balance = 1, $actual_only = false, $from_acc = 1, $to_acc = 8) {
    //
    //        $num_digits = $options['digits'];
    //        $group_num = $options['Grouping'];
    //        $from_date = $options['From_Date'];
    //        $to_date = $options['To_Date'];
    //        $currency_id = $options['Currency_ID'];
    //        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 1;
    //        $active = !empty($options['Active']) ? $options['Active'] : 0;
    //        $back_up = $options['Is_Actual'] == 1 ? true : false;
    //        $actual_only = $options['Actual_TrialBalance'] == 1 ? true : false;
    ////        $from_acc = $options['from_account'];
    ////        $to_acc = $options['to_account'];
    //
    //
    //
    //
    //
    //        $len_zeros_nines = $group_num - 1;
    //        $zeros = str_repeat("0", $len_zeros_nines);
    //        $nines = str_repeat("9", $len_zeros_nines);
    //        $len_zeros_nines_2 = $num_digits - $group_num;
    //        $zeros_2 = str_repeat("0", $len_zeros_nines_2);
    //        $nines_2 = str_repeat("9", $len_zeros_nines_2);
    //
    //
    //        $from_year = substr($from_date, 0, 4);
    //        $start_date = $from_year . "-01-01";
    //        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
    //
    //        $open_balance = 0.0;
    //        $prev_balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $current_balance = 0.0;
    //        $all_balance = 0.0;
    //        $a = 0;
    //
    //        $index_6 = array();
    //        $index_7 = array();
    //        for ($i = 1; $i < 8; $i++) {
    //            $b = 0;
    //            $open_balance_1 = 0.0;
    //            $prev_balance_1 = 0.0;
    //            $debits_1 = 0.0;
    //            $credits_1 = 0.0;
    //            $current_balance_1 = 0.0;
    //            $all_balance_1 = 0.0;
    //
    //            $data = array();
    //            $min = $i;
    //            $max = $i . $nines;
    //            $data = self::viewExactAccounts($group_num, null, null, $min, $max, $back_up, $start_date, $to_date, $opening_balance, $actual_only);
    //            if (!empty($options['from_account']) && !empty($options['to_account'])) {
    //                $check_left_account = Report::check_left_accounts($options['from_account'], $options['to_account'], $i);
    //                if (!$check_left_account)
    //                    continue;
    //            }
    ////            echo $i . '===<br>';
    ////            if ($i == 4) {
    ////                echo"<pre>";
    ////                die(print_r($data));
    ////            }
    //            for ($z = 0; $z < count($data); $z++) {
    //                if (!empty($options['from_account']) && !empty($options['to_account'])) {
    //                    $check_left_account = Report::check_left_accounts($options['from_account'], $options['to_account'], $data[$z]);
    //                    if (!$check_left_account)
    //                        continue;
    //                }
    ////                echo $data[$z] . '===<br>';
    //
    //                $c = 0;
    //                $open_balance_2 = 0.0;
    //                $prev_balance_2 = 0.0;
    //                $debits_2 = 0.0;
    //                $credits_2 = 0.0;
    //                $current_balance_2 = 0.0;
    //                $all_balance_2 = 0.0;
    //
    //                $data_2 = array();
    //                $min_2 = $data[$z];
    //                $max_2 = $data[$z] . $nines_2;
    //                $data_2 = self::viewExactAccounts($num_digits, $group_num, $min_2, $min_2, $max_2, $back_up, $start_date, $to_date, $opening_balance, $actual_only);
    //                for ($k = 0; $k < count($data_2); $k++) {
    //                    if (!empty($options['from_account']) && !empty($options['to_account'])) {
    //                        $check_left_account = Report::check_left_accounts($options['from_account'], $options['to_account'], $data_2[$k]);
    //                        if (!$check_left_account)
    //                            continue;
    //                    }
    ////                    echo $data_2[$k] . '===<br>';
    //                    $code = $data_2[$k];
    //                    if ($opening_balance == 1)
    //                        $open_balance_3 = self::returnExactBalance($code, $currency_id, $from_date, $to_date, $opening_balance, $back_up, $actual_only, true)['Balance'];
    //                    else
    //                        $open_balance_3 = 0.0;
    //                    if ($start_date == $from_date)
    //                        $prev_balance_3 = 0.0;
    //                    else
    //                        $prev_balance_3 = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 0, $back_up, $actual_only)['Balance'];
    //                    $current_array = self::returnExactBalance($code, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only);
    //
    //                    $debits_3 = $current_array['Debits'];
    //                    $credits_3 = $current_array['Credits'];
    //                    $current_balance_3 = $current_array['Balance'];
    //                    $all_balance_3 = $open_balance_3 + $prev_balance_3 + $current_balance_3;
    //                    if ((ltrim(round($all_balance_3, 3), "-") != 0) or ( ltrim(round($all_balance_3, 3), "-") == 0 and $active == 0) or $code == 675 or $code == 775) {
    //                        $result[$a][$b][$c] = array("Name" => self::returnAccountName($code),
    //                            "Code" => $code,
    //                            "Opening_Balance" => $open_balance_3,
    //                            "Prev_Balance" => $prev_balance_3,
    //                            "Debits" => $debits_3,
    //                            "Credits" => $credits_3,
    //                            "Current_Balance" => $current_balance_3,
    //                            "Result_Balance" => $all_balance_3
    //                        );
    //
    //                        if ($i == 6) {
    //                            if ($group_num == 2 and $data[$z] == 67 and $code == 675) {
    //
    //                                $index_6 = array($b, $c, $a);
    //                            }
    //                            if ($group_num > 2 and $data[$z] == 675 and $code == 675) {
    //
    //                                $index_6 = array($b, $c, $a);
    //                            }
    //                        }
    //                        if ($i == 7) {
    //                            if ($group_num == 2 and $data[$z] == 77 and $code == 775) {
    //                                $index_7 = array($b, $c, $a);
    //                            }
    //                            if ($group_num > 2 and $data[$z] == 775 and $code == 775) {
    //                                $index_7 = array($b, $c, $a);
    //                            }
    //                        }
    ////                        if (count($index_6)>0 and $i == 7)
    ////                            echo ("66 ".$a.$b.$c." code ".$code."<br>");
    ////                        if (count($index_7)>0 and $i == 7)
    ////                            echo ("77 ".$a.$b.$c." code ".$code."<br>");
    //                        $c++;
    //                    }
    //                    $open_balance_2 += $open_balance_3;
    //                    $prev_balance_2 += $prev_balance_3;
    //                    $debits_2 += $debits_3;
    //                    $credits_2 += $credits_3;
    //                    $current_balance_2 += $current_balance_3;
    //                    $all_balance_2 += $all_balance_3;
    //                }
    //                if ($open_balance_2 != 0 or $prev_balance_2 != 0 or $debits_2 != 0 or $credits_2 != 0 or ( $group_num == 2 and $data[$z] == 67) or ( $group_num > 2 and $data[$z] == 675) or ( $group_num == 2 and $data[$z] == 77) or ( $group_num > 2 and $data[$z] == 775)) {
    //
    //
    //                    $result[$a][$b]['Totals_2'] = array("Name" => self::returnAccountName($data[$z]),
    //                        "Code" => $data[$z],
    //                        "Opening_Balance" => $open_balance_2,
    //                        "Prev_Balance" => $prev_balance_2,
    //                        "Debits" => $debits_2,
    //                        "Credits" => $credits_2,
    //                        "Current_Balance" => $current_balance_2,
    //                        "Result_Balance" => $all_balance_2
    //                    );
    //
    //                    $b++;
    //                }
    //                $open_balance_1 += $open_balance_2;
    //                $prev_balance_1 += $prev_balance_2;
    //                $debits_1 += $debits_2;
    //                $credits_1 += $credits_2;
    //                $current_balance_1 += $current_balance_2;
    //                $all_balance_1 += $all_balance_2;
    //            }
    //            if ($open_balance_1 != 0 or $prev_balance_1 != 0 or $debits_1 != 0 or $credits_1 != 0 or $i == 6 or $i == 7) {
    //
    //                $result[$a]['Totals_1'] = array("Name" => self::returnAccountName($i),
    //                    "Code" => $i,
    //                    "Opening_Balance" => $open_balance_1,
    //                    "Prev_Balance" => $prev_balance_1,
    //                    "Debits" => $debits_1,
    //                    "Credits" => $credits_1,
    //                    "Current_Balance" => $current_balance_1,
    //                    "Result_Balance" => $all_balance_1
    //                );
    //                $a++;
    //            }
    //            $open_balance += $open_balance_1;
    //            $prev_balance += $prev_balance_1;
    //            $debits += $debits_1;
    //            $credits += $credits_1;
    //            $current_balance += $current_balance_1;
    //            $all_balance += $all_balance_1;
    //        }
    //
    //        if ($prev_balance != 0 or $current_balance != 0) {
    //            if ($prev_balance >= 0 and $current_balance >= 0) {
    ////                die(print_r([$result[$index_6[2]][$index_6[0]][$index_6[1]],$result[$index_7[2]][$index_7[0]][$index_7[1]]]));
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //
    //                $result[$index_7[2]]['Totals_1']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //
    //
    //                $credits += $current_balance;
    //            } else if ($prev_balance <= 0 and $current_balance <= 0) {
    //
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //
    //                $result[$index_6[2]]['Totals_1']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Result_Balance'] += ($prev_balance + $current_balance) * (-1);
    //                $debits += $current_balance * (-1);
    //            } else if ($prev_balance >= 0 and $current_balance <= 0) {
    //
    //                $result[$index_6[2]]['Totals_1'] = array("Name" => self::returnAccountName(675),
    //                    "Code" => 675,
    //                    "Opening_Balance" => 0,
    //                    "Prev_Balance" => 0,
    //                    "Debits" => 0,
    //                    "Credits" => $current_balance * (-1),
    //                    "Current_Balance" => $current_balance * (-1),
    //                    "Result_Balance" => $current_balance * (-1)
    //                );
    //                $result[$index_7[2]]['Totals_1'] = array("Name" => self::returnAccountName(775),
    //                    "Code" => 775,
    //                    "Opening_Balance" => 0,
    //                    "Prev_Balance" => $prev_balance * (-1),
    //                    "Debits" => 0,
    //                    "Credits" => 0,
    //                    "Current_Balance" => 0,
    //                    "Result_Balance" => ($prev_balance) * (-1)
    //                );
    //
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Result_Balance'] += $prev_balance * (-1);
    //
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Result_Balance'] += $prev_balance * (-1);
    //
    //                $result[$index_7[2]]['Totals_1']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Result_Balance'] += $prev_balance * (-1);
    //
    //
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Result_Balance'] += $current_balance * (-1);
    //
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Result_Balance'] += $current_balance * (-1);
    //
    //                $result[$index_6[2]]['Totals_1']['Debits'] += $current_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Result_Balance'] += $current_balance * (-1);
    //
    //
    //                $debits += $current_balance * (-1);
    //            } else if ($prev_balance <= 0 and $current_balance >= 0) {
    //                $result[$index_6[2]]['Totals_1'] = array("Name" => self::returnAccountName(675),
    //                    "Code" => 675,
    //                    "Opening_Balance" => 0,
    //                    "Prev_Balance" => $prev_balance * (-1),
    //                    "Debits" => 0,
    //                    "Credits" => 0,
    //                    "Current_Balance" => 0,
    //                    "Result_Balance" => ($prev_balance) * (-1)
    //                );
    //                $result[$index_7[2]]['Totals_1'] = array("Name" => self::returnAccountName(775),
    //                    "Code" => 775,
    //                    "Opening_Balance" => 0,
    //                    "Prev_Balance" => 0,
    //                    "Debits" => 0,
    //                    "Credits" => $current_balance,
    //                    "Current_Balance" => $current_balance * (-1),
    //                    "Result_Balance" => ($current_balance) * (-1)
    //                );
    //
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]][$index_7[1]]['Result_Balance'] += $current_balance * (-1);
    //
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]][$index_7[0]]['Totals_2']['Result_Balance'] += $current_balance * (-1);
    //
    //                $result[$index_7[2]]['Totals_1']['Credits'] += $current_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Current_Balance'] += $current_balance * (-1);
    //                $result[$index_7[2]]['Totals_1']['Result_Balance'] += $current_balance * (-1);
    //
    //
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]][$index_6[1]]['Result_Balance'] += $prev_balance * (-1);
    //
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]][$index_6[0]]['Totals_2']['Result_Balance'] += $prev_balance * (-1);
    //
    //                $result[$index_6[2]]['Totals_1']['Prev_Balance'] += $prev_balance * (-1);
    //                $result[$index_6[2]]['Totals_1']['Result_Balance'] += $prev_balance * (-1);
    //
    //                $credits += $current_balance;
    //            }
    //            $prev_balance += $prev_balance * (-1);
    //            $current_balance += $current_balance * (-1);
    //            $all_balance += $all_balance * (-1);
    //
    //            if ($result[$index_6[2]][$index_6[0]]['Totals_2']['Result_Balance'] == 0 and count($result[$index_6[2]][$index_6[0]]) == 2) {
    //                unset($result[$index_6[2]][$index_6[0]]);
    //            } else if ($result[$index_6[2]][$index_6[0]][$index_6[1]]['Result_Balance'] == 0) {
    //                unset($result[$index_6[2]][$index_6[0]][$index_6[1]]);
    //            }
    //
    //            if ($result[$index_7[2]][$index_7[0]]['Totals_2']['Result_Balance'] == 0 and count($result[$index_7[2]][$index_7[0]]) == 2) {
    //                unset($result[$index_7[2]][$index_7[0]]);
    //            } else if ($result[$index_7[2]][$index_7[0]][$index_7[1]]['Result_Balance'] == 0) {
    //                unset($result[$index_7[2]][$index_7[0]][$index_7[1]]);
    //            }
    //        }
    //
    //        $result['Totals'] = array(
    //            "Opening_Balance" => $open_balance,
    //            "Prev_Balance" => $prev_balance,
    //            "Debits" => $debits,
    //            "Credits" => $credits,
    //            "Current_Balance" => $current_balance,
    //            "Result_Balance" => $all_balance
    //        );
    //        return $result;
    //    }
    //    public function trialBalanceByCode($num_digits, $group_num, $from_account, $to_account, $from_date, $to_date, $currency_id = 0, $opening_balance = 1, $back_up = false, $actual_only = false, $active = 0) {
    //        $len_zeros_nines = $group_num - 1;
    //        $zeros = str_repeat("0", $len_zeros_nines);
    //        $nines = str_repeat("9", $len_zeros_nines);
    //        $len_zeros_nines_2 = $num_digits - $group_num;
    //        $zeros_2 = str_repeat("0", $len_zeros_nines_2);
    //        $nines_2 = str_repeat("9", $len_zeros_nines_2);
    //
    //        $from_year = substr($from_date, 0, 4);
    //        $start_date = $from_year . "-01-01";
    //        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
    //
    //        $open_balance = 0.0;
    //        $prev_balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $current_balance = 0.0;
    //        $all_balance = 0.0;
    //        $a = 0;
    //        $first_digit = substr($from_account, 0, 1);
    //        $last_digit = substr($to_account, 0, 1);
    //
    //        for ($i = $first_digit; $i <= $last_digit; $i++) {
    //            $b = 0;
    //            $open_balance_1 = 0.0;
    //            $prev_balance_1 = 0.0;
    //            $debits_1 = 0.0;
    //            $credits_1 = 0.0;
    //            $current_balance_1 = 0.0;
    //            $all_balance_1 = 0.0;
    //
    //            $data = array();
    //            if ($i == $first_digit and $i <> $last_digit) {
    //                $min = $i;
    //                $len_nines = strlen($min) - 1;
    //                if ($len_nines < 0)
    //                    $len_nines = 0;
    //                $nines_h = str_repeat("9", $len_nines);
    //                $max = $i . $nines_h;
    //                $digits_num_current = strlen($min);
    //            }
    //            elseif ($i == $first_digit and $i == $last_digit) {
    //                $min = $from_account;
    //                $max = $to_account;
    //                $digits_num_current = strlen($max);
    //                if (strlen($min) > $digits_num_current) {
    //                    $digits_num_current = strlen($min);
    //                    $len_nines = strlen($min) - strlen($max);
    //                    $nines_h = str_repeat("9", $len_nines);
    //                    $max = $to_account . $nines_h;
    //                }
    //            } elseif ($i <> $first_digit and $i == $last_digit) {
    //                $min = $i;
    //                $max = $to_account;
    //                $digits_num_current = strlen($max);
    //                if (strlen($min) > $digits_num_current)
    //                    $digits_num_current = strlen($min);
    //            }
    //            else {
    //                $min = $i;
    //                $max = $i . $len_zeros_nines;
    //                $digits_num_current = $group_num;
    //            }
    //// must check if strlen(code from query<strlen of max must check if code from query < substr(max,0,strlen(fromquery)))
    ////            die("select".$group_num);
    //            $data = self::viewExactAccounts($digits_num_current, null, null, $min, $max, $back_up, $start_date, $to_date, $opening_balance, $actual_only, $group_num);
    ////           die(print_r($data)."test");
    //            $count_data = count($data);
    //            for ($z = 0; $z < $count_data; $z++) {
    //                $exists = false;
    ////                if ($max == $to_account and substr($max,0,strlen($data[$z])) < $data[$z]) {
    //                if ($max == $to_account and substr($data[$z], 0, strlen($max)) > $to_account) {
    //                    unset($data[$z]);
    ////                    $a = 0;
    //                } else {
    //                    $c = 0;
    //                    $open_balance_2 = 0.0;
    //                    $prev_balance_2 = 0.0;
    //                    $debits_2 = 0.0;
    //                    $credits_2 = 0.0;
    //                    $current_balance_2 = 0.0;
    //                    $all_balance_2 = 0.0;
    //
    //                    $data_2 = array();
    //
    //                    if ($from_account == $to_account) {
    //                        $min_2 = $from_account;
    //                        $len_nines = $num_digits - strlen($from_account);
    //                        if ($len_nines < 0)
    //                            $len_nines = 0;
    //                        $nines_h = str_repeat("9", $len_nines);
    //                        $max_2 = $to_account . $nines_h;
    //                        $digits_code = strlen($min_2);
    //                    }
    ////say walla
    //                    elseif ($i == $first_digit and $b == 0 and $from_account <> $to_account) {
    //                        $min_2 = $from_account;
    //                        $len_nines = $num_digits - strlen($data[$z]);
    //                        if ($len_nines < 0)
    //                            $len_nines = 0;
    //                        $nines_h = str_repeat("9", $len_nines);
    //                        $max_2 = $data[$z] . $nines_h;
    //                        $digits_code = strlen($min_2);
    ////                        die("test".$max."-".$min);
    //                    }
    //                    elseif ($max == $to_account) {
    //                        $min_2 = $data[$z];
    //                        $len_nines = $num_digits - strlen($max);
    //                        if ($len_nines < 0)
    //                            $len_nines = 0;
    //                        $nines_h = str_repeat("9", $len_nines);
    //                        $max_2 = $max . $nines_h;
    //                        $digits_code = strlen($min_2);
    //                    }
    //                    else {
    //                        $min_2 = $data[$z];
    //                        $max_2 = $data[$z] . $nines_2;
    //                        $digits_code = strlen($min_2);
    //                    }
    //
    //
    //
    //
    //
    //
    //                    $data_2 = self::viewExactAccounts($num_digits, $digits_code, $min_2, $min_2, $max_2, $back_up, $start_date, $to_date, $opening_balance, $actual_only, $group_num);
    ////                 if ($b>0)
    ////                    die(print_r($data_2));
    //                    for ($k = 0; $k < count($data_2); $k++) {
    //                        $code = $data_2[$k];
    //                        if ($opening_balance == 1)
    //                            $open_balance_3 = self::returnExactBalance($code, $currency_id, $from_date, $to_date, $opening_balance, $back_up, $actual_only, true)['Balance'];
    //                        else
    //                            $open_balance_3 = 0.0;
    //                        if ($start_date == $from_date)
    //                            $prev_balance_3 = 0.0;
    //                        else
    //                            $prev_balance_3 = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 0, $back_up, $actual_only)['Balance'];
    //                        $current_array = self::returnExactBalance($code, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only);
    //                        $debits_3 = $current_array['Debits'];
    //                        $credits_3 = $current_array['Credits'];
    //                        $current_balance_3 = $current_array['Balance'];
    //                        $all_balance_3 = $open_balance_3 + $prev_balance_3 + $current_balance_3;
    //                        if ($open_balance_3 != 0 or $prev_balance_3 != 0 or $debits_3 != 0 or $credits_3 != 0 or ( $all_balance_3 == 0 and $active == 0)) {
    //                            $result[$a][$b][$c] = array("Name" => self::returnAccountName($code),
    //                                "Code" => $code,
    //                                "Opening_Balance" => $open_balance_3,
    //                                "Prev_Balance" => $prev_balance_3,
    //                                "Debits" => $debits_3,
    //                                "Credits" => $credits_3,
    //                                "Current_Balance" => $current_balance_3,
    //                                "Result_Balance" => $all_balance_3
    //                            );
    //                            $c++;
    //                        }
    //                        $open_balance_2 += $open_balance_3;
    //                        $prev_balance_2 += $prev_balance_3;
    //                        $debits_2 += $debits_3;
    //                        $credits_2 += $credits_3;
    //                        $current_balance_2 += $current_balance_3;
    //                        $all_balance_2 += $all_balance_3;
    //                    }
    //                    if ($open_balance_2 != 0 or $prev_balance_2 != 0 or $debits_2 != 0 or $credits_2 != 0) {
    //                        $result[$a][$b]['Totals_2'] = array("Name" => self::returnAccountName($data[$z]),
    //                            "Code" => $data[$z],
    //                            "Opening_Balance" => $open_balance_2,
    //                            "Prev_Balance" => $prev_balance_2,
    //                            "Debits" => $debits_2,
    //                            "Credits" => $credits_2,
    //                            "Current_Balance" => $current_balance_2,
    //                            "Result_Balance" => $all_balance_2
    //                        );
    //                        $b++;
    //                    }
    //                    $open_balance_1 += $open_balance_2;
    //                    $prev_balance_1 += $prev_balance_2;
    //                    $debits_1 += $debits_2;
    //                    $credits_1 += $credits_2;
    //                    $current_balance_1 += $current_balance_2;
    //                    $all_balance_1 += $all_balance_2;
    //                    $exists = true;
    //                }
    //            }
    //            if ($exists) {
    //                if ($open_balance_1 != 0 or $prev_balance_1 != 0 or $debits_1 != 0 or $credits_1 != 0) {
    //                    $result[$a]['Totals_1'] = array("Name" => self::returnAccountName($i),
    //                        "Code" => $i,
    //                        "Opening_Balance" => $open_balance_1,
    //                        "Prev_Balance" => $prev_balance_1,
    //                        "Debits" => $debits_1,
    //                        "Credits" => $credits_1,
    //                        "Current_Balance" => $current_balance_1,
    //                        "Result_Balance" => $all_balance_1
    //                    );
    //                    $a++;
    //                }
    //                $open_balance += $open_balance_1;
    //                $prev_balance += $prev_balance_1;
    //                $debits += $debits_1;
    //                $credits += $credits_1;
    //                $current_balance += $current_balance_1;
    //                $all_balance += $all_balance_1;
    //            }
    //        }
    ////                    die(print_r($data));
    //        $result['Totals'] = array(
    //            "Opening_Balance" => $open_balance,
    //            "Prev_Balance" => $prev_balance,
    //            "Debits" => $debits,
    //            "Credits" => $credits,
    //            "Current_Balance" => $current_balance,
    //            "Result_Balance" => $all_balance
    //        );
    ////        echo "<pre>";
    ////        die(print_r($result));
    //        return $result;
    //    }
    //    public function viewBalanceSheet($num_digits, $group_num, $from_date, $to_date, $back_up = false, $currency_id = 0, $actual_only = false) {
    //        $year_id = self::getYearID(substr($from_date, 0, 4));
    //        $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
    //        $len_zeros_nines = $group_num - 1;
    //        $zeros = str_repeat("0", $len_zeros_nines);
    //        $nines = str_repeat("9", $len_zeros_nines);
    //        $len_zeros_nines_2 = $num_digits - $group_num;
    //        $zeros_2 = str_repeat("0", $len_zeros_nines_2);
    //        $nines_2 = str_repeat("9", $len_zeros_nines_2);
    //
    //
    //        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
    //
    //
    //        if (!$actual_only) {
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_accounting_transactions where current_year_id = "' . $year_id . '"');
    //            $start_date = $this->db->assoc($min_query)['Min_Date'];
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_mgt_logs where current_year_id = "' . $year_id_actual . '"');
    //            $temp = $this->db->assoc($min_query);
    //            if (count($temp) > 0) {
    //                $temp_date = $temp['Min_Date'];
    //                if ($temp < $start_date)
    //                    $start_date = $temp_date;
    //            }
    //        }
    //        else {
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_mgt_logs where current_year_id = "' . $year_id_actual . '"');
    //            $start_date = $this->db->assoc($min_query)['Min_Date'];
    //        }
    //
    //        $assets = array();
    //        $liabilities = array();
    //
    //        $assests_debit = 0.0;
    //        $assests_credit = 0.0;
    //        $assests_balance = 0.0;
    //        $assests_old_balance = 0.0;
    //        $assests_diff_balance = 0.0;
    //
    //        $liabilities_debit = 0.0;
    //        $liabilities_credit = 0.0;
    //        $liabilities_balance = 0.0;
    //        $liabilities_old_balance = 0.0;
    //        $liabilities_diff_balance = 0.0;
    //        $a = 0;
    //        $l = 0;
    //        for ($i = 1; $i < 6; $i++) {
    //            $min = $i;
    //            $max = $i . $nines;
    //            $data = self::viewExactAccounts($group_num, null, null, $min, $max, $back_up, $start_date, $to_date, 1, $actual_only);
    //
    //            $result_first = array();
    //            $s = 0;
    //            for ($z = 0; $z < count($data); $z++) {
    //                $min_2 = $data[$z];
    //                $max_2 = $data[$z] . $nines_2;
    //                $data_2 = self::viewExactAccounts($num_digits, $group_num, $min_2, $min_2, $max_2, $back_up, $start_date, $to_date, 1, $actual_only);
    //                $unknown_debit = 0;
    //                $unknown_credit = 0;
    //                $unknown_balance = 0;
    //                $unknown_old_balance = 0;
    //                $unknown_diff_balance = 0;
    //                $unknown = array();
    //                for ($k = 0; $k < count($data_2); $k++) {
    //                    $code = $data_2[$k];
    //                    $current_array = self::returnExactBalance($code, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only);
    //                    $debit = $current_array['Debits'];
    //                    $credit = $current_array['Credits'];
    //                    $current_balance = $current_array['Balance'];
    //                    if ($start_date == $from_date)
    //                        $old_balance = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, true)['Balance'];
    //                    else if ($start_date < $day_before)
    //                        $old_balance = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only)['Balance'];
    //                    else if ($start_date > $day_before)
    //                        $old_balance = self::returnExactBalance($code, $currency_id, $start_date, $start_date, 1, $back_up, $actual_only, true)['Balance'];
    //                    else if ($start_date < $from_date and $start_date == $day_before)
    //                        $old_balance = self::returnExactBalance($code, $currency_id, $start_date, $from_date, 1, $back_up, $actual_only)['Balance'];
    //
    //                    $diff_bal = $current_balance - $old_balance;
    //                    $unknown[] = array('Account_Code' => $code,
    //                        'Account_Name' => self::returnAccountName($code),
    //                        'Debit' => $debit,
    //                        'Credit' => $credit,
    //                        'Balance' => $current_balance,
    //                        'Old_Balance' => $old_balance,
    //                        'Horizental_Value' => $diff_bal
    //                    );
    //                    $unknown_debit += $debit;
    //                    $unknown_credit += $credit;
    //                    $unknown_balance += $current_balance;
    //                    $unknown_old_balance += $old_balance;
    //                    $unknown_diff_balance += $diff_bal;
    //                }
    //
    //                if ($unknown_balance > 0) {
    //                    $assets[$a] = $unknown;
    //                    $assets[$a]['Total'] = array('Account_Code' => $min_2,
    //                        'Account_Name' => self::returnAccountName($min_2),
    //                        'Debit' => $unknown_debit,
    //                        'Credit' => $unknown_credit,
    //                        'Balance' => $unknown_balance,
    //                        'Old_Balance' => $unknown_old_balance,
    //                        'Horizental_Value' => $unknown_diff_balance
    //                    );
    //                    $assests_debit += $unknown_debit;
    //                    $assests_credit += $unknown_credit;
    //                    $assests_balance += $unknown_balance;
    //                    $assests_old_balance += $unknown_old_balance;
    //                    $assests_diff_balance += $unknown_diff_balance;
    //                    $a++;
    //                }
    //                if ($unknown_balance < 0) {
    //                    $liabilities[$l] = $unknown;
    //                    $liabilities[$l]['Total'] = array('Account_Code' => $min_2,
    //                        'Account_Name' => self::returnAccountName($min_2),
    //                        'Debit' => $unknown_debit,
    //                        'Credit' => $unknown_credit,
    //                        'Balance' => $unknown_balance,
    //                        'Old_Balance' => $unknown_old_balance,
    //                        'Horizental_Value' => $unknown_diff_balance
    //                    );
    //                    $liabilities_debit += $unknown_debit;
    //                    $liabilities_credit += $unknown_credit;
    //                    $liabilities_balance += $unknown_balance;
    //                    $liabilities_old_balance += $unknown_old_balance;
    //                    $liabilities_diff_balance += $unknown_diff_balance;
    //                    $l++;
    //                }
    //
    //                if ($unknown_balance == 0) {
    //                    if ($unknown_old_balance < 0) {
    //                        $liabilities[$l] = $unknown;
    //                        $liabilities[$l]['Total'] = array('Account_Code' => $min_2,
    //                            'Account_Name' => self::returnAccountName($min_2),
    //                            'Debit' => $unknown_debit,
    //                            'Credit' => $unknown_credit,
    //                            'Balance' => $unknown_balance,
    //                            'Old_Balance' => $unknown_old_balance,
    //                            'Horizental_Value' => $unknown_diff_balance
    //                        );
    //                        $liabilities_old_balance += $unknown_old_balance;
    //                        $liabilities_diff_balance += $unknown_diff_balance;
    //                        $l++;
    //                    } else {
    //                        $assets[$a] = $unknown;
    //                        $assets[$a]['Total'] = array('Account_Code' => $min_2,
    //                            'Account_Name' => self::returnAccountName($min_2),
    //                            'Debit' => $unknown_debit,
    //                            'Credit' => $unknown_credit,
    //                            'Balance' => $unknown_balance,
    //                            'Old_Balance' => $unknown_old_balance,
    //                            'Horizental_Value' => $unknown_diff_balance
    //                        );
    //                        $assests_old_balance += $unknown_old_balance;
    //                        $assests_diff_balance += $unknown_diff_balance;
    //                        $a++;
    //                    }
    //                }
    //            }
    //        }
    //
    //        if ($start_date == $from_date) {
    //            $balance_6_old = self::returnExactBalance(6, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, true, true)['Balance'];
    //            $balance_7_old = self::returnExactBalance(7, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, true, true)['Balance'];
    //        } else {
    //            $balance_6_old = self::returnExactBalance(6, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, false, true)['Balance'];
    //            $balance_7_old = self::returnExactBalance(7, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, false, true)['Balance'];
    //        }
    //        $diff_old = $balance_6_old + $balance_7_old;
    //
    //        $result_6 = self::returnExactBalance(6, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only, false, true);
    //        $result_7 = self::returnExactBalance(7, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only, false, true);
    //
    //        $balance_6 = $result_6['Balance'];
    //        $balance_7 = $result_7['Balance'];
    //        $diff = $balance_6 + $balance_7;
    //
    //        $balance_6 = $result_6['Balance'];
    //        $balance_7 = $result_7['Balance'];
    //        $diff = $balance_6 + $balance_7;
    //
    //
    //        //to solve if there is exchange rate
    //        $temp_diff_all = $assests_balance + $liabilities_balance + $diff;
    ////        die("temp: ".$temp_diff_all);
    //        if ($temp_diff_all < 0) {
    //            if ($diff > 0) {
    //                $diff -= $temp_diff_all;
    //                $diff_debit = $temp_diff_all;
    //                $diff_credit = 0.0;
    //            }
    //            if ($diff < 0) {
    //                $diff += $temp_diff_all;
    //                $diff_debit = 0.0;
    //                $diff_credit = $temp_diff_all;
    //            }
    //        } else {
    //            if ($diff > 0)
    //                $diff += $temp_diff_all;
    //            if ($diff < 0)
    //                $diff -= $temp_diff_all;
    //            $diff_debit = 0.0;
    //            $diff_credit = $temp_diff_all;
    //        }
    //
    //        $temp_diff_all_old = $assests_old_balance + $liabilities_old_balance + $diff_old;
    //        if ($temp_diff_all_old < 0) {
    //            if ($diff > 0)
    //                $diff_old += $temp_diff_all_old;
    //            if ($diff < 0)
    //                $diff_old -= $temp_diff_all_old;
    //        }
    //        else {
    //            if ($diff > 0)
    //                $diff_old -= $temp_diff_all_old;
    //            if ($diff < 0)
    //                $diff_old += $temp_diff_all_old;
    //        }
    //
    //
    //        $diff_debit = $result_6['Debits'] - $result_7['Debits'];
    //        if ($diff_debit < 0)
    //            $diff_debit = $diff_debit;
    //        $diff_credit = $result_7['Credits'] - $result_6['Credits'];
    //        if ($diff_credit < 0)
    //            $diff_credit = $diff_credit;
    //        $horizental_diff = $diff - $diff_old;
    //
    //        if ($diff > 0) {
    //            $index = count($assets);
    //            $assets[$index][0] = array('Account_Code' => 139,
    //                'Account_Name' => self::returnAccountName(139),
    //                'Debit' => $diff_debit,
    //                'Credit' => $diff_credit,
    //                'Balance' => $diff,
    //                'Old_Balance' => $diff_old,
    //                'Horizental_Value' => $horizental_diff
    //            );
    //            $assets[$index]['Total'] = array('Account_Code' => 139,
    //                'Account_Name' => self::returnAccountName(139),
    //                'Debit' => $diff_debit,
    //                'Credit' => $diff_credit,
    //                'Balance' => $diff,
    //                'Old_Balance' => $diff_old,
    //                'Horizental_Value' => $horizental_diff
    //            );
    //            $assests_balance += $diff;
    //            $assests_debit += $diff_debit;
    //            $assests_credit += $diff_credit;
    //            $assests_old_balance += $diff_old;
    //            $assests_diff_balance += $horizental_diff;
    //        } elseif ($diff < 0) {
    //            $index = count($liabilities);
    //            $liabilities[$index][0] = array('Account_Code' => 138,
    //                'Account_Name' => self::returnAccountName(138),
    //                'Debit' => $diff_debit,
    //                'Credit' => $diff_credit,
    //                'Balance' => $diff,
    //                'Old_Balance' => $diff_old,
    //                'Horizental_Value' => $horizental_diff
    //            );
    //            $liabilities[$index]['Total'] = array('Account_Code' => 138,
    //                'Account_Name' => self::returnAccountName(138),
    //                'Debit' => $diff_debit,
    //                'Credit' => $diff_credit,
    //                'Balance' => $diff,
    //                'Old_Balance' => $diff_old,
    //                'Horizental_Value' => $horizental_diff
    //            );
    //            $liabilities_balance += $diff;
    //            $liabilities_debit += $diff_debit;
    //            $liabilities_credit += $diff_credit;
    //            $liabilities_old_balance += $diff_old;
    //            $liabilities_diff_balance += $horizental_diff;
    //        } elseif ($diff == 0) {
    //            if ($diff_old > 0) {
    //                $index = count($assets);
    //                $assets[$index][0] = array('Account_Code' => 139,
    //                    'Account_Name' => self::returnAccountName(139),
    //                    'Debit' => $diff_debit,
    //                    'Credit' => $diff_credit,
    //                    'Balance' => $diff,
    //                    'Old_Balance' => $diff_old,
    //                    'Horizental_Value' => $horizental_diff
    //                );
    //                $assets[$index]['Total'] = array('Account_Code' => 139,
    //                    'Account_Name' => self::returnAccountName(139),
    //                    'Debit' => $diff_debit,
    //                    'Credit' => $diff_credit,
    //                    'Balance' => $diff,
    //                    'Old_Balance' => $diff_old,
    //                    'Horizental_Value' => $horizental_diff
    //                );
    //                $assests_balance += $diff;
    //                $assests_debit += $diff_debit;
    //                $assests_credit += $diff_credit;
    //                $assests_old_balance += $diff_old;
    //                $assests_diff_balance += $horizental_diff;
    //            } else if ($diff_old < 0) {
    //                $index = count($liabilities);
    //                $liabilities[$index][0] = array('Account_Code' => 138,
    //                    'Account_Name' => self::returnAccountName(138),
    //                    'Debit' => $diff_debit,
    //                    'Credit' => $diff_credit,
    //                    'Balance' => $diff,
    //                    'Old_Balance' => $diff_old,
    //                    'Horizental_Value' => $horizental_diff
    //                );
    //                $liabilities[$index]['Total'] = array('Account_Code' => 138,
    //                    'Account_Name' => self::returnAccountName(138),
    //                    'Debit' => $diff_debit,
    //                    'Credit' => $diff_credit,
    //                    'Balance' => $diff,
    //                    'Old_Balance' => $diff_old,
    //                    'Horizental_Value' => $horizental_diff
    //                );
    //                $liabilities_balance += $diff;
    //                $liabilities_debit += $diff_debit;
    //                $liabilities_credit += $diff_credit;
    //                $liabilities_old_balance += $diff_old;
    //                $liabilities_diff_balance += $horizental_diff;
    //            }
    //        }
    //        $assets_vertical = 0.0;
    //        $assets_old_vertical = 0.0;
    //        $assets_horizental = 0.0;
    //
    //        for ($t = 0; $t < count($assets); $t++) {
    //            $vertical_per = 0.0;
    //            $old_vertical_per = 0.0;
    //            $horizental_per = 0.0;
    //            for ($k = 0; $k < count($assets[$t]) - 1; $k++) {
    //                if ($assests_balance != 0)
    //                    $vert = ($assets[$t][$k]['Balance'] / $assests_balance) * 100;
    //                else
    //                    $vert = 0;
    //                if (round($assests_old_balance, 3) != 0) {
    //                    $hori = ($assets[$t][$k]['Horizental_Value'] / $assests_old_balance) * 100;
    //                    $old_vert = ($assets[$t][$k]['Old_Balance'] / $assests_old_balance) * 100;
    //                } else {
    //                    $hori = 0;
    //                    $old_vert = 0;
    //                }
    //                $assets[$t][$k]['Vertical_Analysis'] = $vert;
    //                $assets[$t][$k]['Horizental_Analysis'] = $hori;
    //                $assets[$t][$k]['Vertical_Analysis_Old'] = $old_vert;
    //                $vertical_per += $vert;
    //                $old_vertical_per += $old_vert;
    //                $horizental_per += $hori;
    //            }
    //            $assets_vertical += $vertical_per;
    //            $assets_old_vertical += $old_vertical_per;
    //            $assets_horizental += $horizental_per;
    //            $assets[$t]['Total']['Vertical_Analysis'] = $vertical_per;
    //            $assets[$t]['Total']['Vertical_Analysis_Old'] = $old_vertical_per;
    //            $assets[$t]['Total']['Horizental_Analysis'] = $horizental_per;
    //        }
    //        $assets['Debit'] = $assests_debit;
    //        $assets['Credit'] = $assests_credit;
    //        $assets['Balance'] = $assests_balance;
    //        $assets['Old_Balance'] = $assests_old_balance;
    //        $assets['Horizental_Value'] = $assests_diff_balance;
    //        $assets['Vertical_Analysis'] = $assets_vertical;
    //        $assets['Vertical_Analysis_Old'] = $assets_old_vertical;
    //        $assets['Horizental_Analysis'] = $assets_horizental;
    //
    //
    //        $liabilities_vertical = 0.0;
    //        $liabilities_old_vertical = 0.0;
    //        $liabilities_horizental = 0.0;
    //
    //        for ($t = 0; $t < count($liabilities); $t++) {
    //            $vertical_per = 0.0;
    //            $old_vertical_per = 0.0;
    //            $horizental_per = 0.0;
    //            for ($k = 0; $k < count($liabilities[$t]) - 1; $k++) {
    //                if ($liabilities_balance != 0)
    //                    $vert = ($liabilities[$t][$k]['Balance'] / $liabilities_balance) * 100;
    //                else
    //                    $liabilities_balance = 0;
    //                if (round($assests_old_balance, 3) != 0) {
    //                    $hori = ($liabilities[$t][$k]['Horizental_Value'] / $liabilities_old_balance) * 100;
    //                    $old_vert = ($liabilities[$t][$k]['Old_Balance'] / $liabilities_old_balance) * 100;
    //                } else {
    //                    $hori = 0;
    //                    $old_vert = 0;
    //                }
    //                $liabilities[$t][$k]['Vertical_Analysis'] = $vert;
    //                $liabilities[$t][$k]['Horizental_Analysis'] = $hori;
    //                $liabilities[$t][$k]['Vertical_Analysis_Old'] = $old_vert;
    //                $vertical_per += $vert;
    //                $old_vertical_per += $old_vert;
    //                $horizental_per += $hori;
    //            }
    //            $liabilities_vertical += $vertical_per;
    //            $liabilities_old_vertical += $old_vertical_per;
    //            $liabilities_horizental += $horizental_per;
    //            $liabilities[$t]['Total']['Vertical_Analysis'] = $vertical_per;
    //            $liabilities[$t]['Total']['Vertical_Analysis_Old'] = $old_vertical_per;
    //            $liabilities[$t]['Total']['Horizental_Analysis'] = $horizental_per;
    //        }
    //        $liabilities['Debit'] = $liabilities_debit;
    //        $liabilities['Credit'] = $liabilities_credit;
    //        $liabilities['Balance'] = $liabilities_balance;
    //        $liabilities['Old_Balance'] = $liabilities_old_balance;
    //        $liabilities['Horizental_Value'] = $liabilities_diff_balance;
    //        $liabilities['Vertical_Analysis'] = $liabilities_vertical;
    //        $liabilities['Vertical_Analysis_Old'] = $liabilities_old_vertical;
    //        $liabilities['Horizental_Analysis'] = $liabilities_horizental;
    //
    //
    //        $result = array('Assets' => $assets,
    //            'Liabilities' => $liabilities
    //        );
    //
    //        return $result;
    //    }
    //    public function incomeStatement($num_digits, $group_num, $from_date, $to_date, $back_up = false, $currency_id = 0, $actual_only = false) {
    //        $income_st = array();
    //        $year_id = self::getYearID(substr($from_date, 0, 4));
    //        $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
    //        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
    //        if (!$actual_only) {
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_accounting_transactions where current_year_id = "' . $year_id . '"');
    //            $start_date = $this->db->assoc($min_query)['Min_Date'];
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_mgt_logs where current_year_id = "' . $year_id_actual . '"');
    //            $temp = $this->db->assoc($min_query)['Min_Date'];
    //            if ($temp < $start_date)
    //                $start_date = $temp;
    //        }
    //        else {
    //            $min_query = $this->db->query('SELECT MIN(Transaction_Date) AS Min_Date FROM tbl_mgt_logs where current_year_id = "' . $year_id_actual . '"');
    //            $start_date = $this->db->assoc($min_query)['Min_Date'];
    //        }
    //
    //        if ($start_date == $from_date) {
    //            $balance_6_old = 0;
    //            $balance_7_old = 0;
    //        } else {
    //            $balance_6_old = self::returnExactBalance(6, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, false, true)['Balance'];
    //            $balance_7_old = self::returnExactBalance(7, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only, false, true)['Balance'];
    //        }
    //
    //        $result_6 = self::returnExactBalance(6, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only, false, true);
    //        $result_7 = self::returnExactBalance(7, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only, false, true);
    //
    //        $balance = $result_6['Balance'] + $result_7['Balance'];
    //
    //        $total_debit = $result_6['Debits'] + $result_7['Debits'];
    //        $total_credit = $result_6['Credits'] + $result_7['Credits'];
    //
    //        $old_balance = $balance_6_old + $balance_7_old;
    //
    //        $final_diff_bal = $balance - $old_balance;
    //
    //        $len_zeros_nines = $group_num - 1;
    //        $zeros = str_repeat("0", $len_zeros_nines);
    //        $nines = str_repeat("9", $len_zeros_nines);
    //        $len_zeros_nines_2 = $num_digits - $group_num;
    //        $zeros_2 = str_repeat("0", $len_zeros_nines_2);
    //        $nines_2 = str_repeat("9", $len_zeros_nines_2);
    //
    //        $debit_final = 0.0;
    //        $credit_final = 0.0;
    //        $balance_final = 0.0;
    //        $vertical_final = 0.0;
    //        $old_balance_final = 0.0;
    //        $old_vertical_final = 0.0;
    //        $horiz_analysis_final = 0.0;
    //        $horiz_value_final = 0.0;
    //
    //
    //        $a = 0;
    //        for ($i = 7; $i > 5; $i--) {
    //            $data = array();
    //            $min = $i;
    //            $max = $i . $nines;
    //            $data = self::viewExactAccounts($group_num, null, null, $min, $max, $back_up, $start_date, $to_date, 1, $actual_only);
    ////            die(print_r($data));
    //            for ($z = 0; $z < count($data); $z++) {
    //                $b = 0;
    //                $debit_p_acc = 0.0;
    //                $credit_p_acc = 0.0;
    //                $balance_p_acc = 0.0;
    //                $vertical_p_acc = 0.0;
    //                $old_balance_p_acc = 0.0;
    //                $old_vertical_p_acc = 0.0;
    //                $horiz_analysis_p_acc = 0.0;
    //                $horiz_value_p_acc = 0.0;
    //
    //                $data_2 = array();
    //                $min_2 = $data[$z];
    //                $max_2 = $data[$z] . $nines_2;
    //                $data_2 = self::viewExactAccounts($num_digits, $group_num, $min_2, $min_2, $max_2, $back_up, $start_date, $to_date, 1, $actual_only);
    ////                         die(print_r($data_2));
    //                for ($k = 0; $k < count($data_2); $k++) {
    //                    $code = $data_2[$k];
    //                    if ($start_date == $from_date)
    //                        $old_bal = 0.0;
    //                    else
    //                        $old_bal = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only)['Balance'];
    ////                    if ($code==601)
    ////                    die($old_bal);
    //                    $current_array = self::returnExactBalance($code, $currency_id, $from_date, $to_date, 0, $back_up, $actual_only);
    //                    $current_balance = $current_array['Balance'];
    //                    $diff_bal = $current_balance - $old_bal;
    //                    if (round($balance, 3) != 0)
    //                        $vertical_analysis = ($current_balance / $balance) * 100;
    //                    else
    //                        $vertical_analysis = 0;
    //                    if (round($old_balance, 3) != 0) {
    //                        $vertical_analysis_old = ($old_bal / $old_balance) * 100;
    //                        $horizental_analysis = ($diff_bal / $old_balance) * 100;
    //                    } else {
    //                        $vertical_analysis_old = 0;
    //                        $horizental_analysis = 0;
    //                    }
    //
    //
    //                    $income_st[$a][$b] = array(
    //                        'Account_Code' => $code,
    //                        'Account_Name' => self::returnAccountName($code),
    //                        'Debit' => $current_array['Debits'],
    //                        'Credit' => $current_array['Credits'],
    //                        'Balance' => $current_balance,
    //                        'Vertical_Analysis' => $vertical_analysis,
    //                        'Old_Balance' => $old_bal,
    //                        'Vertical_Analysis_Old' => $vertical_analysis_old,
    //                        'Horizental_Analysis' => $horizental_analysis,
    //                        'Horizental_Value' => $diff_bal
    //                    );
    ////                    die(print_r($income_st[$a][$b]).$a." ".$b);
    //                    $b++;
    //                    $debit_p_acc += $current_array['Debits'];
    //                    $credit_p_acc += $current_array['Credits'];
    //                    $balance_p_acc += $current_balance;
    //                    $vertical_p_acc += $vertical_analysis;
    //                    $old_balance_p_acc += $old_bal;
    //                    $old_vertical_p_acc += $vertical_analysis_old;
    //                    $horiz_analysis_p_acc += $horizental_analysis;
    //                    $horiz_value_p_acc += $diff_bal;
    //                }
    ////                die(print_r($income_st[$a][$b-1]).$a." ".$b);
    //                $income_st[$a]['Main_Account_Code'] = $data[$z];
    //                $income_st[$a]['Main_Account_Name'] = self::returnAccountName($data[$z]);
    //                $income_st[$a]['Debit_Per_Account'] = $debit_p_acc;
    //                $income_st[$a]['Credit_Per_Account'] = $credit_p_acc;
    //                $income_st[$a]['Balance_Per_Account'] = $balance_p_acc;
    //                $income_st[$a]['Old_Balance_Per_Account'] = $old_balance_p_acc;
    //                $income_st[$a]['Horizental_Value_Per_Account'] = $horiz_value_p_acc;
    //                $income_st[$a]['Vertical_Analysis_Per_Account'] = $vertical_p_acc;
    //                $income_st[$a]['Old_Vertical_Analysis_Per_Account'] = $old_vertical_p_acc;
    //                $income_st[$a]['Horizental_Analysis_Per_Account'] = $horiz_analysis_p_acc;
    //
    //                $a++;
    //                $debit_final += $debit_p_acc;
    //                $credit_final += $credit_p_acc;
    //                $balance_final += $balance_p_acc;
    //                $vertical_final += $vertical_p_acc;
    //                $old_balance_final += $old_balance_p_acc;
    //                $old_vertical_final += $old_vertical_p_acc;
    //                $horiz_analysis_final += $horiz_analysis_p_acc;
    //                $horiz_value_final += $horiz_value_p_acc;
    //            }
    //        }
    //        $income_st['Final'] = array('Final_Total_Debit' => $debit_final,
    //            'Final_Total_Credit' => $credit_final,
    //            'Final_Balance' => $balance_final,
    //            'Old_Final_Balance' => $old_balance_final,
    //            'Horizental_Value_Balance' => $horiz_value_final,
    //            'Final_Vertical_Analysis' => $vertical_final,
    //            'Final_Old_Vertical_Analysis' => $old_vertical_final,
    //            'Final_Horizental_Analysis' => $horiz_analysis_final
    //        );
    //
    //
    ////        die(print_r($income_st));
    //        return $income_st;
    //    }
    //    public function autometicDepreciationTransactions($today) {
    //        $this->db->query("START TRANSACTION");
    //        $result = self::viewDepreciationByDate($today);
    //        $jv_main = JV::returnJV(0);
    //        $jv_main_1 = JV::returnJV(1);
    //        for ($i = 0; $i < count($result) - 1; $i++) {
    //            $flag = $result[$i]['Is_Hidden'];
    //            if ($result[$i]['Is_Hidden'] == 0) {
    ////                $flag = null;
    //                $jv = $jv_main + $i;
    //            } else {
    ////                $flag = 1;
    //                $jv = $jv_main_1 + $i;
    //            }
    //
    //            $data_1 = array(
    //                "JV_ID" => $jv,
    //                "Transaction_Reference" => $result[$i]['Depreciation_Date_ID'],
    //                "Transaction_Account" => $result[$i]['Credit_Account'],
    //                "Transaction_Type" => "Credit",
    //                "Transaction_Amount" => $result[$i]['Depreciation_Amount'],
    //                "Transaction_Date" => $today,
    //                "Currency_ID" => $result[$i]['Currency_ID'],
    //                "Logged_ID" => "0",
    //                "Transaction_Description" => $result[$i]['Depreciation_Rate_Description'],
    //                "Current_Ex_Rate" => "0",
    //                "main_id" => $result[$i]['Depreciation_Date_ID'],
    //                "main_type" => 'dep'
    //            );
    //            JV::addTransaction($data_1, $flag);
    //            $data_2 = array(
    //                "JV_ID" => $jv,
    //                "Transaction_Reference" => $result[$i]['Depreciation_Date_ID'],
    //                "Transaction_Account" => $result[$i]['Debit_Account'],
    //                "Transaction_Type" => "Debit",
    //                "Transaction_Amount" => $result[$i]['Depreciation_Amount'],
    //                "Transaction_Date" => $today,
    //                "Currency_ID" => $result[$i]['Currency_ID'],
    //                "Logged_ID" => "0",
    //                "Transaction_Description" => $result[$i]['Depreciation_Rate_Description'],
    //                "Current_Ex_Rate" => "0",
    //                "main_id" => $result[$i]['Depreciation_Date_ID'],
    //                "main_type" => 'dep'
    //            );
    //            JV::addTransaction($data_2, $flag);
    //            $update = [&$result[$i]['Depreciation_Date_ID']];
    //            $this->db->prepare_Stmt("Update 
    //                                                tbl_accounting_depreciation_dates
    //                                            SET 
    //                                                Is_Done = 1 
    //                                            WHERE 
    //                                                Depreciation_Date_ID = ?
    //                        ", $update);
    //        }
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            $this->db->query('COMMIT');
    //        } else {
    //            $this->db->query('ROLLBACK');
    //        }
    //        return array_unique($error);
    //    }
    public function autometicDepreciationTransactions($date) {
        $this->db->query("START TRANSACTION");
        $prev_data = self::view_dep_trans($date);

        $logged_id = smc_session()['user_logged_id'];
        foreach ($prev_data as $prev) {

            $cur_jv = JV::returnJV($prev['Is_Hidden']);
            $data_1 = array(
                "JV_ID" => $cur_jv,
                "Transaction_Reference" => $prev['Depreciation_Date_ID'],
                "Transaction_Account" => $prev['dep_account'],
                "Transaction_Type" => "Credit",
                "Transaction_Amount" => $prev['Depreciation_Amount'],
                "Transaction_Date" => $prev['Depreciation_Date'],
                "Currency_ID" => $prev['Currency_ID'],
                "Logged_ID" => $logged_id,
                "Transaction_Description" => $prev['Depreciation_Rate_Description'],
                "Current_Ex_Rate" => $prev['current_rate'],
                "main_id" => $prev['Depreciation_Date_ID'],
                "main_type" => 'dep',
                "branch_id" => $prev['branch_id'],
                "job_id" => $prev['job_id'],
                "project_id" => $prev['project_id']
            );
            JV::addTransaction($data_1, $prev['Is_Hidden']);
            $data_2 = array(
                "JV_ID" => $cur_jv,
                "Transaction_Reference" => $prev['Depreciation_Date_ID'],
                "Transaction_Account" => $prev['pro_account'],
                "Transaction_Type" => "Debit",
                "Transaction_Amount" => $prev['Depreciation_Amount'],
                "Transaction_Date" => $prev['Depreciation_Date'],
                "Currency_ID" => $prev['Currency_ID'],
                "Logged_ID" => $logged_id,
                "Transaction_Description" => $prev['Depreciation_Rate_Description'],
                "Current_Ex_Rate" => $prev['current_rate'],
                "main_id" => $prev['Depreciation_Date_ID'],
                "main_type" => 'dep',
                "branch_id" => $prev['branch_id'],
                "job_id" => $prev['job_id'],
                "project_id" => $prev['project_id']
            );
            JV::addTransaction($data_2, $prev['Is_Hidden']);
            $update = [&$prev['Depreciation_Date_ID']];
            $this->db->prepare_Stmt("Update 
                                                    tbl_accounting_depreciation_dates
                                                SET 
                                                    Is_Done = 1 
                                                WHERE 
                                                    Depreciation_Date_ID = ?
                            ", $update);
        }

        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    //    public function viewDepreciationByDate($today = null, $date_from = null, $date_to = null, $max_date = null, $dep_id = null, $is_hidden = false) {
    //        $total = 0.0;
    //        $data = array();
    //        $condition = '';
    //        if (!is_null($today))
    //            $condition .= ' AND Depreciation_Date <= "' . $today . '" AND Is_Done = 0';
    //        else {
    //            if (!is_null($date_from) and ! is_null($date_to))
    //                $condition .= ' AND Depreciation_Date >= "' . $date_from . '" AND Depreciation_Date <= "' . $date_to . '" ';
    //            if (!is_null($max_date))
    //                $condition .= ' AND Depreciation_Date <= "' . $max_date . '" ';
    //            if (!is_null($dep_id))
    //                $condition .= ' AND Depreciation_Rate_ID = "' . $dep_id . '"';
    //            if (!$is_hidden)
    //                $condition .= ' AND Is_Hidden = 0';
    //            $condition .= ' AND Is_Done = 1';
    //        }
    //        $query = $this->db->query('SELECT * FROM viewdepreciationfulldata where 1=1
    //                                    ' . $condition
    //        );
    //        while ($row = $this->db->assoc($query)) {
    //            $total += $row['Depreciation_Amount'];
    //            $data[] = $row;
    //        }
    //        $data['Total'] = $total;
    //        return $data;
    //    }
    //    public function viewDepreciationMainDetails($date_from = null, $date_to = null, $is_hidden = false) {
    //        $data = array();
    //        $total = 0.0;
    //        $year_total = 0.0;
    //        $condition = '';
    //        if (!is_null($date_from) and ! is_null($date_to))
    //            $condition .= ' AND Depreciation_Date >= "' . $date_from . '" AND a.Depreciation_Date <= "' . $date_to . '"';
    //        if (!$is_hidden)
    //            $condition .= ' AND Is_Hidden =0';
    //        $query = $this->db->query('SELECT 
    //                                        *
    //                                        FROM 
    //                                            fixed_assets_register
    //                                    WHERE 
    //                                        1=1 ' . $condition . '
    //                ');
    //        while ($row = $this->db->assoc($query)) {
    //            $year_sum_default = CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Year_Sum_Dep']);
    //            $sum_dep_default = CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Sum_Dep']);
    //
    //            $total += $sum_dep_default;
    //            $year_total += $year_sum_default;
    //            $data[] = $row;
    //        }
    //        $data['Total_Depreciations'] = $total;
    //        $data['Year_Total_Depreciations'] = $year_total;
    //        return $data;
    //    }

    public function returnAccountName($code, $with_currency = null) {
        $query = $this->db->query('SELECT a.Account_Name,c.Currency_Code FROM tbl_chart_of_accounts a
                left join tbl_common_currency c on a.Currency_ID = c.Currency_ID
                WHERE Account_Code = "' . $code . '"');
        $row = $this->db->assoc($query);
        return (!is_null($with_currency) ? $row['Account_Name'] . (empty($row['Currency_Code']) ? '' : ' - ' . $row['Currency_Code']) : $row['Account_Name']);
    }

    //    private function returnBalanceByAccount($left_code = null, $len = null, $year = null, $code = null, $back_up = false, $currency_id = 0, $only_back_up = false, $from_date = null, $to_date = null, $jv_id = null) {
    //        if ($currency_id == 0)
    //            $currency_id = CurrencyFactory::getDefaultCurrency();
    //        $local_currency = CurrencyFactory::returnLocalCurrency();
    //        $data = array();
    //        $condition = '';
    //        $balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        if (!is_null($left_code))
    //            $condition .= ' AND LEFT(Transaction_Account,' . $len . ') = "' . $left_code . '" ';
    //        if (!is_null($jv_id))
    //            $condition .= ' AND JV_ID = "' . $jv_id . '" ';
    //        if (!is_null($code))
    //            $condition .= ' AND Transaction_Account = "' . $code . '" ';
    //        if (!is_null($year)) {
    //
    //            $condition .= ' AND YEAR(Transaction_Date) = "' . $year . '" ';
    //        }
    //
    //        if (!is_null($from_date) and ! is_null($to_date)) {
    //
    //            $condition .= ' AND Transaction_Date >= "' . $from_date . '" AND Transaction_Date <= "' . $to_date . '" ';
    //        }
    //
    //        if (!$only_back_up) {
    //            $year_id = self::getYearID(substr($from_date, 0, 4));
    //            $query = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_accounting_transactions 
    //                                        WHERE  
    //                                            current_year_id = "' . $year_id . '"
    //                    ' . $condition);
    //            while ($row = $this->db->assoc($query)) {
    //                if ($row['Transaction_Type'] == 'Debit') {
    //
    //                    if ($currency_id == $local_currency) {
    //                        if ($row['Currency_ID'] == $local_currency) {
    //                            $debits += $row['Transaction_Amount'];
    //                            $balance += $row['Transaction_Amount'];
    //                        } else {
    //                            $debits += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                            $balance += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                        }
    //                    } else {
    //                        $debits += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                        $balance += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                    }
    //                } elseif ($row['Transaction_Type'] == 'Credit') {
    //
    //                    if ($currency_id == $local_currency) {
    //                        if ($row['Currency_ID'] == $local_currency) {
    //                            $credits += $row['Transaction_Amount'];
    //                            $balance -= $row['Transaction_Amount'];
    //                        } else {
    //                            $credits += CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                            $balance -= CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                        }
    //                    } else {
    //                        $credits += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                        $balance -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
    //                    }
    //                }
    //            }
    //        }
    //        if ($back_up) {
    //            $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
    //
    //            $query2 = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_mgt_logs 
    //                                        WHERE  
    //                                            current_year_id = "' . $year_id_actual . '"
    //                    ' . $condition);
    //            while ($row2 = $this->db->assoc($query2)) {
    //                if ($row2['Transaction_Type'] == 'Debit') {
    //
    //                    if ($currency_id == $local_currency) {
    //                        if ($row2['Currency_ID'] == $local_currency) {
    //                            $debits += $row2['Transaction_Amount'];
    //                            $balance += $row2['Transaction_Amount'];
    //                        } else {
    //                            $debits += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                            $balance += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                        }
    //                    } else {
    //                        $debits += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                        $balance += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                    }
    //
    ////                   if($currency_id != 0) {
    ////                        $debits  += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                        $balance      += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                    }
    ////                    else {
    ////                        $debits  += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                        $balance      += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                    }
    //                } elseif ($row2['Transaction_Type'] == 'Credit') {
    //                    if ($currency_id == $local_currency) {
    //                        if ($row2['Currency_ID'] == $local_currency) {
    //                            $credits += $row2['Transaction_Amount'];
    //                            $balance -= $row2['Transaction_Amount'];
    //                        } else {
    //                            $credits += CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                            $balance -= CurrencyFactory::returnExchangedValueByExchangedID($row2['Exchange_Rate_ID'], $row2['Transaction_Amount'], $row2['Currency_ID']);
    //                        }
    //                    } else {
    //                        $credits += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                        $balance -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'], $currency_id, $row2['Transaction_Amount']);
    //                    }
    //
    //
    ////                    if($currency_id != 0) {
    ////                        $credits += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                        $balance      -= CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row2['Currency_ID'],$currency_id,$row2['Transaction_Amount']);
    ////                    }
    ////                    else {
    ////                        $credits += CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                        $balance      -= CurrencyFactory::returnPriceInDefaultCurrencyValue($row2['Currency_ID'],$row2['Transaction_Amount']);
    ////                    }
    //                }
    //            }
    //        }
    //        $result = array(
    //            'Credit' => $credits,
    //            'Debit' => $debits,
    //            'Balance' => $balance
    //        );
    //        return $result;
    //    }

    public function returnAccountsToBeClosed($year_id, $first_accounts = false, $second_accounts = false, $flag = null) {
        $data = array();
        $condition = '';
        if ($first_accounts)
            $condition .= ' AND LEFT (a.Account_Code,1) < 6';
        if ($second_accounts)
            $condition .= ' AND (LEFT (a.Account_Code,1) = 6 OR LEFT (a.Account_Code,1) = 7)';
        //        if (is_null($flag))
        //            $table = 'tbl_accounting_transactions';
        //        else
        //            $table = 'tbl_mgt_logs';
        $query = $this->db->query('SELECT 
                                            a.Account_Code,
                                            a.Account_ID
                                        FROM 
                                            tbl_accounting_transactions t join tbl_chart_of_accounts a 
                                                on a.Account_ID = t.Account_ID
                                        WHERE 
                                            current_year_id = "' . $year_id . '" ' . $condition . '
                                                and t.is_actual = "' . $flag . '"
                                        GROUP BY
                                            a.Account_Code

                    ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    //    public function closeYear($logged_id, $actual = false) {
    //        $this->db->query("START TRANSACTION");
    //        $flag = $actual ? 1 : 0;
    //        $currency_id = CurrencyFactory::returnLocalCurrency();
    //
    //        $transactions = self::closeYearTransactionsList($actual);
    ////        $j= 0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $last_index = count($transactions) - 1;
    //        $net_result = $transactions[$last_index]['Amount'];
    //        $next_year_id = $transactions[$last_index]['current_year_id'];
    //        for ($i = 0; $i < count($transactions); $i++) {
    //            $data = array(
    //                "JV_ID" => $transactions[$i]['JV_ID'],
    //                "Transaction_Reference" => $transactions[$i]['Ref'],
    //                "Transaction_Account" => $transactions[$i]['ID'],
    //                "Transaction_Type" => $transactions[$i]['Type'],
    //                "Transaction_Amount" => $transactions[$i]['Amount'],
    //                "Transaction_Date" => $transactions[$i]['Date'],
    //                "Currency_ID" => $currency_id,
    //                "Logged_ID" => $logged_id,
    //                "Transaction_Description" => $transactions[$i]['Description'],
    //                "Current_Ex_Rate" => "0",
    //                "current_year_id" => $transactions[$i]['current_year_id'],
    //                "main_id" => "0",
    //                "main_type" => 'cly'
    //            );
    //            JV::addTransaction($data, $flag);
    //            if ($transactions[$i]['Type'] == "Debit")
    //                $debits += $transactions[$i]['Amount'];
    //            else
    //                $credits += $transactions[$i]['Amount'];
    //        }
    //
    //        $today = Date::getToday();
    //        if ($actual)
    //            $table = "tbl_common_current_year_actual";
    //        else
    //            $table = "tbl_common_current_year";
    //
    //        $is_current = "0";
    //        $is_current2 = "1";
    //        $update = [
    //            &$debits,
    //            &$credits,
    //            &$net_result,
    //            &$today,
    //            &$logged_id,
    //            &$is_current,
    //            &$is_current2
    //        ];
    //
    //        $this->db->prepare_Stmt("UPDATE
    //                                        " . $table . "
    //                                    SET 
    //                                        total_debits = ?,
    //                                        total_credits = ?,
    //                                        result_of_year = ?,
    //                                        closing_date = ?,
    //                                        closed_by = ?,   
    //                                        is_current = ?
    //                                    WHERE   
    //                                        is_current = ?
    //                ", $update);
    //        $update2 = [&$is_current2, &$next_year_id];
    //        $this->db->prepare_Stmt("UPDATE
    //                                    " . $table . "
    //                                SET 
    //                                    is_current = ?
    //                                WHERE   
    //                                    current_year_id = ?", $update2);
    ////                $error = $this->db->error();
    ////        die(print_r($error));
    //        $error = $this->db->error();
    //        if (empty($error)) {
    //            $this->db->query('COMMIT');
    //        } else {
    //            $this->db->query('ROLLBACK');
    //        }
    //        return array_unique($error);
    //    }
    //
    //    public function closeYearTransactionsList($actual = false) {
    ////        $today          = Date::getToday();
    //        $currency_id = CurrencyFactory::returnLocalCurrency();
    //        $currency_Symbol = CurrencyFactory::getLocalCurrencySymbol();
    //        if (!$actual) {
    //            $year_id = Session::getCurrentYearID();
    //            $year = Session::getCurrentYear();
    //            $flag = 0;
    //        } else {
    //            $year_id = Session::getCurrentYearIDActual();
    //            $year = Session::getCurrentYearActual();
    //            $flag = 1;
    //        }
    //
    //        $accounts_first = self::returnAccountsToBeClosed($year_id, true, false, $flag);
    ////        $j = 0;
    //        $jv_1 = JV::returnJV($flag);
    //        $jv_2 = 1;
    //        $second_year = $year + 1;
    //        $check_exists = $this->db->query('SELECT current_year_id FROM tbl_common_current_year WHERE current_year = "' . $second_year . '"');
    //        $is_exists = $this->db->assoc($check_exists);
    //        if (!is_null($is_exists['current_year_id']))
    //            $next_year_id = $is_exists['current_year_id'];
    //        else {
    //            $insert = [&$second_year];
    //            $this->db->prepare_Stmt("INSERT INTO tbl_common_current_year SET current_year = ?", $insert);
    //            $select = $this->db->query('SELECT current_year_id FROM tbl_common_current_year WHERE current_year = "' . $second_year . '"');
    //            $next_year_id = $this->db->assoc($select)['current_year_id'];
    //        }
    //        $ref = ($year) . '-' . ($second_year);
    //        $from_date = $year . '-01-01';
    //        $to_date = $year . '-12-31';
    //        $date_1 = $to_date;
    //        $date_2 = $second_year . '-01-01';
    //
    //        $desc_1 = 'Closing of year';
    //        $desc_2 = 'Opening of year';
    //        $trans_close = array();
    //
    ////        $old_pos = 0;
    ////        $old_neg = 0;
    //        $old = 0;
    //        $sum = 0;
    //        for ($i = 0; $i < count($accounts_first); $i++) {
    //            $account_code = $accounts_first[$i]['Account_Code'];
    //            $account_id = $accounts_first[$i]['Account_ID'];
    //            $account_name = self::returnAccountName($account_code);
    //            $options = ["Account_ID" => $account_code, "Currency_ID" => $currency_id,
    //                "From_Date" => $from_date, "To_Date" => $to_date, "Opening_Balance" => true, "Is_Actual" => $actual];
    //            $temp = self::returnExactBalance($options);
    //
    //            if ($account_code == "139" or $account_code == "138") {
    //                $old += $temp['Balance'];
    //                if ($temp['Balance'] < 0) {
    //                    $temp['Balance'] = $temp['Balance'] * (-1);
    //                    $type_1 = 'Debit';
    //                } else {
    //
    //                    $type_1 = 'Credit';
    //                }
    //                $trans_close[] = array("JV_ID" => $jv_1,
    //                    "Ref" => $ref,
    //                    "ID" => $account_id,
    //                    "Code" => $account_code,
    //                    "Name" => $account_name,
    //                    "Type" => $type_1,
    //                    "Amount" => $temp['Balance'],
    //                    "Currency_Symbol" => $currency_Symbol,
    //                    "Date" => $date_1,
    //                    "Description" => $desc_1,
    //                    "current_year_id" => $year_id
    //                );
    //                $temp['Balance'] = 0;
    //            }
    //
    //            if ($temp['Balance'] > 0) {
    //                $type_1 = 'Credit';
    //                $type_2 = 'Debit';
    //            } else {
    //                $temp['Balance'] = $temp['Balance'] * (-1);
    //                $type_1 = 'Debit';
    //                $type_2 = 'Credit';
    //            }
    //            if (round($temp['Balance'], 3) != 0) {
    //                $trans_close[] = array("JV_ID" => $jv_1,
    //                    "Ref" => $ref,
    //                    "ID" => $account_id,
    //                    "Code" => $account_code,
    //                    "Name" => $account_name,
    //                    "Type" => $type_1,
    //                    "Amount" => $temp['Balance'],
    //                    "Currency_Symbol" => $currency_Symbol,
    //                    "Date" => $date_1,
    //                    "Description" => $desc_1,
    //                    "current_year_id" => $year_id
    //                );
    //
    //                $trans_close[] = array("JV_ID" => $jv_2,
    //                    "Ref" => $ref,
    //                    "ID" => $account_id,
    //                    "Code" => $account_code,
    //                    "Name" => $account_name,
    //                    "Type" => $type_2,
    //                    "Amount" => $temp['Balance'],
    //                    "Currency_Symbol" => $currency_Symbol,
    //                    "Date" => $date_2,
    //                    "Description" => $desc_2,
    //                    "current_year_id" => $next_year_id
    //                );
    //            }
    //        }
    //
    //        $accounts_second = self::returnAccountsToBeClosed($year_id, false, true, $flag);
    ////        die(print_r($trans_close));
    ////        $sum = 0.0;
    //        for ($i = 0; $i < count($accounts_second); $i++) {
    //            $account_code = $accounts_second[$i]['Account_Code'];
    //            $account_id = $accounts_second[$i]['Account_ID'];
    //            $account_name = self::returnAccountName($account_code);
    //            $options = ["Account_ID" => $account_code, "Currency_ID" => $currency_id,
    //                "From_Date" => $from_date, "To_Date" => $to_date, "Opening_Balance" => true, "Is_Actual" => $actual];
    //            $temp = self::returnExactBalance($options);
    //
    //            if ($temp['Balance'] > 0) {
    //                $sum += $temp['Balance'];
    //                $type_1 = 'Credit';
    //                $type_2 = 'Debit';
    //            } else {
    //                $sum += $temp['Balance'];
    //                $temp['Balance'] = $temp['Balance'] * (-1);
    //                $type_1 = 'Debit';
    //                $type_2 = 'Credit';
    //            }
    //            $trans_close[] = array("JV_ID" => $jv_1,
    //                "Ref" => $ref,
    //                "ID" => $account_id,
    //                "Code" => $account_code,
    //                "Name" => $account_name,
    //                "Type" => $type_1,
    //                "Amount" => $temp['Balance'],
    //                "Currency_Symbol" => $currency_Symbol,
    //                "Date" => $date_1,
    //                "Description" => $desc_1,
    //                "current_year_id" => $year_id
    //            );
    //        }
    //        if (count($trans_close) > 0) {
    ////            die($sum.' pos');
    //            $ids_arr = JV::getAccountIDsByCodes(['139', '138']);
    //            $sum += $old;
    //            if ($sum > 0) {
    //                $type_2 = 'Debit';
    //                $diff_code = '139';
    //                $diff_id = $ids_arr['139'];
    //            } else {
    //                $sum = $sum * (-1);
    //                $diff_code = '138';
    //                $diff_id = $ids_arr['138'];
    //                $type_2 = "Credit";
    //            }
    //
    //            $account_name = self::returnAccountName($diff_code);
    //            $trans_close[] = array("JV_ID" => $jv_2,
    //                "Ref" => $ref,
    //                "ID" => $diff_id,
    //                "Code" => $diff_code,
    //                "Name" => $account_name,
    //                "Type" => $type_2,
    //                "Amount" => $sum,
    //                "Currency_Symbol" => $currency_Symbol,
    //                "Date" => $date_2,
    //                "Description" => $desc_2,
    //                "current_year_id" => $next_year_id
    //            );
    //        }
    //        return $trans_close;
    //    }
    //    public function retrieveDailyJVsByRange($from_date = null, $to_date = null, $from_jv = null, $to_jv = null, $back_up = false) {
    //        $data = array();
    //        $jvs = array();
    //        $dates = array();
    //        $condition = '';
    //        $local_currency = CurrencyFactory::returnLocalCurrency();
    //        //min and max jv and dates
    //        if (!is_null($from_date) and ! is_null($to_date)) {
    //            $condition .= ' AND t.Transaction_Date >= "' . $from_date . '" AND t.Transaction_Date <= "' . $to_date . '"';
    //        }
    //        if (!is_null($from_jv) and ! is_null($to_jv))
    //            $condition .= ' AND t.JV_ID >= "' . $from_jv . '" AND t.JV_ID <= "' . $to_jv . '"';
    //        if ($back_up) {
    //            $year_id = Session::getCurrentYearIDActual();
    //            $table = 'tbl_mgt_logs';
    //        } else {
    //            $year_id = Session::getCurrentYearID();
    //            $table = 'tbl_accounting_transactions';
    //        }
    //        $query = $this->db->query('SELECT 
    //                                        DISTINCT t.JV_ID,
    //                                        CONCAT(e.Employee_FirstName," ",e.Employee_MiddleName," ",e.Employee_LastName) AS Employee_Name,
    //                                        t.Transaction_Date
    //                                    FROM 
    //                                        ' . $table . ' t
    //                                    LEFT JOIN
    //                                        tbl_common_users u
    //                                    ON
    //                                        u.User_ID =  t.Logged_ID
    //                                    LEFT JOIN
    //                                        tbl_hrm_employee e
    //                                    ON
    //                                        e.Employee_ID =  u.Employee_ID
    //                                    WHERE 
    //                                        t.current_year_id = "' . $year_id . '" ' . $condition . '
    //                                    ORDER BY 
    //                                        t.Transaction_ID
    //                   ');
    //        $i = 0;
    //        $first_total_debit = 0.0;
    //        $first_total_credit = 0.0;
    //        $local_total = 0.0;
    //        $first_currency = CurrencyFactory::getCurrencyByPlacement(1);
    //        $second_currency = CurrencyFactory::getCurrencyByPlacement(2);
    //        $third_currency = CurrencyFactory::getCurrencyByPlacement(3);
    //        while ($row = $this->db->assoc($query)) {
    //            $jvs[] = $row['JV_ID'];
    //            $dates[] = $row['Transaction_Date'];
    //            $trans = $this->db->query('SELECT 
    //                                            t.Transaction_Amount,
    //                                            t.Currency_ID,
    //                                            c.Currency_Symbol,
    //                                            t.Exchange_Rate_ID,
    //                                            t.Transaction_Description,
    //                                            e.ExchRate,
    //                                            CONCAT(a.Account_Name,", ", t.Transaction_Account) AS Account
    //                                        FROM 
    //                                            ' . $table . ' t
    //                                        LEFT JOIN 
    //                                            tbl_common_currency c
    //                                        ON 
    //                                            c.Currency_ID = t.Currency_ID
    //                                        LEFT JOIN 
    //                                            tbl_chart_of_accounts a
    //                                        ON 
    //                                            a.Account_Code = t.Transaction_Account
    //                                        LEFT JOIN 
    //                                            tbl_currencies_rate e
    //                                        ON 
    //                                            e.Exchange_Rate_ID = t.Exchange_Rate_ID
    //                                        
    //                                        WHERE 
    //                                            t.JV_ID = "' . $row['JV_ID'] . '"
    //                                        AND  
    //                                            t.Transaction_Type = "Debit"
    //                                            and t.current_year_id = "' . $year_id . '"
    //                    ');
    //            $count_small = 0;
    //            $j = 0;
    //            while ($row_trans = $this->db->assoc($trans)) {
    //                $count_small++;
    //                $data[$i][$j]['Credit'] = 0;
    //                $data[$i][$j]['Debit'] = $row_trans['Transaction_Amount'];
    //                $data[$i][$j]['Account'] = $row_trans['Account'];
    //                $data[$i][$j]['Currency_Symbol'] = $row_trans['Currency_Symbol'];
    //                $data[$i][$j]['Transaction_Description'] = $row_trans['Transaction_Description'];
    //                if (!is_null($row_trans['ExchRate']))
    //                    $data[$i][$j]['ExchRate'] = $row_trans['ExchRate'];
    //                else
    //                    $data[$i][$j]['ExchRate'] = 0;
    //                if ($local_currency != $row_trans['Currency_ID'])
    //                    $data[$i][$j]['Local_Amount'] = CurrencyFactory::returnExchangedValueByExchangedID($row_trans['Exchange_Rate_ID'], $row_trans['Transaction_Amount'], $row_trans['Currency_ID']);
    //                else
    //                    $data[$i][$j]['Local_Amount'] = $row_trans['Transaction_Amount'];
    //                $first_total_debit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row_trans['Currency_ID'], $first_currency['Currency_ID'], $data[$i][$j]['Debit']);
    //                $local_total += $data[$i][$j]['Local_Amount'];
    //                $j++;
    //            }
    //
    //            $trans_2 = $this->db->query('SELECT 
    //                                            t.Transaction_Amount,
    //                                            t.Currency_ID,
    //                                            c.Currency_Symbol,
    //                                            t.Exchange_Rate_ID,
    //                                            t.Transaction_Description,
    //                                            e.ExchRate,
    //                                            CONCAT(a.Account_Name,", ", t.Transaction_Account) AS Account
    //                                        FROM 
    //                                            ' . $table . ' t
    //                                        LEFT JOIN 
    //                                            tbl_common_currency c
    //                                        ON 
    //                                            c.Currency_ID = t.Currency_ID
    //                                        LEFT JOIN 
    //                                            tbl_chart_of_accounts a
    //                                        ON 
    //                                            a.Account_Code = t.Transaction_Account
    //                                        LEFT JOIN 
    //                                            tbl_currencies_rate e
    //                                        ON 
    //                                            e.Exchange_Rate_ID = t.Exchange_Rate_ID
    //                                        
    //                                        
    //                                        WHERE 
    //                                            t.JV_ID = "' . $row['JV_ID'] . '"
    //                                        AND  
    //                                            t.Transaction_Type = "Credit"
    //                                            and
    //                                            
    //                                        current_year_id = "' . $year_id . '"
    //                    ');
    //            while ($row_trans2 = $this->db->assoc($trans_2)) {
    //                $count_small++;
    //                $data[$i][$j]['Credit'] = $row_trans2['Transaction_Amount'];
    //                $data[$i][$j]['Debit'] = 0;
    //                $data[$i][$j]['Account'] = $row_trans2['Account'];
    //                $data[$i][$j]['Currency_Symbol'] = $row_trans2['Currency_Symbol'];
    //                $data[$i][$j]['Transaction_Description'] = $row_trans2['Transaction_Description'];
    //                if (!is_null($row_trans2['ExchRate']))
    //                    $data[$i][$j]['ExchRate'] = $row_trans2['ExchRate'];
    //                else
    //                    $data[$i][$j]['ExchRate'] = 0;
    //                if ($local_currency != $row_trans2['Currency_ID'])
    //                    $data[$i][$j]['Local_Amount'] = CurrencyFactory::returnExchangedValueByExchangedID($row_trans2['Exchange_Rate_ID'], $row_trans2['Transaction_Amount'], $row_trans2['Currency_ID']);
    //                else
    //                    $data[$i][$j]['Local_Amount'] = $row_trans2['Transaction_Amount'];
    //                $first_total_credit += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row_trans2['Currency_ID'], $first_currency['Currency_ID'], $data[$i][$j]['Credit']);
    //                $local_total -= $data[$i][$j]['Local_Amount'];
    //                $j++;
    //            }
    //            $data[$i]['Employee_Name'] = $row['Employee_Name'];
    //            $data[$i]['Transaction_Date'] = $row['Transaction_Date'];
    //            $data[$i]['JV_ID'] = $row['JV_ID'];
    //            $data[$i]['Count_Transactions'] = $count_small;
    //            $i++;
    //        }
    //
    //        $jvs = array_unique($jvs);
    //        $dates = array_unique($dates);
    //        if (count($dates) > 0) {
    //            $max_jv = max($jvs);
    //            $min_jv = min($jvs);
    //            $max_date = max($dates);
    //            $min_date = min($dates);
    //        } else {
    //            $today = Date::getToday();
    //            $max_jv = null;
    //            $min_jv = null;
    //            $min_date = $today;
    //            $max_date = $today;
    //        }
    //        $data['Max_JV'] = $max_jv;
    //        $data['Min_JV'] = $min_jv;
    //        $data['Max_Date'] = $max_date;
    //        $data['Min_Date'] = $min_date;
    //
    //        $data['First_Total'] = array("Credit" => $first_total_credit,
    //            "Debit" => $first_total_debit,
    //            "Symbol" => $first_currency['Currency_Symbol']
    //        );
    //        $data['Local_Total'] = array("Total" => $local_total,
    //            "Symbol" => CurrencyFactory::getLocalCurrencySymbol()
    //        );
    //        if (is_null($second_currency['Currency_Symbol'])) {
    //            $data['Second_Total'] = array();
    //        } else {
    //            $data['Second_Total'] = array("Credit" => CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($first_currency['Currency_ID'], $second_currency['Currency_ID'], $first_total_credit),
    //                "Debit" => CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($first_currency['Currency_ID'], $second_currency['Currency_ID'], $first_total_debit),
    //                "Symbol" => $second_currency['Currency_Symbol']
    //            );
    //        }
    //        if (is_null($third_currency['Currency_Symbol'])) {
    //            $data['Third_Total'] = array();
    //        } else {
    //            $data['Third_Total'] = array("Credit" => CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($first_currency['Currency_ID'], $third_currency['Currency_ID'], $first_total_credit),
    //                "Debit" => CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($first_currency['Currency_ID'], $third_currency['Currency_ID'], $first_total_debit),
    //                "Symbol" => $third_currency['Currency_Symbol']
    //            );
    //        }
    //
    //        return $data;
    //    }

    private function getYearID($year, $flag = null) {
        if (!is_null($flag))
            $table = 'tbl_common_current_year_actual';
        else
            $table = 'tbl_common_current_year';
        $query = $this->db->query('SELECT current_year_id FROM ' . $table . ' WHERE current_year = "' . $year . '"');
        $year = $this->db->assoc($query)['current_year_id'];
        return $year;
    }

    //    public function returnExactBalanceByID($account_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false) {
    public function returnExactBalanceByID($options) {
        //                echo"<pre>";die(print_r($options));
        $condition = '';
        $balance = 0.0;
        $local_balance = 0.0;
        $second_balance = 0.0;
        $debits = 0.0;
        $credits = 0.0;
        $debits_local = 0.0;
        $credits_local = 0.0;
        $debits_second = 0.0;
        $credits_second = 0.0;

        if (!empty($options['cond'])) {
            $condition .= $options['cond'];
        }
        if (!empty($options['Account_ID']))
            $condition .= ' AND t.Account_ID  in (' . $options['Account_ID'] . ') ';
        //echo"<pre>";die(print_r($options)); 
        $currency_id = empty($options['Currency_ID']) ? CurrencyFactory::getDefaultCurrency() : $options['Currency_ID'];
        if (!empty($options['is_trial_balance'])) {
            if (!empty($options['opening_only']) && $options['opening_only'] == 1)
                $condition .= '  and t.main_type="opy" ';
            elseif (!empty($options['Opening_Balance']) || $options['Opening_Balance'] == 0)
                $condition .= ' and t.main_type <> "opy" ';
        }
        if (!empty($options['Opening_Balance'])) {
            if (!empty($options['From_Date']) && !empty($options['due_date_from']))
                $condition .= 'and (t.Transaction_Date <= "' . $options['To_Date'] . '" or t.due_date <= "' . $options['due_date_from'] . '") ';
            else {
                if (!empty($options['From_Date']))
                    $condition .= ' and t.Transaction_Date <= "' . $options['To_Date'] . '"';
                if (!empty($options['due_date_from']))
                    $condition .= '  and t.due_date <= "' . $options['due_date_from'] . '"';
            }
            //            if (!empty($options['from_create_time']))
            //                $condition .= ' and t.date_created <= "' . $options['to_create_time'] . '"';
        }
        if (isset($options['close_only'])) {
            if ($options['close_only'] == 1)
                $condition .= '  and t.main_type="cly" ';
        }
        elseif (isset($options['with_close'])) {
            if ($options['with_close'] == 0)
                $condition .= ' and t.main_type <> "cly" ';
        }
        //
        if (!empty($options['From_Date']) && !empty($options['To_Date']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.Transaction_Date between "' . $options['From_Date'] . '" and "' . $options['To_Date'] . '" ';
        if (!empty($options['due_date_from']) && !empty($options['due_date_to']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.due_date between "' . $options['due_date_from'] . '"  and "' . $options['due_date_to'] . '" ';
        if (!empty($options['from_create_time']) && !empty($options['to_create_time']) && empty($options['opening_only']) && empty($options['close_only']) /* && empty($options['Opening_Balance']) */)
            $condition .= ' and t.date_created between "' . $options['from_create_time'] . '" and "' . $options['to_create_time'] . '" ';
        if (isset($options['Is_Actual']) && $options['Is_Actual'] == 0) {
            $condition .= ' and t.is_actual = 0  ';
        } elseif (isset($options['Actual_Only']) && $options['Actual_Only']) {
            $condition .= ' and t.is_actual = 1  ';
        }
        //        else
        //            $condition .=' and ((t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '") 
        //                or ( t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '")) ';

        if (!empty($options['trans_type']) && $options['trans_type'] != '') {
            $condition .= ' and t.main_type in ("' . implode('","', $options['trans_type']) . '") ';
        }
        if (!empty($options['debit_credit_type']) && $options['debit_credit_type'] != 'All') {
            $condition .= ' and t.Transaction_Type = "' . $options['debit_credit_type'] . '" ';
        }
        if (!empty($options['from_jv'])) {
            $condition .= ' and t.JV_ID >= "' . $options['from_jv'] . '" ';
        }
        if (!empty($options['to_jv'])) {
            $condition .= ' and  t.JV_ID <= "' . $options['to_jv'] . '"';
        }
        //        if (!empty($options['from_account'])) {
        //            $condition .= ' and left(t.Transaction_Account,' . strlen($options['from_account']) . ') >= "' . $options['from_account'] . '" ';
        //        }
        //        if (!empty($options['to_account'])) {
        //            $condition .= ' and  left(t.Transaction_Account,' . strlen($options['from_account']) . ') <= "' . $options['to_account'] . '"';
        //        }
        if (!empty($options['from_amount'])) {
            $condition .= ' and t.Transaction_Amount >= "' . $options['from_amount'] . '" ';
        }
        if (!empty($options['to_amount'])) {
            $condition .= ' and  t.Transaction_Amount <= "' . $options['to_amount'] . '"';
        }
        if (!empty($options['job_ids'])) {
            $condition .= ' and t.job_id in (' . $options['job_ids'] . ')';
        }
        if (!empty($options['project_ids'])) {
            $condition .= ' and t.project_id in (' . $options['project_ids'] . ')';
        }
        if (!empty($options['multi_accounts'])) {
            $condition .= ' and t.Account_ID in (' . $options['multi_accounts'] . ')';
        }
        if (!empty($options['family_acc'])) {
            $family_accs = CommonACC::get_family_accs_by_id($options['family_acc']);
            $condition .= ' and t.Account_ID in (' . $family_accs . ')';
        }
        if (!empty($options['ref_type'])) {
            $condition .= ' and t.subtype in ("' . implode('","', explode(",", $options['ref_type'])) . '") and t.main_type="mjv" ';
        }
        if (!empty($options['trans_currency'])) {
            $condition .= ' and t.Currency_ID ="' . $options['trans_currency'] . '"';
        }
        if (!empty($options['branch_id'])) {
            $condition .= ' and t.branch_id ="' . $options['branch_id'] . '"';
        }
        if (!empty($options['salesman_id'])) {
            $condition .= ' and t.salesman_id ="' . $options['salesman_id'] . '"';
        }
        if (!empty($options['pos_customer_id'])) {
            $condition .= ' and t.pos_customer_id ="' . $options['pos_customer_id'] . '"';
        }


        if(Session::getPermissionsObject()->hasPermission('Branches')){
            $condition .= !empty($options['search_branch_id']) ? ' and t.branch_id ="' . ($options['search_branch_id']) . '"' : '';
        }else{
            $condition .= ' and t.branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        //        if (!empty($options['multi_year'])) {
        //            $condition .=' and t.main_type not in ("cly","opy") ';
        //        }else{ 
        $condition .= ' and t.current_year_id = "' . $this->year_id . '" ';
        //        }
        //        if($options['Account_ID'] ==3782){
        //                echo('SELECT 
        //                                                t.Transaction_Reference,
        //                                                t.Currency_ID,
        //                                                t.Account_ID,
        //                                                t.Transaction_Amount,
        //                                                t.Current_Ex_Rate,
        //                                                t.second_currency_rate,
        //                                                t.Exchange_Rate_ID,
        //                                                t.Transaction_Type,
        //                                                t.local_amount,
        //                                                (t.Transaction_Amount*t.second_currency_rate) as second_amount,
        //                                                t.main_type
        //                                            FROM tbl_accounting_transactions t  
        //                                            WHERE 1=1
        //                                             ' . $condition . '<br>');
        //        }
        $acc_arr = array();
        $query = $this->db->query('SELECT 
                                                t.Transaction_Reference,
                                                t.Currency_ID,
                                                t.Account_ID,
                                                t.Transaction_Amount,
                                                t.Current_Ex_Rate,
                                                t.second_currency_rate,
                                                t.Exchange_Rate_ID,
                                                t.Transaction_Type,
                                                t.local_amount,
                                                (t.Transaction_Amount*t.second_currency_rate) as second_amount,
                                                t.main_type
                                            FROM tbl_accounting_transactions t  
                                            WHERE 1=1
                                         ' . $condition);
        //echo $condition.'<hr>';
        while ($row = $this->db->assoc($query)) {
            $temp_amount = 0.0;
            if ($currency_id == smc_session()['local_currency'])
                $temp_amount = $row['local_amount'];
            else
                $temp_amount = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
            //
            $indx = empty($options['is_arr']) ? 0 : $row['Account_ID'];
            if (!isset($acc_arr[$indx])) {
                $acc_arr[$indx] = array(
                    "Balance" => 0,
                    "Debits" => 0,
                    "Credits" => 0,
                    "local_debits" => 0,
                    "local_credits" => 0,
                    "second_debits" => 0,
                    "second_credits" => 0,
                    "local_balance" => 0,
                    "second_balance" => 0
                );
            }
            //
            if ($row['Transaction_Type'] == 'Debit') {
                $acc_arr[$indx]["Debits"] += $temp_amount;
                $acc_arr[$indx]["local_debits"] += $row['local_amount'];
                $acc_arr[$indx]["second_debits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] += $temp_amount;
                $acc_arr[$indx]["local_balance"] += $row['local_amount'];
                $acc_arr[$indx]["second_balance"] += $row['second_amount'];
            } elseif ($row['Transaction_Type'] == 'Credit') {
                $acc_arr[$indx]["Credits"] += $temp_amount;
                $acc_arr[$indx]["local_credits"] += $row['local_amount'];
                $acc_arr[$indx]["second_credits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] -= $temp_amount;
                $acc_arr[$indx]["local_balance"] -= $row['local_amount'];
                $acc_arr[$indx]["second_balance"] -= $row['second_amount'];
            }
        }
        //
        if (!empty($options['is_arr']))
            return $acc_arr;
        //
        if (!isset($acc_arr[0]))
            $acc_arr[0] = array(
                "Balance" => 0,
                "Debits" => 0,
                "Credits" => 0,
                "local_debits" => 0,
                "local_credits" => 0,
                "second_debits" => 0,
                "second_credits" => 0,
                "local_balance" => 0,
                "second_balance" => 0
            );
        return $acc_arr[0];
    }

    //    public function returnExactBalance($code, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false, $left = false) {
    //        $condition = ' ';
    //        if ($left) {
    //            $condition .= ' AND LEFT(a.Account_Code,1) = "' . $code . '"';
    //        } else {
    //            $condition .= ' AND a.Account_Code IN ("' . $code . '")';
    //        }
    //        $acc_id_arr = array();
    //        $query = $this->db->query('SELECT  a.Account_ID
    //                                        FROM  tbl_chart_of_accounts a 
    //                                        WHERE true ' . $condition);
    //        while ($row = $this->db->assoc($query)) {
    //            $acc_id_arr[$row['Account_ID']] = $row['Account_ID'];
    //        }
    //        $account_id = implode(',', $acc_id_arr);
    //        return $this->returnExactBalanceByID($account_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up, $actual_only, $opening_only);
    //    }
    //    public function returnExactBalance($code, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false, $left = false) {
    public function returnExactBalance($options, $exact_acc_arr = null) {
        //        echo "<pre>";die(print_r($exact_acc_arr));
        if (empty($options['cond']))
            $options['cond'] = '';
        $condition = ' ';
        if (!empty($options['acc_cond'])) {
            $condition .= $options['acc_cond'];
        }


        if (!empty($options['left'])) {
            $condition .= ' AND LEFT(Account_Code,' . strlen($options['code']) . ') = "' . $options['code'] . '"';
        } else {
            if (empty($options['code']) && !empty($options['multi_accounts']))
                $condition .= ' and Account_ID in (' . $options['multi_accounts'] . ')';
            else
                $condition .= ' AND Account_Code IN ("' . $options['code'] . '")';
        }


        $acc_id_arr = array();
        $account_ids = '';
        $query = $this->db->query('SELECT  Account_ID,Account_Code FROM  tbl_chart_of_accounts WHERE true ' . $condition);
        while ($row = $this->db->assoc($query)) {
            if (is_null($exact_acc_arr) || isset($exact_acc_arr[$row['Account_ID']])) {
                $acc_id_arr[$row['Account_ID']] = $row['Account_Code'];
                $account_ids .= (empty($account_ids) ? '' : ',') . $row['Account_ID'];
            }
        }
        $options['Account_ID'] = $account_ids;
        if (empty($account_ids))
            $options['cond'] .= " and 1=2 ";
        $acc_arr = $this->returnExactBalanceByID($options);
        if (empty($options['is_arr']) || !empty($options['index_acc_id']))
            return $acc_arr;
        $result_arr = array();
        foreach ($acc_arr as $acc_id => $row) {
            $result_arr[$acc_id_arr[$acc_id]] = $row;
            unset($acc_arr[$acc_id]);
        }
        unset($acc_arr);
        return $result_arr;
    }

    public function returnCustomerExactBalance($customer_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false) {
        $acc_id_arr = array();
        $query = $this->db->query('SELECT  a.Account_ID FROM  tbl_chart_of_accounts a 
                                WHERE main_id = "' . $customer_id . '" and main_type="cust" and sub_type="main" ');
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['Account_ID']] = $row['Account_ID'];
        }
        $account_id = implode(',', $acc_id_arr);
        $options = ["Account_ID" => $account_id, "Currency_ID" => $currency_id,
            "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only, "opening_only" => $opening_only];
        $options[strlen($from_date) > 10 ? "from_create_time" : "From_Date"] = $from_date;
        $options[strlen($from_date) > 10 ? "to_create_time" : "To_Date"] = $to_date;
        //
        return $this->returnExactBalanceByID($options);
    }

    public function returnSupplierExactBalance($supplier_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false) {
        $acc_id_arr = array();
        $query = $this->db->query('SELECT  a.Account_ID
                                            FROM  tbl_chart_of_accounts a 
                                            WHERE main_id = "' . $supplier_id . '" and main_type="supp" and sub_type="main" ');
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['Account_ID']] = $row['Account_ID'];
        }
        $account_id = implode(',', $acc_id_arr);
        $options = ["Account_ID" => $account_id, "Currency_ID" => $currency_id, "From_Date" => $from_date, "To_Date" => $to_date,
            "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only, "opening_only" => $opening_only];
        return $this->returnExactBalanceByID($options);
        //        return $this->returnExactBalanceByID($account_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up, $actual_only, $opening_only);
    }

    public function returnEmployeeExactBalance($emp_id, $currency_id, $from_date, $to_date, $opening_balance, $back_up = false, $actual_only = false, $opening_only = false) {
        $acc_id_arr = array();
        $query = $this->db->query('SELECT  a.Account_ID FROM  tbl_chart_of_accounts a 
                                WHERE main_id = "' . $emp_id . '" and main_type="emp" and sub_type="inc" ');
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['Account_ID']] = $row['Account_ID'];
        }
        $account_id = implode(',', $acc_id_arr);
        //        echo $account_id.'==';die();
        $options = ["Account_ID" => $account_id, "Currency_ID" => $currency_id,
            "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only, "opening_only" => $opening_only];
        $options[strlen($from_date) > 10 ? "from_create_time" : "From_Date"] = $from_date;
        $options[strlen($from_date) > 10 ? "to_create_time" : "To_Date"] = $to_date;
        //
        return $this->returnExactBalanceByID($options);
    }

    //    private function returnExactBalance($code,$currency_id,$from_date,$to_date,$opening_balance,$back_up,$actual_only,$opening_only = false,$left=false) {
    //        if ($currency_id == 0)
    //            $currency_id = CurrencyFactory::getDefaultCurrency();
    //        $local_currency = CurrencyFactory::returnLocalCurrency();
    //        $condition ='';
    //        $balance = 0.0;
    //        $debits  = 0.0;
    //        $credits = 0.0;
    //        if ($opening_only)
    //            $condition .= ' AND JV_ID = 1';
    //        else {
    //            if ($opening_balance == 0)
    //                $condition .= ' AND JV_ID <> 1';
    //            $condition .= ' AND 
    //                                Transaction_Date >= "'.$from_date.'" 
    //                            AND 
    //                                Transaction_Date <= "'.$to_date.'"
    //                        ';
    //        }
    //        if ($left) {
    //            $condition .= ' AND LEFT(Transaction_Account,1) = "'.$code.'"';
    //        }
    //        else {
    //            $condition .= ' AND Transaction_Account = "'.$code.'"';
    //        }
    //        if (!$actual_only) {
    //            $query = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_accounting_transactions 
    //                                        WHERE 
    //                                            1 = 1                              
    //                    '.$condition);
    //            while ($row = $this->db->assoc($query)) {
    //                $temp_amount = 0.0;
    //                $temp_amount_1 = 0.0;
    //                if ($row['Currency_ID'] != $currency_id) {
    //                    if ($row['Currency_ID'] != $local_currency)
    //                        $temp_amount_1 = CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                    else
    //                        $temp_amount_1 = $row['Transaction_Amount'];
    //                    $temp_amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($local_currency,$currency_id,$temp_amount_1);
    //                }
    //                else 
    //                    $temp_amount = $row['Transaction_Amount'];
    //                if ($row['Transaction_Type'] == 'Debit') {
    //                    $debits  += $temp_amount;
    //                    $balance += $temp_amount;
    //                } 
    //                elseif ($row['Transaction_Type'] == 'Credit') {
    //                    $credits += $temp_amount;
    //                    $balance -= $temp_amount;
    //                }
    //            }
    //        }
    //        if ($back_up) {
    //            $query = $this->db->query('SELECT 
    //                                            *
    //                                        FROM 
    //                                            tbl_mgt_logs 
    //                                        WHERE 
    //                                            Transaction_Account = "'.$code.'"
    //
    //                    '.$condition);
    //            while ($row = $this->db->assoc($query)) {
    //                $temp_amount = 0.0;
    //                $temp_amount_1 = 0.0;
    //                if ($row['Currency_ID'] != $currency_id) {
    //                    if ($row['Currency_ID'] != $local_currency)
    //                        $temp_amount_1 = CurrencyFactory::returnExchangedValueByExchangedID($row['Exchange_Rate_ID'], $row['Transaction_Amount'], $row['Currency_ID']);
    //                    else
    //                        $temp_amount_1 = $row['Transaction_Amount'];
    //                    $temp_amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($local_currency,$currency_id,$temp_amount_1);
    //                }
    //                else 
    //                    $temp_amount = $row['Transaction_Amount'];
    //                if ($row['Transaction_Type'] == 'Debit') {
    //                    $debits  += $temp_amount;
    //                    $balance += $temp_amount;
    //                } 
    //                elseif ($row['Transaction_Type'] == 'Credit') {
    //                    $credits += $temp_amount;
    //                    $balance -= $temp_amount;
    //                }
    //            }
    //        }
    //        $result = array(
    //                        "Balance" => $balance,
    //                        "Debits"  => $debits,
    //                        "Credits" => $credits
    //                );
    //        return $result;
    //    } 



    public function viewGroupSix() {
        $data = array();
        $query = $this->db->query('SELECT 
                                            CONCAT(Account_Code," - ",Account_Name) AS Account_Name,
                                            Account_Code
                                        FROM 
                                            tbl_chart_of_accounts
                                        WHERE
                                            LEFT(Account_Code,1) = 6
                                        AND 
                                            CHAR_LENGTH(Account_Code) = 2
                                        ORDER BY  
                                            LEFT(Account_Code,2)
                    ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    private function expenseAccounts($len, $to_date, $opening_balance, $back_up, $actual_only) {
        $data = array();
        $condition = '';
        $select = '';
        if ($opening_balance == 0)
            $condition .= ' AND t.main_type <> "opy"';
        if ($len == 2) {
            $select .= ' DISTINCT LEFT(a.Account_Code,2) AS ';
        } else {
            $select .= ' DISTINCT a.Account_Code AS ';
            $condition .= ' AND LEFT(a.Account_Code,2) = "' . $len . '"';
        }
        if (!$back_up) {
            $condition .= ' and t.is_actual = 0';
        } else if ($actual_only) {
            $condition .= ' and t.is_actual = 1';
        }
        //        if (!$actual_only) {
        $query = $this->db->query('SELECT 
                                                ' . $select . ' Account_Code
                                            FROM 
                                                tbl_accounting_transactions t join tbl_chart_of_accounts a
                                                on a.Account_ID = t.Account_ID
                                            WHERE
                                                Transaction_Date <= "' . $to_date . '"
                                            AND 
                                                LEFT(a.Account_Code,1) = 6
                        ' . $condition . ' Order by  LEFT(a.Account_Code,2)');
        while ($row = $this->db->assoc($query))
            $data[] = $row['Account_Code'];
        //        }
        //        if ($back_up) {
        //            $query2 = $this->db->query('SELECT 
        //                                            ' . $select . ' Account_Code
        //                                        FROM 
        //                                            tbl_mgt_logs t join tbl_chart_of_accounts a
        //                                            on a.Account_ID = t.Account_ID
        //                                        WHERE
        //                                            Transaction_Date <= "' . $to_date . '"
        //                                        AND 
        //                                            LEFT(a.Account_Code,1) = 6
        //                    ' . $condition . 'Order by  LEFT(a.Account_Code,' . $len . ')');
        //            while ($row2 = $this->db->assoc($query2))
        //                if (!in_array($row2['Account_Code'], $data))
        //                    $data[] = $row2['Account_Code'];
        //        }
        return $data;
    }

    public function expenseReport($from_date, $to_date, $accounts = array(), $opening_balance = 1, $currency_id = 0, $back_up = 0, $actual_only = false) {
        if ($back_up == 1)
            $back_up = true;
        else
            $back_up = false;
        $old_balance = 0.0;
        $current_balance = 0.0;
        $all_balance = 0.0;
        $condition = '';
        $expenses = array();

        $from_year = substr($from_date, 0, 4);
        $start_date = $from_year . "-01-01";
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
        if (count($accounts) > 0)
            $two_digits = $accounts;
        else
            $two_digits = self::expenseAccounts(2, $to_date, $opening_balance, $back_up, $actual_only);
        //        die (print_r($two_digits));
        for ($i = 0; $i < count($two_digits); $i++) {
            $per_2_old = 0.0;
            $per_2_current = 0.0;
            $per_2_all = 0.0;
            $digits = self::expenseAccounts($two_digits[$i], $to_date, $opening_balance, $back_up, $actual_only);
            for ($y = 0; $y < count($digits); $y++) {
                if ($start_date == $from_date) {
                    if ($opening_balance == 1)
                        $account_balance_old = self::returnExactBalance(["code" => $digits[$y], "Currency_ID" => $currency_id, "From_Date" => $start_date, "To_Date" => $day_before, "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only, "opening_only" => true])['Balance'];
                    else
                        $account_balance_old = 0.0;
                }
                else {

                    $account_balance_old = self::returnExactBalance(["code" => $digits[$y], "Currency_ID" => $currency_id, "From_Date" => $start_date, "To_Date" => $day_before, "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only])['Balance'];
                }
                $account_balance_current = self::returnExactBalance(["code" => $digits[$y], "Currency_ID" => $currency_id, "From_Date" => $from_date, "To_Date" => $to_date, "Opening_Balance" => $opening_balance, "Is_Actual" => $back_up, "Actual_Only" => $actual_only])['Balance'];
                $account_balance_all = $account_balance_old + $account_balance_current;
                $expenses[$i][] = array('Code' => $digits[$y],
                    'Name' => self::returnAccountName($digits[$y]),
                    'Old_Balance' => $account_balance_old,
                    'Current_Balance' => $account_balance_current,
                    'All_Balance' => $account_balance_all
                );
                $per_2_old += $account_balance_old;
                $per_2_current += $account_balance_current;
                $per_2_all += $account_balance_all;
            }
            $expenses[$i]['Two_Digits'] = array('Code' => $two_digits[$i],
                'Name' => self::returnAccountName($two_digits[$i]),
                'Old_Balance' => $per_2_old,
                'Current_Balance' => $per_2_current,
                'All_Balance' => $per_2_all
            );
            $old_balance += $per_2_old;
            $current_balance += $per_2_current;
            $all_balance += $per_2_all;
        }
        $expenses['Totals'] = array(
            'Old_Balance' => $old_balance,
            'Current_Balance' => $current_balance,
            'All_Balance' => $all_balance
        );
        return $expenses;
    }

    //    public function newGeneralLedger($code, $from_date, $to_date, $currency_id = 0, $type = "All", $back_up = false, $actual_only = false, $users = null, $trans_type = null, $job_ids = null) {
    ////        $case = 1;
    //        $year_id = $this->year_id;
    //        $year_id_actual = $this->year_id_actual;
    ////        $from_year = substr($from_date, 0, 4);
    //        $start_date = $back_up ? smc_session()['start_date'] : smc_session()['start_date_act'];
    //        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
    //        $data = array();
    //        $prev_balance = 0.0;
    //        $debits = 0.0;
    //        $credits = 0.0;
    //        $current_balance = 0.0;
    //        $all_balance = 0.0;
    //        if ($currency_id == 0)
    //            $currency_id = CurrencyFactory::getDefaultCurrency();
    //        $local_currency = smc_session()['local_currency'];
    //
    //        $condition = '';
    //        if (!is_null($job_ids))
    //            $condition.=' and job_id in (' . $job_ids . ')';
    //        if ($type == "Credit" or $type == "Debit")
    //            $condition .= ' AND Transaction_Type = "' . $type . '"';
    //        if (!empty($trans_type)) {
    //            $condition .= ' and t.main_type in ("' . implode('","', $trans_type) . '")';
    //        }
    //        if (!empty($users)) {
    //            $condition .= ' and Logged_ID in (' . implode(',', $users) . ')';
    //        }
    //        if ($code != 0) {//condition in case user select date or anything before selecting code
    //            $code = str_replace(',', '","', $code);
    //            $condition .= ' AND a.Account_Code IN ("' . $code . '")';
    //
    //
    //            if ($start_date < $from_date and ! is_null($start_date)) {
    //                $prev_balance = self::returnExactBalance($code, $currency_id, $start_date, $day_before, 1, $back_up, $actual_only)['Balance'];
    //                $all_balance = $prev_balance;
    //                $data[] = array(
    //                    "main_id" => "0",
    //                    "main_type" => "0",
    //                    "Transaction_Account" => "--",
    //                    "Transaction_Date" => "--",
    //                    "JV_ID" => "--",
    //                    "Ref_ID" => "--",
    //                    "Transaction_Description" => "Opening Balance",
    //                    "Debit" => "--",
    //                    "Credit" => "--",
    //                    "Current_Balance" => $prev_balance,
    //                    "All_Balance" => $all_balance
    //                );
    //            }
    //        }
    //        if (!$back_up) {
    //            $condition .=' and t.is_actual = 0';
    //        } else if ($actual_only) {
    //            $condition .=' and t.is_actual = 1';
    //        }
    ////        if (!$actual_only) {
    //        $query_current = $this->db->query('
    //                                                SELECT 
    //                                                    t.Transaction_Reference,
    //                                                    t.Currency_ID,
    //                                                    t.Transaction_Amount,
    //                                                    t.Current_Ex_Rate,
    //                                                    t.Exchange_Rate_ID,
    //                                                    t.Transaction_Type,
    //                                                    t.main_id,
    //                                                    t.main_type,
    //                                                    t.Transaction_Description,
    //                                                    concat(if(t.is_actual=1,"Act.",""),t.JV_ID) as JV_ID,
    //                                                    t.Transaction_Date,
    //                                                    a.Account_Code,
    //                                                    a.Account_Name,
    //                                                    u.serial_prefix,
    //                                                    concat(Transaction_Date,JV_ID) as date_jv
    //                                                FROM 
    //                                                    tbl_accounting_transactions t
    //                                                    join tbl_chart_of_accounts a
    //                                                    on a.Account_ID = t.Account_ID
    //                                                left join tbl_users_accounting_accounts u
    //                                                on
    //                                                    u.User_ID = t.Logged_ID
    //                                                WHERE  
    //                                                    current_year_id = "' . $year_id . '"
    //                                                AND
    //                                                    Transaction_Date >= "' . $from_date . '" 
    //                                                AND 
    //                                                    Transaction_Date <= "' . $to_date . '"
    //                                                ' . $condition . '
    //                                                ORDER BY 
    //                                                    Transaction_Date,JV_ID
    //                        ');
    //        while ($row_current = $this->db->assoc($query_current)) {
    //            $temp_amount = 0.0;
    //            $do = true;
    //            if ($row_current['Transaction_Reference'] <> "EXR-000") {
    //                $temp_amount = self::getExchangedAmount($currency_id, $row_current['Currency_ID'], $row_current['Transaction_Amount'], $row_current['Current_Ex_Rate'], $row_current['Exchange_Rate_ID']);
    //            } else {
    //                $temp_amount = 0;
    //                $do = false;
    //            }
    //            if ($row_current['Transaction_Type'] == 'Debit' and $do == true) {
    //                $current_balance += $temp_amount;
    //                $debits += $temp_amount;
    //                $all_balance += $temp_amount;
    //                $debit_amount = $temp_amount;
    //                $credit_amount = 0.00;
    //            } elseif ($row_current['Transaction_Type'] == 'Credit' and $do == true) {
    //                $current_balance -= $temp_amount;
    //                $credits += $temp_amount;
    //                $all_balance -= $temp_amount;
    //                $credit_amount = $temp_amount;
    //                $debit_amount = 0.00;
    //            }
    //            $data[] = array(
    //                "serial_prefix" => $row_current['serial_prefix'],
    //                "main_id" => $row_current['main_id'],
    //                "main_type" => $row_current['main_type'],
    //                "Transaction_Account" => $row_current['Account_Code'],
    //                "Account_Name" => $row_current['Account_Name'],
    //                "Transaction_Date" => $row_current['Transaction_Date'],
    //                "JV_ID" => $row_current['JV_ID'],
    //                "Ref_ID" => $row_current['Transaction_Reference'],
    //                "Transaction_Description" => $row_current['Transaction_Description'],
    //                "Debit" => $debit_amount,
    //                "Credit" => $credit_amount,
    //                "Current_Balance" => $current_balance,
    //                "All_Balance" => $all_balance
    //            );
    //        }
    ////        }
    ////        if ($back_up) {
    ////            $query_current = $this->db->query('
    ////                                                SELECT 
    ////                                                    t.Transaction_Reference,
    ////                                                    t.Currency_ID,
    ////                                                    t.Transaction_Amount,
    ////                                                    t.Current_Ex_Rate,
    ////                                                    t.Exchange_Rate_ID,
    ////                                                    t.Transaction_Type,
    ////                                                    t.main_id,
    ////                                                    t.main_type,
    ////                                                    t.Transaction_Description,
    ////                                                    t.JV_ID,
    ////                                                    t.Transaction_Date,
    ////                                                    a.Account_Code,
    ////                                                    u.serial_prefix,
    ////                                                    concat(Transaction_Date,JV_ID) as date_jv
    ////                                                FROM 
    ////                                                    tbl_mgt_logs t join tbl_chart_of_accounts a
    ////                                                    on a.Account_ID = t.Account_ID
    ////                                                left join tbl_users_accounting_accounts u
    ////                                                on
    ////                                                    u.User_ID = t.Logged_ID
    ////                                                WHERE  
    ////                                                    current_year_id = "' . $year_id_actual . '"
    ////                                                AND
    ////                                                    Transaction_Date >= "' . $from_date . '" 
    ////                                                AND 
    ////                                                    Transaction_Date <= "' . $to_date . '"
    ////                                                ' . $condition . '
    ////                                                ORDER BY 
    ////                                                    Transaction_Date,JV_ID
    ////                        ');
    ////            while ($row_current = $this->db->assoc($query_current)) {
    ////                $temp_amount = 0.0;
    ////                $do = true;
    ////                if ($row_current['Transaction_Reference'] <> "EXR-000") {
    ////
    ////                    $temp_amount = self::getExchangedAmount($currency_id, $row_current['Currency_ID'], $row_current['Transaction_Amount'], $row_current['Current_Ex_Rate'], $row_current['Exchange_Rate_ID']);
    ////                } elseif ($row_current['Transaction_Reference'] == "EXR-000") {
    ////                    $temp_amount = 0;
    ////                    $do = false;
    ////                }
    ////                if ($row_current['Transaction_Type'] == 'Debit' and $do == true) {
    ////                    $current_balance += $temp_amount;
    ////                    $debits += $temp_amount;
    ////                    $all_balance += $temp_amount;
    ////                    $debit_amount = $temp_amount;
    ////                    $credit_amount = 0.00;
    ////                } elseif ($row_current['Transaction_Type'] == 'Credit' and $do == true) {
    ////                    $current_balance -= $temp_amount;
    ////                    $credits += $temp_amount;
    ////                    $all_balance -= $temp_amount;
    ////                    $debit_amount = 0.00;
    ////                    $credit_amount = $temp_amount;
    ////                }
    ////                $data[] = array(
    ////                    "serial_prefix" => "",
    ////                    "main_id" => "",
    ////                    "main_type" => "",
    ////                    "Transaction_Account" => $row_current['Account_Code'],
    ////                    "Transaction_Date" => $row_current['Transaction_Date'],
    ////                    "JV_ID" => ("Actual-" . $row_current['JV_ID']),
    ////                    "Ref_ID" => $row_current['Transaction_Reference'],
    ////                    "Transaction_Description" => $row_current['Transaction_Description'],
    ////                    "Debit" => $debit_amount,
    ////                    "Credit" => $credit_amount,
    ////                    "Current_Balance" => $current_balance,
    ////                    "All_Balance" => $all_balance
    ////                );
    ////            }
    ////        }
    //
    //
    //        $default = $this->db->query('SELECT
    //                                        Currency_Symbol
    //                                    FROM
    //                                        tbl_common_currency 
    //                                    WHERE 
    //                                        Currency_ID = "' . $currency_id . '" ');
    //        $default_row = $this->db->assoc($default);
    //        $row_current['Currency_Symbol'] = $default_row['Currency_Symbol'];
    //
    //        $data['Currency_Symbol'] = $row_current;
    //        $data['Total'] = array(
    //            "Prev_Balance" => $prev_balance,
    //            "Debit" => $debits,
    //            "Credit" => $credits,
    //            "Current_Balance" => $current_balance,
    //            "All_Balance" => $all_balance
    //        );
    ////        echo"<pre>";
    ////        die(print_r($data));
    //        return $data;
    //    }

    public function viewAllAccounts() {
        $data = array();
        $query = $this->db->query('SELECT 
                                            c.Account_Name,  
                                            c.Account_Code  
                                        FROM 
                                            tbl_accounting_transactions t
                                        JOIN
                                            tbl_chart_of_accounts c
                                        ON 
                                            t.Account_ID = c.Account_ID
                                            where c.Status_ID = 1
                                        GROUP BY
                                            t.Account_ID
                    ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;

        return $data;
    }

    private function getExchangedAmount($to_currency, $from_currency, $amount, $from_to_local_rate, $second_rate, $exchange_rate_id) {
        if ($to_currency == $from_currency)
            return $amount;
        //
        $rate = 0;
        if ($to_currency == smc_session()['local_currency'])
            $rate = $from_to_local_rate;
        elseif ($to_currency == smc_session()['second_currency']['id'])
            $rate = $second_rate;
        if ($rate == 0) {
            $rate_arr = CurrencyFactory::returnExchangeRate($from_currency, $to_currency);
            $rate = ($rate_arr[1] == '*' ? $rate_arr[0] : (1 / $rate_arr[0]));
        }
        return ($amount * $rate);
        //        if ($from_to_local_rate == 0)
        //            $local_amount = CurrencyFactory::returnExchangedValueByExchangedID($exchange_rate_id, $amount, $from_currency);
        //        else
        //            $local_amount = $amount * $from_to_local_rate;
        //        //
        //        if ($to_currency == smc_session()['local_currency']) {
        //            return $local_amount;
        //        } elseif ($to_currency == smc_session()['second_currency']['id'] && $second_rate != 0) {
        //            $amount*= $second_rate;
        //            return $amount;
        //        } else {
        //            $amount = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $to_currency, $local_amount);
        //            return $amount;
        //        }
    }

    private function getbalancebyRate($currency_id, $transaction_currency, $date, $trans_amount) {
        // first seach for the last exchange before the transaction
        $ex_query = $this->db->query('SELECT 
                                            ExchRate,
                                            from_currency,
                                            to_currency
                                        FROM 
                                            tbl_currencies_rate 
                                        WHERE 
                                            (   
                                                (
                                                        from_currency = "' . $transaction_currency . '"
                                                    AND 
                                                        to_currency = "' . $currency_id . '"
                                                )
                                                OR 
                                                (
                                                        to_currency = "' . $transaction_currency . '"
                                                    AND 
                                                        from_currency = "' . $currency_id . '"
                                                )
                                            )
                                        AND 
                                            Exchange_Rate_Date <= "' . $date . '"
                                        ORDER BY 
                                            Exchange_Rate_ID
                                        DESC LIMIT 1
                    ');
        $row_query = $this->db->assoc($ex_query);
        // if no result try first exchange after the transaction
        if (count($row_query) == 0) {
            $ex_query = $this->db->query('SELECT 
                                                ExchRate,
                                                from_currency,
                                                to_currency 
                                            FROM 
                                                tbl_currencies_rate 
                                            WHERE 
                                                (   
                                                    (
                                                            from_currency = "' . $transaction_currency . '"
                                                        AND 
                                                            to_currency = "' . $currency_id . '"
                                                    )
                                                    OR 
                                                    (
                                                            to_currency = "' . $transaction_currency . '"
                                                        AND 
                                                            from_currency = "' . $currency_id . '"
                                                    )
                                                )
                                            AND 
                                                Exchange_Rate_Date > "' . $date . '"
                                            ORDER BY 
                                                Exchange_Rate_ID
                                            LIMIT 1
                        ');
            $row_query = $this->db->assoc($ex_query);
        }

        if ($row_query['ExchRate'] > 1 or $row_query['ExchRate'] < 1) {
            if ($row_query['from_currency'] == $transaction_currency)
                $temp_amount = $trans_amount * $row_query['ExchRate'];
            else
                $temp_amount = $trans_amount / $row_query['ExchRate'];
        }
        else {
            $temp_amount = $row['Transaction_Amount'];
        }
        return $temp_amount;
    }

    public function viewSuppCustAccounts($is_supp, $date_from, $date_to, $is_leb, $type, $codes) {
        //leb : 120
        if ($is_supp) {
            if (empty($codes))
                $codes_arr = "''";
            else {
                //            $codes = implode($codes, ",");
                $codes_arr = '';
                foreach ($codes as $code) {
                    $explode_code = explode('#', $code);
                    if (!empty($codes_arr))
                        $codes_arr .= ',';
                    $codes_arr .= "'" . $explode_code[1] . "'";
                }
            }
        }else {
            $codes_arr = "'main'";
        }
        $accounts = array();
        if ($is_leb == 1)
            $cond = " and " . ($is_supp ? 's.Supplier_Country' : 's.Customer_Country_ID') . " = '" . smc_session()['org_detail']['Organization_Country'] . "'";
        else
            $cond = " and " . ($is_supp ? 's.Supplier_Country' : 's.Customer_Country_ID') . " <> '" . smc_session()['org_detail']['Organization_Country'] . "'";

        $query = $this->db->query("SELECT 
                                            DISTINCT ca.Account_Code AS Account,
                                            " . ($is_supp ? 's.Supplier_Name' : 's.Customer_Name') . " AS Name,
                                            " . ($is_supp ? 's.Supplier_CR' : 's.Customer_CR') . " AS CR,
                                            " . ($is_supp ? 's.Supplier_Country' : 's.Customer_Country_ID') . " AS is_leb
                                        FROM 
                                            tbl_accounting_transactions t
                                        INNER JOIN 
                                            tbl_chart_of_accounts ca 
                                        inner JOIN 
                                            " . ($is_supp ? 'tbl_stock_suppliers' : 'tbl_customers') . " s
                                        ON 
                                            " . ($is_supp ? 's.Supplier_ID' : 's.Customer_ID') . " = ca.main_id
                                        WHERE 
                                            ca.main_type='" . ($is_supp ? 'supp' : 'cust') . "'
                                        AND 
                                            t.Transaction_Type= '" . $type . "'
                                        AND 
                                            t.Transaction_Date >= '" . $date_from . "'
                                        AND
                                            t.Transaction_Date <= '" . $date_to . "'
                                        AND 
                                            t.main_type <> 'opy'
                                        AND 
                                            ca.sub_type in  (" . $codes_arr . ")
                                        " . $cond);


        while ($row = $this->db->assoc($query))
            $accounts[] = $row;
        return $accounts;
    }

    private function getBalanceByType($account, $date_from, $date_to, $type, $currency_id, $is_actual = 0) {
        $case = 1;
        $local_currency = CurrencyFactory::returnLocalCurrency();
        $balance = 0.0;
        $query = $this->db->query('SELECT 
                                                t.*,
                                                a.Account_Code
                                            FROM 
                                                tbl_accounting_transactions t join tbl_chart_of_accounts a 
                                                on a.Account_ID = t.Account_ID
                                            WHERE 
                                                a.Account_Code = "' . $account . '"
                                            AND 
                                                Transaction_Date >= "' . $date_from . '"
                                            AND
                                                Transaction_Date <= "' . $date_to . '"
                                            and 
                                                Transaction_Type = "' . $type . '"
                                            and
                                                t.main_type <> "opy"
                                            and t.is_actual = "' . $is_actual . '"
                                            and 
                                                current_year_id = "' . $this->year_id . '"

                        ');
        while ($row = $this->db->assoc($query)) {
            if ($row['Currency_ID'] != $currency_id) {
                if ($case == 1 or $case == 2) {
                    if ($row['Current_Ex_Rate'] == 0) {
                        if ($row['Currency_ID'] == $local_currency) {
                            //if local currency then we have to check if there is exchange rate on the current transaction
                            $curr_rate = $this->db->query('SELECT  
                                                                        distinct t.Current_Ex_Rate as curr_ex_rate
                                                                    from 
                                                                        tbl_accounting_transactions t
                                                                    where 
                                                                        t.JV_ID = "' . $row['JV_ID'] . '"
                                                                    and 
                                                                        t.Current_Ex_Rate > 0
                                                                    and 
                                                                        current_year_id = "' . $row['current_year_id'] . '"
                                                                    limit 1
                                                                    ');
                            $jv_current_rate = $this->db->assoc($curr_rate);
                            if (count($jv_current_rate) > 0) {
                                $balance += $row['Transaction_Amount'] / $jv_current_rate['curr_ex_rate'];
                            } else {
                                // else we need to calculate the value based on historical exchange rate
                                $balance += self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                            }
                        } else {
                            // else we need to calculate the value based on historical exchange rate
                            $balance += self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                        }
                    }
                    //if there is current exchange rate on the transaction
                    elseif ($row['Current_Ex_Rate'] != 0 and $currency_id == $local_currency) {
                        //                        $balance += $row['Transaction_Amount'] * $row['Current_Ex_Rate'];
                        $balance += $row['local_amount'];
                    } elseif ($row['Current_Ex_Rate'] != 0 and $currency_id != $local_currency) {
                        $balance += self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                    }
                } else if ($case == 3) {
                    $balance += CurrencyFactory::returnExchangedValueBetweenTwoCurrencies($row['Currency_ID'], $currency_id, $row['Transaction_Amount']);
                }
            } else
                $balance += $row['Transaction_Amount'];
        }
        return $balance;
    }

    public function viewTopSuppCust($data) {
        //        $acc,$year,$limit=4,$currency=84;
        $result = array();
        $accounts = self::viewSuppCustAccounts($data['is_supplier'], $data['date_from'], $data['date_to'], $data['is_leb'], $data['type'], $data['accounts']);
        $index = array();
        for ($i = 0; $i < count($accounts); $i++) {
            $balance = self::getBalanceByType($accounts[$i]['Account'], $data['date_from'], $data['date_to'], $data['type'], $data['currency']);
            $balance =  CommonFunctions::public_round_number($balance);
            $result[] = ["name" => ($accounts[$i]['Name'] . " - " . $accounts[$i]['Account']), "CR" => $accounts[$i]['CR'], "balance" => $balance];
            $index[$i] = $balance;
        }
        array_multisort($index, SORT_DESC, $result);
        $final = array_slice($result, 0, $data['limit']);
        return $final;
    }

    public function getExactBalance($data, $code, $left, $exact = false) {
        //        echo $left;
        //account_code//currency//from_date//to_date//is_actual//left
        $local_currency = CurrencyFactory::returnLocalCurrency();
        $condition = '';
        $balance = 0.0;
        $debits = 0.0;
        $credits = 0.0;
        $condition .= 'and Transaction_Date >= "' . $data['from_date'] . '" and Transaction_Date <= "' . $data['to_date'] . '"';
        if ($exact) {
            $condition .= ' and a.Account_Code = "' . $code . '"';
        } else {
            $condition .= ' and LEFT(a.Account_Code,' . $left . ') = "' . $code . '"';
        }
        $currency_id = $data['currency'];
        $condition .= $data['is_actual'] ? '' : ' and t.is_actual = 0';
        //        $year_id = isset($data['is_actual']) ? $this->year_id_actual : $this->year_id;
        $query = $this->db->query('SELECT  t.*,a.Account_Code
            FROM tbl_accounting_transactions t 
                join tbl_chart_of_accounts a on a.Account_ID = t.Account_ID
            WHERE  current_year_id = "' . $this->year_id . '" ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $temp_amount = 0.0;
            if ($row['Currency_ID'] != $currency_id and $row['main_type'] <> "cle") {
                if ($row['Current_Ex_Rate'] == 0) {
                    if ($row['Currency_ID'] == $local_currency) {
                        //if local currency then we have to check if there is exchange rate on the current transaction
                        $curr_rate = $this->db->query('SELECT distinct t.Current_Ex_Rate as curr_ex_rate
                            from  tbl_accounting_transactions t
                                where  t.JV_ID = "' . $row['JV_ID'] . '" and  t.Current_Ex_Rate > 0
                                and  current_year_id = "' . $row['current_year_id'] . '" limit 1 ');
                        $jv_current_rate = $this->db->assoc($curr_rate);
                        if (count($jv_current_rate) > 0) {
                            $temp_amount = $row['Transaction_Amount'] / $jv_current_rate['curr_ex_rate'];
                        } else {
                            // else we need to calculate the value based on historical exchange rate
                            $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                        }
                    } else {
                        // else we need to calculate the value based on historical exchange rate
                        $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                    }
                }
                //if there is current exchange rate on the transaction
                elseif ($row['Current_Ex_Rate'] != 0 and $currency_id == $local_currency) {
                    $temp_amount = $row['local_amount'];
                } elseif ($row['Current_Ex_Rate'] != 0 and $currency_id != $local_currency) {
                    // else we need to calculate the value based on historical exchange rate
                    $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
                }
            } elseif ($row['Currency_ID'] != $currency_id and $row['main_type'] == "cle")
                $temp_amount = ($currency_id == smc_session()['local_currency'] ? $row['local_amount'] : 0.0);
            else
                $temp_amount = $row['Transaction_Amount'];
            if ($row['Transaction_Type'] == 'Debit') {
                $debits += $temp_amount;
                $balance += $temp_amount;
            } elseif ($row['Transaction_Type'] == 'Credit') {
                $credits += $temp_amount;
                $balance -= $temp_amount;
            }
        }
        //        echo $balance.'<br>';
        //        if ($data['is_actual']) {
        ////            $year_id_actual = self::getYearID(substr($from_date, 0, 4), "1");
        //            $query = $this->db->query('SELECT 
        //                                            *
        //                                        FROM 
        //                                            tbl_mgt_logs t join tbl_chart_of_accounts a on
        //                                            a.Account_ID = t.Account_ID
        //                                        WHERE 
        //                                            current_year_id = "' . $this->year_id_actual . '"
        //
        //                    ' . $condition);
        //            while ($row = $this->db->assoc($query)) {
        //                $temp_amount = 0.0;
        //                if ($row['Currency_ID'] != $currency_id and $row['Transaction_Reference'] <> "EXR-000") {
        //                    if ($row['Current_Ex_Rate'] == 0) {
        //                        if ($row['Currency_ID'] == $local_currency) {
        //                            //if local currency then we have to check if there is exchange rate on the current transaction
        //                            $curr_rate = $this->db->query('SELECT  
        //                                                                    distinct t.Current_Ex_Rate as curr_ex_rate
        //                                                                from 
        //                                                                    tbl_mgt_logs t
        //                                                                where 
        //                                                                    t.JV_ID = "' . $row['JV_ID'] . '"
        //                                                                and 
        //                                                                    t.Current_Ex_Rate > 0
        //                                                                and 
        //                                                                    current_year_id = "' . $row['current_year_id'] . '"
        //                                                                limit 1
        //                                                                ');
        //                            $jv_current_rate = $this->db->assoc($curr_rate);
        //                            if (count($jv_current_rate) > 0) {
        //                                $temp_amount = $row['Transaction_Amount'] / $jv_current_rate['curr_ex_rate'];
        //                            } else {
        //                                // else we need to calculate the value based on historical exchange rate
        //                                $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
        //                            }
        //                        } else {
        //                            // else we need to calculate the value based on historical exchange rate
        //                            $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
        //                        }
        //                    }
        //                    //if there is current exchange rate on the transaction
        //                    elseif ($row['Current_Ex_Rate'] != 0 and $currency_id == $local_currency) {
        //                        $temp_amount = $row['Transaction_Amount'] * $row['Current_Ex_Rate'];
        //                    } elseif ($row['Current_Ex_Rate'] != 0 and $currency_id != $local_currency) {
        //                        // else we need to calculate the value based on historical exchange rate
        //                        $temp_amount = self::getbalancebyRate($currency_id, $row['Currency_ID'], $row['Transaction_Date'], $row['Transaction_Amount']);
        //                    } else
        //                        $temp_amount = $row['Transaction_Amount'];
        //                }
        //                elseif ($row['Currency_ID'] != $currency_id and $row['Transaction_Reference'] == "EXR-000")
        //                    $temp_amount = 0;
        //                else
        //                    $temp_amount = $row['Transaction_Amount'];
        //
        //                if ($row['Transaction_Type'] == 'Debit') {
        //
        //                    $debits += $temp_amount;
        //                    $balance += $temp_amount;
        //                } elseif ($row['Transaction_Type'] == 'Credit') {
        //
        //                    $credits += $temp_amount;
        //                    $balance -= $temp_amount;
        //                }
        //            }
        //        }
        $result = array(
            "Balance" => $balance,
            "Debits" => $debits,
            "Credits" => $credits
        );
        //        echo $balance.'<br>';
        //        die($result['Balance']);
        return $result;
    }

    private function getExactAccounts($keys, $account, $left) {
        $data = array();
        $year_id = $keys['is_actual'] ? $this->year_id_actual : $this->year_id;
        $condition = 'AND 
                            Transaction_Date >= "' . $keys['from_date'] . '" 
                        AND 
                            Transaction_Date <= "' . $keys['to_date'] . '"
                        AND
                            LEFT (a.Account_Code,"' . $left . '") IN (' . $account . ')';
        $condition .= $keys['is_actual'] ? '' : ' and t.is_actual=0 ';
        $query = $this->db->query('SELECT 
                                                DISTINCT a.Account_Code
                                            FROM 
                                                tbl_accounting_transactions t join tbl_chart_of_accounts a
                                                on a.Account_ID = t.Account_ID
                                            WHERE 
                                                current_year_id = "' . $year_id . '"

                    ' . $condition);
        while ($row = $this->db->assoc($query))
            $data[] = $row['Account_Code'];
        //        if ($keys['is_actual']) {
        //            $query2 = $this->db->query('SELECT 
        //                                            DISTINCT a.Account_Code
        //                                        FROM 
        //                                            tbl_mgt_logs t join tbl_chart_of_accounts a
        //                                            on a.Account_ID = t.Account_ID
        //                                        WHERE 
        //                                            current_year_id = "' . $this->year_id_actual . '"
        //                                           
        //                    ' . $condition);
        //            while ($row2 = $this->db->assoc($query2))
        //                $data[] = $row2['Account_Code'];
        //        }
        $unique_data = array_values(array_unique($data));
        sort($unique_data, SORT_STRING);
        return $unique_data;
    }

    //    public function statementOfIncome($keys) {
    //        //from_date//to_date//currency//is_actual
    //        $data = array();
    //        //Balance for sales accounts should be credit (-ve), display it as (+ve)
    //        $keys['cond'] = ' and left(Account_Code,1) = "7" ';
    //        $data['sales'] = ['title' => 'Sales', 'value' => (self::returnExactBalanceByID($keys)['Balance']) * (-1)];
    //        //Balance for purchases except 605, should be in debit (+ve), display it as (-ve)
    //        $data['cost_goods']['title'] = 'Cost of goods';
    //        $keys['cond'] = ' and left(Account_Code,2) = "60" ';
    //        $balance_60 = self::returnExactBalanceByID($keys)['Balance'];
    //        $keys['cond'] = ' and left(Account_Code,3) = "605" ';
    //        $balance_605 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['cost_goods']['value']['purchases'] = ['title' => 'Purchases', 'value' => (($balance_60 - $balance_605) * (-1))];
    //        //Balance of costs on purchases, should be in debit (+ve), display as (-ve)
    //        $keys['cond'] = ' and left(Account_Code,2) = "61" ';
    //        $balance_61 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['cost_goods']['value']['cost_purchases'] = ['title' => 'Cost of purchases', 'value' => (($balance_61) * (-1))];
    //        //Balance of variation of stock ending(6052) - begining(6051)
    //        $stock_value = 0;
    //        if (empty($keys['stock_type'])) {
    //            $keys['cond'] = ' and left(Account_Code,4) = "6052" ';
    //            $balance_6052 = self::returnExactBalanceByID($keys)['Balance'];
    //            $keys['cond'] = ' and left(Account_Code,4) = "6051" ';
    //            $balance_6051 = self::returnExactBalanceByID($keys)['Balance'];
    //            $stock_value = (($balance_6052 + $balance_6051) ) * -1;
    //        } else if ($keys['stock_type'] === 'manual') {
    //            $stock_value = $keys['stock_value'];
    //        } else {
    //            $product = new Product();
    //            $stock_value = ($product->costing_report(['date' => $keys['to_date'], 'type' => 'method', 'type_id' => $keys['stock_type']])['total']);
    //            $stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $stock_value);
    //        }
    //        $data['cost_goods']['value']['variation_stock'] = ['title' => 'Variation of stock', 'value' => $stock_value];
    //        //total balance for costs of goods
    //        $data['cost_goods']['value']['total'] = ['title' => 'Total cost of sold goods', 'value' => ($data['cost_goods']['value']['purchases']['value'] + $data['cost_goods']['value']['cost_purchases']['value'] + $data['cost_goods']['value']['variation_stock']['value'])];
    //        //balance for Accounts 1 & 2
    //        $data['gross_margin'] = ['title' => 'Gross Margin', 'value' => ($data['sales']['value'] + $data['cost_goods']['value']['total']['value'])];
    //        // balance of general and administrative expenses 62 and 68 and should be in debit (+ve), display as (-ve)
    //        $data['other_expenses']['title'] = 'Other Expenses';
    //        $total_exp = 0.0;
    //        $keys['cond'] = ' and left(Account_Code,2) = "62" ';
    //        $balance_62 = self::returnExactBalanceByID($keys)['Balance'];
    //        $keys['cond'] = ' and left(Account_Code,2) = "68" ';
    //        $balance_68 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['other_expenses']['value']['general_admin'] = ['title' => 'General & administrative Expenditures', 'value' => (($balance_62 + $balance_68) * (-1))];
    //        $total_exp += $data['other_expenses']['value']['general_admin']['value'];
    //        //balance of labor and wages Accounts 63
    //        $keys['cond'] = ' and left(Account_Code,2) = "63" ';
    //        $balance_63 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['other_expenses']['value']['labor_wages'] = ['title' => 'Labor & Wages', 'value' => (($balance_63) * (-1))];
    //        $total_exp += $data['other_expenses']['value']['labor_wages']['value'];
    //        //balance of depreciation Accounts 65
    //         $keys['cond'] = ' and left(Account_Code,2) = "65" ';
    //        $balance_65 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['other_expenses']['value']['depreciation'] = ['title' => 'Depreciation', 'value' => (($balance_65) * (-1))];
    //        $total_exp += $data['other_expenses']['value']['depreciation']['value'];
    //        //balance of exchange rate Account 675
    //        $keys['cond'] = ' and left(Account_Code,3) = "675" ';
    //        $balance_675 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['other_expenses']['value']['ex_rate'] = ['title' => 'Difference of exchange rate', 'value' => (($balance_675) * (-1))];
    //        $total_exp += $data['other_expenses']['value']['ex_rate']['value'];
    //        // balance of charges and fees Accounts 64, 66 & 67
    //        $keys['cond'] = ' and left(Account_Code,2) = "64" ';
    //        $balance_64 = self::returnExactBalanceByID($keys)['Balance'];
    //        $keys['cond'] = ' and left(Account_Code,2) = "66" ';
    //        $balance_66 = self::returnExactBalanceByID($keys)['Balance'];
    //        $keys['cond'] = ' and left(Account_Code,2) = "67" ';
    //        $balance_67 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['other_expenses']['value']['charges_fees'] = ['title' => 'Charges & Fees', 'value' => (($balance_64 + $balance_67 + $data['other_expenses']['value']['ex_rate']['value'] + $balance_66) * (-1))];
    //        $total_exp += $data['other_expenses']['value']['charges_fees']['value'];
    //        //Total expenditures is the summation of all other expenses
    //        $data['total_expense'] = ['title' => 'Total Expenditures', 'value' => $total_exp];
    //        //Net profit or losses is the summation of gross margin and total expenditures
    //        $data['net'] = ['title' => 'Net profit or loss', 'value' => ($data['gross_margin']['value'] + $data['total_expense']['value'])];
    //        //Retained earnings of begining of year 139 (loss) or 138 (profit)
    //        $keys['cond'] = ' and left(Account_Code,3) = "139" ';
    //        $balance_139 = self::returnExactBalanceByID($keys)['Balance'];
    //        $keys['cond'] = ' and left(Account_Code,3) = "138" ';
    //        $balance_138 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['retained_begin'] = ['title' => 'Retained Earnings of Begining of year', 'value' => (($balance_139 * (-1)) + ($balance_138 * (-1)))];
    //        //Retained earnings of end of year
    //        $keys['cond'] = ' and left(t.Account_Code,1) = "6" ';
    //        $balance_6 = self::returnExactBalanceByID($keys)['Balance'];
    //        $data['retained_end'] = ['title' => 'Retained Earnings of Ending of year', 'value' => (($balance_6 * (-1)) + $data['sales']['value'] + $data['retained_begin']['value'])];
    //
    //        return $data;
    //    }

    public function statementOfIncome($keys) {
        //        echo$keys['stock_method'];
        //        echo"<pre>";die(print_r($keys));
        //                $data['cost_goods']['value']['variation_stock'] = ['title' => 'Variation of stock', 'value' => ((self::getExactBalance($keys, 6052, 4)['Balance'] + self::getExactBalance($keys, 6051, 4)['Balance']) * (-1))];
        //from_date//to_date//currency//is_actual
        $data = array();
        //Balance for sales accounts should be credit (-ve), display it as (+ve)
        $keys['left'] = 1;
        $keys['code'] = 7;
        $keys['Currency_ID'] = $keys['currency'];
        $sales = self::returnExactBalance($keys)['Balance'] * -1;
        $data['sales'] = ['title' => 'sales', 'value' => $sales, 'link' => 1, 'account' => 7, 'tooltip' => 'sales_tooltip'];
        //Balance for purchases except 605, should be in debit (+ve), display it as (-ve)
        $data['cost_goods']['title'] = 'cost_of_goods';
        $keys['code'] = 60;
        $cost_goods = self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 605;
        $cost_goods -= self::returnExactBalance($keys)['Balance'];
        $data['cost_goods']['value']['purchases'] = ['title' => 'purchases', 'value' => ($cost_goods * (-1)), 'tooltip' => 'purchase_tooltip'];
        //Balance of costs on purchases, should be in debit (+ve), display as (-ve)
        $keys['code'] = 61;
        $cost_purchase = self::returnExactBalance($keys)['Balance'] * -1;
        $data['cost_goods']['value']['cost_purchases'] = ['title' => 'cost_of_purchases', 'value' => $cost_purchase, 'tooltip' => 'cost_purchase_tooltip'];
        //Balance of variation of stock ending(6052) - begining(6051)
        //begining stock
        $stock_value = 0;
        if ($keys['stock_method'] == "acc") {
            $acc_id = smc_session()['account_setting']['begining_stock_account_id'];
            $keys['code'] = JV::getAccountCodeByID($acc_id);
            $stock_value = self::returnExactBalance($keys)['Balance'];
        } else if ($keys['stock_method'] === 'manual') {
            $stock_value = $keys['stock_value'];
        } else {
            $product = new Product();
            $stock_value = ($product->costing_report(['date' => $keys['from_date'], 'type' => $keys['stock_method'], 'type_id' => $keys['stock_type']])['total']);
            $stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $stock_value);
        }
        //end stock
        $end_stock_value = 0;
        if ($keys['end_stock_method'] == "acc") {
            $acc_id = smc_session()['account_setting']['end_stock_account_id'];
            $keys['code'] = JV::getAccountCodeByID($acc_id);
            $end_stock_value = self::returnExactBalance($keys)['Balance'] * -1;
        } else if ($keys['end_stock_method'] === 'manual') {
            $end_stock_value = $keys['end_stock_value'];
        } else {
            $product = new Product();
            $end_stock_value = ($product->costing_report(['date' => $keys['to_date'], 'type' => $keys['end_stock_method'], 'type_id' => $keys['end_stock_type']])['total']);
            $end_stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $end_stock_value);
        }
        $last_stock_val = $end_stock_value - $stock_value;
        $data['cost_goods']['value']['ending_stock'] = ['title' => 'ending_stock', 'value' => $end_stock_value];
        $data['cost_goods']['value']['begining_stock'] = ['title' => 'begining_stock', 'value' => $stock_value];
        $data['cost_goods']['value']['variation_stock'] = ['title' => 'variation_of_stock', 'value' => $last_stock_val, 'tooltip' => 'variation_stock_tooltip'];
        //total balance for costs of goods
        $data['cost_goods']['value']['total'] = ['title' => 'total_cost_of_sold_goods', 'value' => ($data['cost_goods']['value']['purchases']['value'] + $data['cost_goods']['value']['cost_purchases']['value'] + $data['cost_goods']['value']['variation_stock']['value']), 'tooltip' => 'total_cost_sold_goods_tooltip'];
        //balance for Accounts 1 & 2
        $data['gross_margin'] = ['title' => 'gross_margins', 'value' => ($data['sales']['value'] + $data['cost_goods']['value']['total']['value']), 'tooltip' => 'gross_margin_tooltip'];
        // balance of general and administrative expenses 62 and 68 and should be in debit (+ve), display as (-ve)
        $data['other_expenses']['title'] = 'other_expenses';
        $total_exp = 0.0;
        $keys['code'] = 62;
        $general_admin = (self::returnExactBalance($keys)['Balance'] * -1);
        $keys['code'] = 68;
        $general_admin += (self::returnExactBalance($keys)['Balance'] * -1);
        $data['other_expenses']['value']['general_admin'] = ['title' => 'general_admin_expenditures', 'value' => $general_admin, 'tooltip' => 'general_admin_tooltip'];
        $total_exp += $data['other_expenses']['value']['general_admin']['value'];
        //balance of labor and wages Accounts 63
        $keys['code'] = 63;
        $labor_wages = self::returnExactBalance($keys)['Balance'] * -1;
        $data['other_expenses']['value']['labor_wages'] = ['title' => 'labor_wages', 'value' => $labor_wages, 'tooltip' => 'labor_wages_tooltip'];
        $total_exp += $data['other_expenses']['value']['labor_wages']['value'];
        //balance of depreciation Accounts 65
        $keys['code'] = 65;
        $depreciation = self::returnExactBalance($keys)['Balance'] * -1;
        $data['other_expenses']['value']['depreciation'] = ['title' => 'depreciation', 'value' => $depreciation, 'tooltip' => 'depreciation_tooltip'];
        $total_exp += $data['other_expenses']['value']['depreciation']['value'];
        //balance of exchange rate Account 675
        $keys['code'] = 675;
        $ex_rate = (self::returnExactBalance($keys)['Balance'] * -1);
        $data['other_expenses']['value']['ex_rate'] = ['title' => 'difference_exchange_rate', 'value' => $ex_rate, 'tooltip' => 'ex_rate_tooltip'];
        $total_exp += $data['other_expenses']['value']['ex_rate']['value'];
        // balance of charges and fees Accounts 64, 66 & 67
        $keys['code'] = 64;
        $charges_fees = (self::returnExactBalance($keys)['Balance'] * -1);
        $keys['code'] = 67;
        $charges_fees += (self::returnExactBalance($keys)['Balance'] * -1);
        $charges_fees += $data['other_expenses']['value']['ex_rate']['value'];
        $keys['code'] = 66;
        $charges_fees += (self::returnExactBalance($keys)['Balance'] * -1);
        $data['other_expenses']['value']['charges_fees'] = ['title' => 'charges_fees', 'value' => $charges_fees, 'tooltip' => 'charges_fees_tooltip'];
        $total_exp += $data['other_expenses']['value']['charges_fees']['value'];
        //Total expenditures is the summation of all other expenses
        $data['total_expense'] = ['title' => 'total_expenditures', 'value' => $total_exp];
        //Net profit or losses is the summation of gross margin and total expenditures
        $data['net'] = ['title' => 'net_profit', 'value' => ($data['gross_margin']['value'] + $data['total_expense']['value']), 'tooltip' => 'net_tootltip'];
        //Retained earnings of begining of year 139 (loss) or 138 (profit)
        $keys['code'] = 139;
        $retained_begin = self::returnExactBalance($keys)['Balance'] * -1;
        $keys['code'] = 138;
        $retained_begin += (self::returnExactBalance($keys)['Balance'] * -1);
        $data['retained_begin'] = ['title' => 'retained_earn_beg_year', 'value' => $retained_begin, 'tooltip' => 'retained_earn_beg_year_tooltip'];
        //Retained earnings of end of year
        //        $data['retained_end'] = ['title' => 'retained_earn_end_year', 'value' => ((self::getExactBalance($keys, 6, 1)['Balance'] * (-1)) + $data['sales']['value'] + $data['retained_begin']['value']),'tooltip'=>'retained_end_tooltip'];
        $data['retained_end'] = ['title' => 'retained_earn_end_year', 'value' => ( $data['net']['value'] + $data['retained_begin']['value'])];

        return $data;
    }

    public function StmtFinancialPosition($keys) {
        //from_date//to_date//currency//is_actual
        $data = array();
        $keys['left'] = 1;
        $keys['code'] = 5;
        $keys['Currency_ID'] = $keys['currency'];
        $a = self::returnExactBalance($keys)['Balance'];
        //        echo"<pre>";
        //        die(print_r($a));
        //        $a = self::getExactBalance($keys, 5, 1)['Balance'];
        $b = 0;
        $data['assets']['cash'] = ['title' => commonLanguage::getMessage('cash_cash_equivalent'), 'value' => $a, 'tooltip' => CommonLanguage::getMessage('cash_tooltip')];
        $keys['code'] = 21;
        $b += self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 22;
        $b += self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 28;
        $b += self::returnExactBalance($keys)['Balance'];
        //        $b = (self::getExactBalance($keys, 21, 2)['Balance'] + self::getExactBalance($keys, 22, 2)['Balance'] + self::getExactBalance($keys, 28, 2)['Balance']);
        $data['assets']['non_current'] = ['title' => commonLanguage::getMessage('non_current_assets'), 'value' => $b, 'tooltip' => CommonLanguage::getMessage('non_current_assets_tooltip')];
        //
        //        $c = 0;
        //        if ($keys['end_stock_method'] == "acc") {
        //            $acc_id = smc_session()['account_setting']['end_stock_account_id'];
        //            $keys['code'] = JV::getAccountCodeByID($acc_id);
        //            $c = self::returnExactBalance($keys)['Balance'];
        ////            $c = (self::getExactBalance($keys, $acc_code, strlen($acc_code))['Balance'] );
        //        } else if ($keys['end_stock_method'] === 'manual') {
        //            $c = $keys['stock_value'];
        //        } else {
        //            $product = new Product();
        //            $c = ($product->costing_report(['date' => $keys['to_date'], 'type' => 'method', 'type_id' => $keys['stock_type']])['total']);
        //            $c = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $c);
        //        }

        $stock_value = 0;
        if ($keys['stock_method'] == "acc") {
            $acc_id = smc_session()['account_setting']['begining_stock_account_id'];
            $keys['code'] = JV::getAccountCodeByID($acc_id);
            $stock_value = self::returnExactBalance($keys)['Balance'];
            //            $stock_value = ( self::getExactBalance($keys, $acc_code, strlen($acc_code))['Balance'] );
        } else if ($keys['stock_method'] === 'manual') {
            $stock_value = $keys['stock_value'];
        } else {
            $product = new Product();
            $stock_value = ($product->costing_report(['date' => $keys['from_date'], 'type' => $keys['stock_method'], 'type_id' => $keys['stock_type']])['total']);
            $stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $stock_value);
        }
        $acc_id = smc_session()['account_setting']['end_stock_account_id'];
        $keys['code'] = JV::getAccountCodeByID($acc_id);
        $stock_row = self::returnExactBalance($keys)['Balance'];
        //end stock
        $end_stock_value = 0;
        if ($keys['end_stock_method'] == "acc") {
            //            $acc_id = smc_session()['account_setting']['end_stock_account_id'];
            //            $keys['code'] = JV::getAccountCodeByID($acc_id);
            $end_stock_value = $stock_row * -1;
            //            $end_stock_value = (self::getExactBalance($keys, $acc_code, strlen($acc_code))['Balance'] ) * -1;
        } else if ($keys['end_stock_method'] === 'manual') {
            $end_stock_value = $keys['end_stock_value'];
        } else {
            $product = new Product();
            $end_stock_value = ($product->costing_report(['date' => $keys['to_date'], 'type' => $keys['end_stock_method'], 'type_id' => $keys['end_stock_type']])['total']);
            $end_stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $keys['currency'], $end_stock_value);
        }
        //        echo  $end_stock_value.'==='.$stock_value;
        $last_stock_val = $end_stock_value - $stock_value;
        //        $c = self::getExactBalance($keys, 37, 2)['Balance'];
        $data['assets']['stock'] = ['title' => commonLanguage::getMessage('stock'), 'value' => $stock_row, 'tooltip' => CommonLanguage::getMessage('ending_stock')];
        $first = '40';
        $second = '41';
        $third = '42,43,44,46,47';
        //        $third = '43';
        $d = $e = $f = $g = 0.0;
        $first_arr = self::getExactAccounts($keys, $first, 2);
        //        echo"<pre>";die(print_r($first_arr));
        $keys['left'] = 0;
        for ($i = 0; $i < count($first_arr); $i++) {
            $keys['code'] = $first_arr[$i];
            $balance = self::returnExactBalance($keys)['Balance'];
            //            $balance = self::getExactBalance($keys, $first_arr[$i], strlen($first_arr[$i]), true)['Balance'];

            ($balance > 0) ? $e += $balance : ((substr($first_arr[$i], 0, 2) == "40") ? $f += $balance : $g += $balance);
        }
        $second_arr = self::getExactAccounts($keys, $second, 2);
        for ($i = 0; $i < count($second_arr); $i++) {
            $keys['code'] = $second_arr[$i];
            $balance = self::returnExactBalance($keys)['Balance'];
            //            $balance = self::getExactBalance($keys, $second_arr[$i], strlen($second_arr[$i]), true)['Balance'];
            ($balance > 0) ? $d += $balance : $g += $balance;
        }
        $third_arr = self::getExactAccounts($keys, $third, 2);
        for ($i = 0; $i < count($third_arr); $i++) {
            $keys['code'] = $third_arr[$i];
            $balance = self::returnExactBalance($keys)['Balance'];
            //            $balance = self::getExactBalance($keys, $third_arr[$i], strlen($third_arr[$i]), true)['Balance'];
            ($balance > 0) ? $e += $balance : $g += $balance;
        }
        $data['assets']['account_receivables'] = ['title' => commonLanguage::getMessage('account_receivables'), 'value' => $d, 'tooltip' => CommonLanguage::getMessage('account_receivables_tooltip')];
        $data['assets']['other_receivables'] = ['title' => commonLanguage::getMessage('other_receivables'), 'value' => $e, 'tooltip' => CommonLanguage::getMessage('other_receivables_tooltip')];
        $data['liabilities']['account_payable'] = ['title' => commonLanguage::getMessage('accounts_payable'), 'value' => $f * (-1), 'tooltip' => CommonLanguage::getMessage('account_payable_tooltip')];
        $data['liabilities']['other_payable'] = ['title' => commonLanguage::getMessage('other_payable'), 'value' => $g * (-1), 'tooltip' => CommonLanguage::getMessage('other_payable_tooltip')];
        $keys['left'] = 1;
        $keys['code'] = 45;
        $h = self::returnExactBalance($keys)['Balance'];
        //        $h = self::getExactBalance($keys, 45, 2)['Balance'];
        $data['liabilities']['partners'] = ['title' => commonLanguage::getMessage('due_to_partners'), 'value' => $h * (-1), 'tooltip' => CommonLanguage::getMessage('due_to_partner_tooltip')];
        $capital_acc_id = smc_session()['account_setting']['capital_acc_id'];
        $keys['code'] = JV::getAccountCodeByID($capital_acc_id);
        $i = self::returnExactBalance($keys)['Balance'];
        //        $i = self::getExactBalance($keys, $capital_acc_code, strlen($capital_acc_code))['Balance'];
        $data['liabilities']['capital'] = ['title' => commonLanguage::getMessage('capital'), 'value' => $i * (-1), 'tooltip' => CommonLanguage::getMessage('accounts_in') . $keys['code']];

        $j = 0;
        $keys['code'] = 139;
        $j += self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 138;
        $j += self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 6;
        $j += self::returnExactBalance($keys)['Balance'];
        $keys['code'] = 7;
        $j += self::returnExactBalance($keys)['Balance'];
        $j -= $last_stock_val;
        //        $j = self::getExactBalance($keys, 139, 3)['Balance'] + self::getExactBalance($keys, 138, 3)['Balance'] + self::getExactBalance($keys, 6, 1)['Balance'] + self::getExactBalance($keys, 7, 1)['Balance'] + $last_stock_val;
        $data['liabilities']['loss_profit'] = ['title' => commonLanguage::getMessage('accumulated_losses_profit'), 'value' => $j * (-1), 'tooltip' => CommonLanguage::getMessage('loss_profit_tooltip')];
        $data['liabilities']['total'] = ['title' => commonLanguage::getMessage('total_liabilities'), 'value' => ($f + $g + $h + $i + $j) * (-1)];
        $data['assets']['total'] = ['title' => commonLanguage::getMessage('total_assets'), 'value' => ($a + $b + $stock_row + $d + $e)];

        return $data;
    }

    public static function getDebitCreditTotals($fields) {
        $db = DBConnectorFactory::loadDriver();
        $cond = ' ';
        $data = array();
        if (!empty($fields['Transaction_Date_From']) && !empty($fields['Transaction_Date_To'])) {
            $cond .= ' and t.Transaction_Date >= "' . $fields['Transaction_Date_From'] . '" AND t.Transaction_Date <= "' . $fields['Transaction_Date_To'] . '"';
        }
        if (!empty($fields['due_date_from']) && !empty($fields['due_date_to'])) {
            $cond .= 'and  due_date >= "' . $fields['due_date_from'] . '" AND due_date <= "' . $fields['due_date_to'] . '"';
        }
        if ($fields['Is_Actual'] == 0) {
            $cond .= ' and t.is_actual = "' . $fields['Is_Actual'] . '" ';
        }
        if (isset($fields['trans_type']) && $fields['trans_type'] != '') {
            $cond .= ' and t.main_type in ("' . implode('","', $fields['trans_type']) . '") ';
        }
        if (!empty($fields['from_jv'])) {
            $cond .= ' and t.JV_ID >= "' . $fields['from_jv'] . '" ';
        }
        if (!empty($fields['to_jv'])) {
            $cond .= ' and  t.JV_ID <= "' . $fields['to_jv'] . '"';
        }
        if (!empty($fields['from_account'])) {
            $cond .= ' and  left(c.Account_Code,' . strlen($fields['from_account']) . ') >= "' . $fields['from_account'] . '"';
        }
        if (!empty($fields['to_account'])) {
            $cond .= ' and  left(c.Account_Code,' . strlen($fields['to_account']) . ') <= "' . $fields['to_account'] . '"';
        }
        if (!empty($fields['from_amount'])) {
            $cond .= ' and t.Transaction_Amount >= "' . $fields['from_amount'] . '" ';
        }
        if (!empty($fields['to_amount'])) {
            $cond .= ' and  t.Transaction_Amount <= "' . $fields['to_amount'] . '"';
        }
        if (!empty($fields['job_ids'])) {
            $cond .= ' and t.job_id in (' . $fields['job_ids'] . ')';
        }
        if (!empty($fields['project_ids'])) {
            $cond .= ' and t.project_id in (' . $fields['project_ids'] . ')';
        }
        if (!empty($fields['multi_accounts'])) {
            $cond .= ' and t.Account_ID in (' . $fields['multi_accounts'] . ')';
        }
        if (!empty($fields['family_acc'])) {
            $family_accs = CommonACC::get_family_accs_by_id($fields['family_acc']);
            $cond .= ' and t.Account_ID in (' . $family_accs . ')';
        }
        if (!empty($fields['ref_type'])) {
            $cond .= ' and t.subtype in ("' . implode('","', explode(",", $fields['ref_type'])) . '") and t.main_type="mjv" ';
        }
        if (!empty($fields['trans_currency'])) {
            $cond .= ' and t.Currency_ID ="' . $fields['trans_currency'] . '"';
        }
        if (!empty($fields['jv_id'])) {
            $cond = ' and JV_ID = "' . $fields['jv_id'] . '" and is_actual = "' . $fields['Is_Actual'] . '"';
        }

 
        if(Session::getPermissionsObject()->hasPermission('Branches')){
            $cond .= !empty($fields['search_branch_id']) ? ' and branch_id ="' . ($fields['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        


        $year_id = Session::getCurrentYearID();
        $data = array("Debit" => array("amount" => 0, "second_amount" => 0, "Transaction_Type" => "Debit"),
            "Credit" => array("amount" => 0, "second_amount" => 0, "Transaction_Type" => "Credit"));
        $query = $db->query('select sum(t.local_amount) as amount,t.Transaction_Type,t.branch_id,
                sum(t.Transaction_Amount*t.second_currency_rate) as second_amount' . (!empty($fields['is_activity']) ? ',activity_tree.activity_code,activity_tree.activity_title' : '') . '
                    from  tbl_accounting_transactions t join tbl_chart_of_accounts c 
                    on c.Account_ID = t.Account_ID 
                    ' . (!empty($fields['is_activity']) ? ' inner join tbl_activity_tree activity_tree on activity_tree.activity_id =  t.activity_id ' : '') . '
                    where t.current_year_id = "' . $year_id . '"
                     ' . $cond . ' 
                            group by t.Transaction_Type
                ');
 
        while ($row = $db->assoc($query)) {
            $data[$row['Transaction_Type']] = $row;
        }

        return $data;
    }

    public static function view_dep_trans($date) {
        //used from automatic depreciation on load accounting and on edit expense
        // to checked passed date depreciations that do not have transactions yet
        $db = DBConnectorFactory::loadDriver();
        $data = array();
        $query = $db->query('select d.Depreciation_Date_ID,d.Depreciation_Date,d.Depreciation_Amount,cp.Account_ID as pro_account
                ,cd.Account_ID as dep_account,ex.Is_Hidden,ex.Currency_ID,ex.current_rate,r.Depreciation_Rate_Description,
                ex.branch_id,ex.job_id,ex.project_id
                from tbl_accounting_depreciation_dates d join tbl_accounting_depreciation_rate_data r
                on d.Depreciation_Rate_ID = r.Depreciation_Rate_ID
                join tbl_accounting_expenses_details ed on ed.exp_detail_id = r.exp_detail_id
                join tbl_accounting_expenses ex on ex.Expense_ID = ed.Expense_ID
                join tbl_chart_of_accounts cp on cp.main_id = ed.Account_ID and cp.main_type="dep" and cp.sub_type="pro"
                join tbl_chart_of_accounts cd on cd.main_id = ed.Account_ID and cd.main_type="dep" and cd.sub_type="dep"
                where Is_Done = 0  and ex.is_pending = 0 and  Depreciation_Date <="' . $date . '"');
        while ($row = $db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function get_uptodate_dep($rate_id, $is_actual) {
        $db = DBConnectorFactory::loadDriver();
        $start_date = $is_actual ? smc_session()['start_date_act'] : smc_session()['start_date'];
        $end_date = $is_actual ? smc_session()['end_date_act'] : smc_session()['end_date'];
        $query = $db->query('select sum(Depreciation_Amount) as dep_sum 
                from fixed_assets_register where Depreciation_Date between "' . $start_date . '" and "' . $end_date . '" 
                    and Is_Done=1 and Depreciation_Rate_ID = "' . $rate_id . '"
                    group by Depreciation_Rate_ID');
        $row = $db->assoc($query);
        //        die($row['dep_sum'].'===');
        return $row['dep_sum'];
    }

    public function mainDepreciationData($id, $date_from = null, $date_to = null) {
        $condition = '';
        if (!is_null($date_from) and ! is_null($date_to))
            $condition .= ' AND Depreciation_Date BETWEEN ("' . $date_from . '" AND "' . $date_to . '")';
        $query = $this->db->query('SELECT * FROM fixed_assets_register WHERE Depreciation_Rate_ID="' . $id . '" ' . $condition);
        $row = $this->db->assoc($query);
        $row['Total_Amount'] = self::get_uptodate_dep($id, $row['Is_Hidden']);
        return $row;
    }

    // public function general_ledger_report($code, $from_date, $to_date, $currency_id = 0, $type = "All", $back_up = false, $actual_only = false, $users = null, $trans_type = null, $job_ids = null) {
    public function general_ledger_report($options) {
        //        $case = 1;
        $code = !empty($options['Account_Number']) ? $options['Account_Number'] : '';
        $back_up = $options['actual'];
        $from_date = $options['From_Date'] ? $options['From_Date'] : smc_session()['start_date'];
        $to_date = $options['To_Date'] ? $options['To_Date'] : smc_session()['end_date'];
        $actual_only = empty($options['Actual_Only']) ? 0 : $options['Actual_Only'];
        $year_id = $back_up ? $this->year_id_actual : $this->year_id;
        //        $year_id_actual = $this->year_id_actual;
        //        $from_year = substr($from_date, 0, 4);
        $start_date = $back_up ? smc_session()['start_date'] : smc_session()['start_date_act'];
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day'));
        //                echo $day_before.'==';

        $data = array();
        $prev_balance = 0.0;
        $debits = 0.0;
        $credits = 0.0;
        $local_debits = 0.0;
        $local_credits = 0.0;
        $second_debits = 0.0;
        $second_credits = 0.0;
        $current_balance = 0.0;
        $local_balance = 0.0;
        $second_balance = 0.0;
        $all_balance = 0.0;
        //        if ($currency_id == 0)
        $currency_id = $options['Currency_ID'];
        //        $local_currency = smc_session()['local_currency'];
        if (!empty($options['related_acc']) && !empty($code)) {
            $query = $this->db->query('select main_type,main_id,sub_type
                from tbl_chart_of_accounts where Account_Code = "' . $code . '"');
            $row = $this->db->assoc($query);
            if (($row['main_type'] == 'cust' || $row['main_type'] == 'supp') && $row['sub_type'] == 'main') {
                $rel_cond = '';
                if ($row['main_type'] == 'cust')
                    $rel_cond .= ' and main_type = "cust" and sub_type in ("main","bill") ';
                else
                    $rel_cond .= ' and main_type = "supp" and sub_type in ("main","fa","exp") ';

                $query = $this->db->query('select group_concat(Account_ID) as accs from tbl_chart_of_accounts
                    where main_id = "' . $row['main_id'] . '" ' . $rel_cond);

                $row_acc = $this->db->assoc($query)['accs'];
                $options['multi_accounts'] = empty($options['multi_accounts']) ? $row_acc : $options['multi_accounts'] . $row_acc;
                $code = '';
            }
        }
        //        echo $options['multi_accounts'].'====';
        $condition = '';
        if (!empty($options['job_ids']))
            $condition .= ' and t.job_id in (' . $options['job_ids'] . ')';
        if (!empty($options['project_ids']))
            $condition .= ' and t.project_id in (' . $options['project_ids'] . ')';
        if (!empty($options['activity_ids']))
            $condition .= ' and t.activity_id in (' . $options['activity_ids'] . ')';
        if ($options['Type'] == "Credit" or $options['Type'] == "Debit")
            $condition .= ' AND Transaction_Type = "' . $options['Type'] . '"';
        if (!empty($options['trans_type'])) {
            $condition .= ' and t.main_type in ("' . implode('","', $options['trans_type']) . '")';
        }
        if (!empty($options['users'])) {
            $condition .= ' and t.Logged_ID in (' . implode(',', $options['users']) . ')';
        }

        if (!empty($options['from_jv'])) {
            $condition .= ' and t.JV_ID >= "' . $options['from_jv'] . '" ';
        }
        if (!empty($options['to_jv'])) {
            $condition .= ' and  t.JV_ID <= "' . $options['to_jv'] . '"';
        }
        if (!empty($options['from_account'])) {
            $condition .= ' and left(a.Account_Code,' . strlen($options['from_account']) . ') >= "' . $options['from_account'] . '" ';
        }
        if (!empty($options['to_account'])) {
            $condition .= ' and  left(a.Account_Code,' . strlen($options['to_account']) . ') <= "' . $options['to_account'] . '"';
        }
        if (!empty($options['from_amount'])) {
            $condition .= ' and t.Transaction_Amount >= "' . $options['from_amount'] . '" ';
        }
        if (!empty($options['to_amount'])) {
            $condition .= ' and  t.Transaction_Amount <= "' . $options['to_amount'] . '"';
        }
        if (!empty($options['multi_accounts'])) {
            $condition .= ' and t.Account_ID in (' . $options['multi_accounts'] . ')';
        }
        if (!empty($options['family_acc'])) {
            $family_accs = CommonACC::get_family_accs_by_id($options['family_acc']);
            $condition .= ' and t.Account_ID in (' . $family_accs . ')';
        }
        if (!empty($options['ref_type'])) {
            $condition .= ' and t.subtype in ("' . implode('","', explode(",", $options['ref_type'])) . '") and t.main_type="mjv" ';
        }
        if (!empty($options['trans_currency'])) {
            $condition .= ' and t.Currency_ID ="' . $options['trans_currency'] . '"';
        }
        if (!empty($options['branch_id'])) {
            $condition .= ' and t.branch_id ="' . $options['branch_id'] . '"';
        }
        if (!empty($options['salesman_id'])) {
            $condition .= ' and t.salesman_id ="' . $options['salesman_id'] . '"';
        }
        if (!empty($options['pos_customer_id'])) {
            $condition .= ' and t.pos_customer_id ="' . $options['pos_customer_id'] . '"';
        }
        if (!empty($from_date) && !empty($to_date)) {
            $condition .= ' and Transaction_Date >= "' . $from_date . '" and Transaction_Date <= "' . $to_date . '"';
        }
        if (!empty($options['due_date_from']) && !empty($options['due_date_to'])) {
            $condition .= ' and due_date >= "' . $options['due_date_from'] . '" and due_date <= "' . $options['due_date_to'] . '"';
        }

        if (!empty($code)) {//condition in case user select date or anything before selecting code
            $code = str_replace(',', '","', $code);
            $condition .= ' AND a.Account_Code IN ("' . $code . '")';
        }
        //        if(!empty($options['multi_year'])){
        //            $condition.='  and t.main_type not in ("opy","cly") ';
        //        }else{
        $condition .= ' and current_year_id = "' . $year_id . '"';
        //        }
        $open_arr = $options;

        $open_arr['code'] = $code;
        $open_arr['From_Date'] = empty($from_date) ? '' : $start_date;
        $open_arr['To_Date'] = empty($from_date) ? '' : $day_before;
        $open_arr['Opening_Balance'] = 1;
        $open_arr['Is_Actual'] = $back_up;
        $open_arr['Actual_Only'] = $actual_only;
        //        echo "<pre>";die(print_r($open_arr));
        $prev_arr = array();
        if (!empty($start_date) && ($start_date < $from_date || $start_date < $open_arr['due_date_from'])) {
            $prev_arr = self::returnExactBalance($open_arr);
            //            echo"<pre>";
            //            die(print_r($prev_arr));
            //        echo $prev_balance . '==';
            $prev_balance = $prev_arr['Balance'];
            $all_balance = $prev_arr['Balance'];
            //            "local_debits" => $debits_local,
            //            "local_credits" => $credits_local,
            //            "second_debits" => $debits_second,
            //            "second_credits" => $credits_second,
            //            "local_balance" => $local_balance,
            //            "second_balance" => $second_balance
            $data[] = array(
                "main_id" => "0",
                "main_type" => "0",
                "Transaction_Account" => "--",
                "Account_Name" => "--",
                "Transaction_Date" => "--",
                "due_date" => "--",
                "JV_ID" => "--",
                "jv" => "--",
                "Ref_ID" => "--",
                "job_name" => "--",
                "user_ref" => "--",
                "main_nb" => "--",
                "Transaction_Description" => "Opening Balance",
                "Debit" => $prev_arr['Debits'],
                "Credit" => $prev_arr['Credits'],
                "Current_Balance" => $prev_arr['Balance'],
                "local_debit" => $prev_arr['local_debits'],
                "local_credit" => $prev_arr['local_credits'],
                "local_balance" => $prev_arr['local_balance'],
                "second_debit" => $prev_arr['second_debits'],
                "second_credit" => $prev_arr['second_credits'],
                "second_balance" => $prev_arr['second_balance'],
                "All_Balance" => $all_balance
            );
        }
        //        }
        //die();
        if (!$back_up) {
            $condition .= ' and t.is_actual = 0';
        } else if ($actual_only) {
            $condition .= ' and t.is_actual = 1';
        }

        //$condition .= ' and t.branch_id = 1'; ////for branches but pos

        //        if (!$actual_only) {
        $query_current = $this->db->query('
                                                    SELECT 
                                                        t.Transaction_Reference,
                                                        t.user_ref,
                                                        t.Currency_ID,
                                                        t.Transaction_Amount,
                                                        t.Current_Ex_Rate,
                                                        t.second_currency_rate,
                                                        t.Exchange_Rate_ID,
                                                        t.Transaction_Type,
                                                        t.main_id,
                                                        t.main_type,
                                                        t.Transaction_Description,
                                                        concat(if(t.is_actual=1,"Act.",""),t.JV_ID) as JV_ID,
                                                        t.JV_ID as jv,
                                                        t.Transaction_Date,
                                                        t.due_date,
                                                        a.Account_Code,
                                                        a.Account_Name,
                                                        t.prefix as serial_prefix,
                                                        t.is_actual,
                                                        if(isnull(j.job_name),"",j.job_name) as job_name,
                                                        t.local_amount,
                                                        (t.Transaction_Amount*t.second_currency_rate) as second_amount,
                                                        concat(Transaction_Date,JV_ID) as date_jv,t.main_nb,t.prefix,
                                                        t.check_nb' . (!empty($options['is_activity']) ? ',activity_tree.activity_code,activity_tree.activity_title' : '') . '
                                                    FROM 
                                                        tbl_accounting_transactions t
                                                        join tbl_chart_of_accounts a
                                                        on a.Account_ID = t.Account_ID
                                                        left join tbl_accounting_jobs j
                                                        on j.Job_ID = t.Job_ID
                                                        ' . (!empty($options['is_activity']) ? ' inner join tbl_activity_tree activity_tree on activity_tree.activity_id =  t.activity_id ' : '') . '
                                                    WHERE  
                                                        1=1

                                                    ' . $condition . '
                                                    ORDER BY 
                                                        Transaction_Date,t.JV_ID
                            ');
        while ($row_current = $this->db->assoc($query_current)) {
            $temp_amount = 0.0;
            $do = true;
            if ($currency_id == smc_session()['local_currency']) {
                //for exchange rate
                $temp_amount = $row_current['local_amount'];
            } else {
                $temp_amount = self::getExchangedAmount($currency_id, $row_current['Currency_ID'], $row_current['Transaction_Amount'], $row_current['Current_Ex_Rate'], $row_current['second_currency_rate'], $row_current['Exchange_Rate_ID']);
            }
            if ($row_current['Transaction_Type'] == 'Debit' and $do == true) {
                $current_balance += $temp_amount;
                $local_balance += $row_current['local_amount'];
                $second_balance += $row_current['second_amount'];
                $debits += $temp_amount;
                $local_debits += $row_current['local_amount'];
                $second_debits += $row_current['second_amount'];
                $all_balance += $temp_amount;
                $debit_amount = $temp_amount;
                $local_debit_amount = $row_current['local_amount'];
                $second_debit_amount = $row_current['second_amount'];
                $local_credit_amount = 0;
                $second_credit_amount = 0;
                $credit_amount = 0.00;
            } elseif ($row_current['Transaction_Type'] == 'Credit' and $do == true) {
                $current_balance -= $temp_amount;
                $local_balance -= $row_current['local_amount'];
                $second_balance -= $row_current['second_amount'];
                $credits += $temp_amount;
                $local_credits += $row_current['local_amount'];
                $second_credits += $row_current['second_amount'];
                $all_balance -= $temp_amount;
                $credit_amount = $temp_amount;
                $local_debit_amount = 0;
                $second_debit_amount = 0;
                $debit_amount = 0.00;
                $local_credit_amount = $row_current['local_amount'];
                $second_credit_amount = $row_current['second_amount'];
            }
            $edit_arr = CommonACC::get_edit_link_by_type($row_current['main_type'], $row_current['main_id'], $row_current['is_actual'], $row_current['JV_ID']);
            $activity_code = '';
            $activity_title = '';
            if (!empty($options['is_activity'])) {
                $activity_code = $row_current['activity_code'];
                $activity_title = $row_current['activity_title'];
            }
            $abrv = CommonBusiness::get_trans_main_type($row_current['main_type'], true);
            $data[] = array(
                "serial_prefix" => $row_current['serial_prefix'],
                "main_id" => $row_current['main_id'],
                "main_type" => $row_current['main_type'],
                "check_nb" => $row_current['check_nb'],
                "activity_code" => $activity_code,
                "activity_title" => $activity_title,
                "link" => $edit_arr['link'],
                "has_permission" => ($this->permissions->hasPermission($edit_arr['permission']) ? 1 : 0),
                "main_nb" => $abrv . ' ' . $row_current['prefix'] . $row_current['main_nb'],
                "is_actual" => $row_current['is_actual'],
                "Transaction_Account" => $row_current['Account_Code'],
                "Account_Name" => $row_current['Account_Name'],
                "Transaction_Date" => $row_current['Transaction_Date'],
                "JV_ID" => $row_current['JV_ID'],
                "jv" => $row_current['jv'],
                "Ref_ID" => $row_current['Transaction_Reference'],
                "user_ref" => $row_current['user_ref'],
                "job_name" => $row_current['job_name'],
                "due_date" => $row_current['due_date'],
                "Transaction_Description" => $row_current['Transaction_Description'],
                "Debit" => $debit_amount,
                "Credit" => $credit_amount,
                "Current_Balance" => $current_balance,
                "local_debit" => $local_debit_amount,
                "local_credit" => $local_credit_amount,
                "local_balance" => $local_balance,
                "second_debit" => $second_debit_amount,
                "second_credit" => $second_credit_amount,
                "second_balance" => $second_balance,
                "All_Balance" => $all_balance
            );
        }


        $default = $this->db->query('SELECT
                                            Currency_Symbol
                                        FROM
                                            tbl_common_currency 
                                        WHERE 
                                            Currency_ID = "' . $currency_id . '" ');
        $default_row = $this->db->assoc($default);
        $row_current['Currency_Symbol'] = $default_row['Currency_Symbol'];

        $data['Currency_Symbol'] = $row_current;
        $data['Total'] = array(
            "Prev_Balance" => $prev_balance,
            "Debit" => $debits,
            "Credit" => $credits,
            "Current_Balance" => $current_balance,
            "local_debit" => $local_debits,
            "local_credit" => $local_credits,
            "local_balance" => $local_balance,
            "second_debit" => $second_debits,
            "second_credit" => $second_credits,
            "second_balance" => $second_balance,
            "All_Balance" => $all_balance
        );
        //        "Debit" => $prev_arr['Debits'],
        //                "Credit" => $prev_arr['Credits'],
        //                "Current_Balance" => $prev_arr['Balance'],
        //                "local_debit" => $prev_arr['local_debits'],
        //                "local_credit" => $prev_arr['local_credits'],
        //                "local_balance" => $prev_arr['local_balance'],
        //                "second_debit" => $prev_arr['second_debits'],
        //                "second_credit" => $prev_arr['second_credits'],
        //                "second_balance" => $prev_arr['second_balance'],
        //                "All_Balance" => $all_balance
        //        if (!empty($prev_arr)) {
        $data['last_total'] = array(
            "Prev_Balance" => $prev_balance,
            "Debit" => ($debits + (!empty($prev_arr['Debits']) ? $prev_arr['Debits'] : 0)),
            "Credit" => ($credits + (!empty($prev_arr['Credits']) ? $prev_arr['Credits'] : 0)),
            "Current_Balance" => ($current_balance + (!empty($prev_arr['Balance']) ? $prev_arr['Balance'] : 0)),
            "local_debit" => ($local_debits + (!empty($prev_arr['local_debits']) ? $prev_arr['local_debits'] : 0)),
            "local_credit" => ($local_credits + (!empty($prev_arr['local_credits']) ? $prev_arr['local_credits'] : 0)),
            "local_balance" => ($local_balance + (!empty($prev_arr['local_balance']) ? $prev_arr['local_balance'] : 0)),
            "second_debit" => ($second_debits + (!empty($prev_arr['second_debits']) ? $prev_arr['second_debits'] : 0)),
            "second_credit" => ($second_credits + (!empty($prev_arr['second_credits']) ? $prev_arr['second_credits'] : 0)),
            "second_balance" => ($second_balance + (!empty($prev_arr['second_balance']) ? $prev_arr['second_balance'] : 0)),
            "All_Balance" => $all_balance
        );
        //        }
        //        echo"<pre>";
        //        die(print_r($data));
        return $data;
    }

    public static function check_left_accounts($from_account, $to_account, $account) {
        //        $from_account = (int) $from_account;
        //        $to_account = (int) $to_account;
        //        echo min($to_account, $account).'<br>';
        //        echo substr($account, 0, strlen(min($from_account, $account))).'=='.substr($from_account, 0, strlen(min($from_account, $account))).'<br>';
        //        echo substr($account, 0, strlen(min($from_account, $account))) >= substr($from_account, 0, strlen(min($from_account, $account))) ? 'true<br>' : 'false<br>';
        //        echo substr($account, 0, strlen(min($to_account, $account))) <= substr($to_account, 0, strlen(min($to_account, $account))) ? 'true<br>' : 'false<br>';
        if (substr($account, 0, strlen(min($from_account, $account))) >= substr($from_account, 0, strlen(min($from_account, $account))) && substr($account, 0, strlen(min($to_account, $account))) <= substr($to_account, 0, strlen(min($to_account, $account))))
            $flag = true;
        else
            $flag = false;
        return $flag;
        //                echo $from_account . '==' . $to_account . '==' . $account .($flag==1 ? '==true' : '==false'). '<br>';
    }

    public function trial_balance_report($options) {
        //public function trialBalanceByDigits($num_digits, $group_num, $from_date = null, $to_date = null, $active = 0, $back_up = false, $currency_id = 0, $opening_balance = 1, $actual_only = false, $from_acc = 1, $to_acc = 8) {
        $options['is_trial_balance'] = 1;
        $num_digits = $options['digits'];
        $group_num = $options['Grouping'];
        $from_date = $options['From_Date'] ? $options['From_Date'] : smc_session()['start_date'];
        //        $to_date = $options['To_Date'] ? $options['To_Date'] : smc_session()['end_date'];
        //        $currency_id = $options['Currency_ID'];
        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 0;
        $with_close = !empty($options['with_close']) ? $options['with_close'] : 0;
        //        die($with_close.'==');
        //        $active = !empty($options['Active']) ? $options['Active'] : 0;
        //        $unmoved = !empty($options['unmoved']) ? $options['unmoved'] : 0;
        $back_up = $options['Is_Actual'] == 1 ? true : false;
        //        $actual_only = $options['Actual_Only'] == 1 ? true : false;
        //        $len_zeros_nines = $group_num - 1;
        //        $nines = str_repeat("9", $len_zeros_nines);
        $len_zeros_nines_2 = $num_digits - $group_num;
        $nines_2 = str_repeat("9", $len_zeros_nines_2);


        $start_date = $back_up ? smc_session()['start_date_act'] : smc_session()['start_date']; //used as start for opening balance
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day')); // used as end of opening balance


        $parents_arr = array();
        $acc_arr = array();
        $this->get_coa_tree(0, $parents_arr, $acc_arr, $options);
        $data = array();
        foreach ($parents_arr[0] as $acc_id) {
            $min = $acc_arr[$acc_id]['Account_Code']; // min acc to retreive e.g. ($i=1 => 1)
            $max = $acc_arr[$acc_id]['Account_Code'] . $nines_2; // max acc to retreive e.g. ($i=1 = >19999..)
            $options['code'] = $min;
            $options['left'] = true;
            $options['is_arr'] = true;
            $options['index_acc_id'] = true;
            $options['acc_cond'] = " and length(Account_Code) <= '" . strlen($max) . "' ";
            //
            $open_balance_3_arr = array();
            $close_balance_3_arr = array();
            $prev_balance_3_arr = array();
            $current_array_arr = array();
            if ($opening_balance == 1) {
                $options_opening = $options;
                //                if($options_opening['multi_year']==1){
                //                    $query_year = $this->db->query('select current_year_id from tbl_common_current_year
                //                        where "'.$from_date.'" between start_date and end_date');
                //                    $row_year = $this->db->assoc($query_year)['current_year_id'];
                //                    if(!empty($row_year))
                //                        $options_opening['current_year_id'] = $row_year;
                //                }
                $options_opening['opening_only'] = 1;
                $options_opening['close_only'] = 0;
                $open_balance_3_arr = self::returnExactBalance($options_opening, $acc_arr);
            }
            if ($with_close == 1) {
                $options_close = $options;
                $options_close['opening_only'] = 0;
                $options_close['close_only'] = 1;
                $close_balance_3_arr = self::returnExactBalance($options_close, $acc_arr);
            }
            if ($start_date != $from_date) {

                $options_prev = $options;
                $options_prev['From_Date'] = empty($options_prev['From_Date']) ? '' : $start_date;
                $options_prev['To_Date'] = empty($options_prev['To_Date']) ? '' : $day_before;
                $options_prev['Opening_Balance'] = 1;
                $options_prev['opening_only'] = 0;
                $prev_balance_3_arr = self::returnExactBalance($options_prev, $acc_arr);
            }
            $current_options = $options;
            $current_options['with_close'] = 0;
            $current_options['Opening_Balance'] = 0;
            $current_array_arr = self::returnExactBalance($current_options, $acc_arr);

            $this->build_trial_arr($data, $acc_id, $open_balance_3_arr, $prev_balance_3_arr, $current_array_arr, $close_balance_3_arr, $parents_arr, $acc_arr, $options);
        }
//        echo"<pre>";die(print_r($data));
        return $data;
    }

    public function get_group_totals($acc_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $open_balance = $close_balance = $prev_balance = $debits = $credits = $debits_local = $credits_local = 0;
        $debits_second = $credits_second = $current_balance = $current_balance_local = $current_balance_second = $overall_balance = 0;
        $accounts = array($acc_id);
        $this->get_acc_childs($acc_id, $accounts, $parents_arr);
        $is_parent = false;
        if (!empty($parents_arr[$acc_id]))
            $is_parent = true;
        foreach ($accounts as $current_id) {
            if (!empty($current_arr[$current_id])) {
                $current_balance += $current_arr[$current_id]['Balance'];
                $overall_balance += $current_arr[$current_id]['Balance'];
                $debits += $current_arr[$current_id]['Debits'];
                $credits += $current_arr[$current_id]['Credits'];
                $debits_local += $current_arr[$current_id]['local_debits'];
                $credits_local += $current_arr[$current_id]['local_credits'];
                $debits_second += $current_arr[$current_id]['second_debits'];
                $credits_second += $current_arr[$current_id]['second_credits'];
                $current_balance_local += $current_arr[$current_id]['local_balance'];
                $current_balance_second += $current_arr[$current_id]['second_balance'];
            }
            if (!empty($open_arr[$current_id])) {
                $open_balance += $open_arr[$current_id]['Balance'];
                $overall_balance += $open_arr[$current_id]['Balance'];
            }
            if (!empty($prev_arr[$current_id])) {
                $prev_balance += $prev_arr[$current_id]['Balance'];
                $overall_balance += $prev_arr[$current_id]['Balance'];
            }
            if (!empty($close_arr[$current_id])) {
                $close_balance += $close_arr[$current_id]['Balance'];
                $overall_balance += $close_arr[$current_id]['Balance'];
            }
        }
        if ($is_parent && mb_strlen($acc_arr[$acc_id]['Account_Code']) > $options['Grouping'])
            return null;
        if (mb_strlen($acc_arr[$acc_id]['Account_Code']) > $options['digits'])
            return null;
        if (($is_parent && (abs(round($credits, 3)) > 0 || abs(round($debits, 3)) > 0)) || (abs(round($overall_balance, 3)) > 0) || ($options['Active'] == 0 && (($options['unmoved'] == 0 && (((abs(round($credits, 3)) > 0) || (abs(round($debits, 3)) > 0)))) || $options['unmoved'] == 1) )) {
            return array(
                "Name" => $acc_arr[$acc_id]['Account_Name'], "Code" => $acc_arr[$acc_id]['Account_Code'], "currency" => $acc_arr[$acc_id]['Currency_Symbol'],
                "open_balance" => $open_balance, "close_balance" => $close_balance, "prev_balance" => $prev_balance,
                "Debits" => $debits, "Credits" => $credits, "local_debits" => $debits_local, "local_credits" => $credits_local,
                "second_debits" => $debits_second, "second_credits" => $credits_second, "Balance" => $current_balance,
                "local_balance" => $current_balance_local, "second_balance" => $current_balance_second, "overall_balance" => $overall_balance,
                "is_parent" => $is_parent
            );
        }
        return null;
    }

    public function get_coa_tree($parent_ids, &$parents_arr, &$acc_arr, $options) {
        $new_parent_ids = array();
        $cond = ' ';
        if (!empty($options['from_account']))
            $cond .= ' and left(Account_Code,length(LEAST(Account_Code,"' . $options['from_account'] . '"))) >= left("' . $options['from_account'] . '",length(LEAST(Account_Code,"' . $options['from_account'] . '"))) ';
        if (!empty($options['to_account']))
            $cond .= ' and left(Account_Code,length(LEAST(Account_Code,"' . $options['to_account'] . '"))) <= left("' . $options['to_account'] . '",length(LEAST(Account_Code,"' . $options['to_account'] . '"))) ';
        $query = $this->db->query("select Parent_ID,Account_ID,Account_Code,Account_Name,Currency_Symbol
                from tbl_chart_of_accounts c left join tbl_common_currency cu 
                on cu.Currency_ID = c.Currency_ID where Parent_ID in ({$parent_ids}) " . $cond);
        while ($row = $this->db->assoc($query)) {
            $acc_arr[$row['Account_ID']] = $row;
            if (!isset($parents_arr[$row['Parent_ID']]))
                $parents_arr[$row['Parent_ID']] = array();
            $new_parent_ids[$row['Account_ID']] = $row['Account_ID'];
            $parents_arr[$row['Parent_ID']][] = $row['Account_ID'];
        }
        if (!empty($new_parent_ids))
            $this->get_coa_tree(implode(',', $new_parent_ids), $parents_arr, $acc_arr, $options);
    }

    public function build_trial_arr(&$data, $acc_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $acc_total = $this->get_group_totals($acc_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
        if (!empty($acc_total)) {
            $data[] = $acc_total;
        }
        if (!empty($parents_arr[$acc_id])) {
            foreach ($parents_arr[$acc_id] as $child_id) {
                $this->build_trial_arr($data, $child_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
            }
        }
    }

    public function get_acc_childs($acc_id, &$data, $parents_arr, $is_direct = false) {
        if (!empty($parents_arr[$acc_id])) {
            foreach ($parents_arr[$acc_id] as $child_id) {
                $data[] = $child_id;
                if (!$is_direct) {
                    $this->get_acc_childs($child_id, $data, $parents_arr);
                }
            }
        }
    }

    public function job_trial_balance($options) {
        //        $options['Active'] = 0;
        //        $options['digits'] = 20;
        //        $options['Is_Actual'] = 0;
        //        $options['From_Date'] = '2018-01-01';
        $num_digits = $options['digits'];
        $group_num = $options['Grouping'];
        $from_date = $options['From_Date'];
        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 0;
        $with_close = !empty($options['with_close']) ? $options['with_close'] : 0;
        $back_up = $options['Is_Actual'] == 1 ? true : false;
        $len_zeros_nines = $num_digits - $group_num;
        $nines = str_repeat("9", $len_zeros_nines);
        //        echo $nines.'==';die();

        $start_date = $back_up ? smc_session()['start_date_act'] : smc_session()['start_date']; //used as start for opening balance
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day')); // used as end of opening balance

        $parents_arr = array();
        $acc_arr = array();
        $this->get_job_tree(0, $parents_arr, $acc_arr, $options);
        //        echo"<pre>";
        //        die(print_r($parents_arr));
        $data = array();
        foreach ($parents_arr[0] as $job_id) {
            $min = $acc_arr[$job_id]['job_code']; // min acc to retreive e.g. ($i=1 => 1)
            $max = $acc_arr[$job_id]['job_code'] . $nines; // max acc to retreive e.g. ($i=1 = >19999..)
            $options['code'] = $min;
            $options['left'] = true;
            $options['is_arr'] = true;
            $options['index_acc_id'] = true;
            $options['cond'] = " and length(job_code) <= '" . strlen($max) . "' ";
            //
            $open_balance_3_arr = array();
            $close_balance_3_arr = array();
            $prev_balance_3_arr = array();
            $current_array_arr = array();
            if ($opening_balance == 1) {
                $options_opening = $options;
                $options_opening['opening_only'] = 1;
                $options_opening['close_only'] = 0;
                $open_balance_3_arr = self::returnJobBalance($options_opening);
            }
            if ($with_close == 1) {
                $options_close = $options;
                $options_close['opening_only'] = 0;
                $options_close['close_only'] = 1;
                $close_balance_3_arr = self::returnJobBalance($options_close);
            }
            if ($start_date != $from_date) {

                $options_prev = $options;
                $options_prev['From_Date'] = empty($options_prev['From_Date']) ? '' : $start_date;
                $options_prev['To_Date'] = empty($options_prev['To_Date']) ? '' : $day_before;
                $options_prev['Opening_Balance'] = 1;
                $options_prev['opening_only'] = 0;
                $prev_balance_3_arr = self::returnJobBalance($options_prev);
            }
            //            echo "<pre>";
            //            die(print_r($prev_balance_3_arr));
            $current_options = $options;
            $current_options['with_close'] = 0;
            $current_options['Opening_Balance'] = 0;
            $current_array_arr = self::returnJobBalance($current_options);
            //                        echo"<pre>";print_r($current_array_arr);
            $this->build_job_trial_arr($data, $job_id, $open_balance_3_arr, $prev_balance_3_arr, $current_array_arr, $close_balance_3_arr, $parents_arr, $acc_arr, $options);
        }

        return $data;
    }

    public function get_job_tree($parent_ids, &$parents_arr, &$acc_arr, $options) {
        $new_parent_ids = array();
        $cond = ' ';
        if (!empty($options['from_account']))
            $cond .= ' and left(job_code,length(LEAST(job_code,"' . $options['from_account'] . '"))) >= left("' . $options['from_account'] . '",length(LEAST(job_code,"' . $options['from_account'] . '"))) ';
        if (!empty($options['to_account']))
            $cond .= ' and left(job_code,length(LEAST(job_code,"' . $options['to_account'] . '"))) <= left("' . $options['to_account'] . '",length(LEAST(job_code,"' . $options['to_account'] . '"))) ';
        $query = $this->db->query("select parent_id,job_id,job_code,job_name
                from tbl_accounting_jobs where parent_id in ({$parent_ids}) " . $cond);
        while ($row = $this->db->assoc($query)) {
            $acc_arr[$row['job_id']] = $row;
            if (!isset($parents_arr[$row['parent_id']]))
                $parents_arr[$row['parent_id']] = array();
            $new_parent_ids[$row['job_id']] = $row['job_id'];
            $parents_arr[$row['parent_id']][] = $row['job_id'];
        }
        if (!empty($new_parent_ids))
            $this->get_job_tree(implode(',', $new_parent_ids), $parents_arr, $acc_arr, $options);
    }

    public function build_job_trial_arr(&$data, $job_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $acc_total = $this->get_job_group_totals($job_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
        //       echo $job_id.'==<br>';
        //       echo"<pre>";
        //       print_r($acc_arr);
        if (!empty($acc_total)) {
            $data[] = $acc_total;
        }
        if (!empty($parents_arr[$job_id])) {
            foreach ($parents_arr[$job_id] as $child_id) {

                $this->build_job_trial_arr($data, $child_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
            }
        }
    }

    public function get_job_group_totals($job_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $open_balance = $prev_balance = $close_balance = $debits = $credits = $debits_local = $credits_local = 0;
        $debits_second = $credits_second = $current_balance = $current_balance_local = $current_balance_second = $overall_balance = 0;
        $jobs = array($job_id);
        $this->get_acc_childs($job_id, $jobs, $parents_arr);
        $is_parent = false;
        if (!empty($parents_arr[$job_id]))
            $is_parent = true;
        foreach ($jobs as $current_id) {
            if (!empty($current_arr[$current_id])) {
                $current_balance += $current_arr[$current_id]['Balance'];
                $overall_balance += $current_arr[$current_id]['Balance'];
                $debits += $current_arr[$current_id]['Debits'];
                $credits += $current_arr[$current_id]['Credits'];
                $debits_local += $current_arr[$current_id]['local_debits'];
                $credits_local += $current_arr[$current_id]['local_credits'];
                $debits_second += $current_arr[$current_id]['second_debits'];
                $credits_second += $current_arr[$current_id]['second_credits'];
                $current_balance_local += $current_arr[$current_id]['local_balance'];
                $current_balance_second += $current_arr[$current_id]['second_balance'];
            }
            if (!empty($open_arr[$current_id])) {
                $open_balance += $open_arr[$current_id]['Balance'];
                $overall_balance += $open_arr[$current_id]['Balance'];
            }
            if (!empty($prev_arr[$current_id])) {
                $prev_balance += $prev_arr[$current_id]['Balance'];
                $overall_balance += $prev_arr[$current_id]['Balance'];
            }
            if (!empty($close_arr[$current_id])) {
                $close_balance += $close_arr[$current_id]['Balance'];
                $overall_balance += $close_arr[$current_id]['Balance'];
            }
        }
        if ($is_parent && mb_strlen($acc_arr[$job_id]['job_code']) > $options['Grouping'])
            return null;
        if (mb_strlen($acc_arr[$job_id]['job_code']) > $options['digits'])
            return null;
        if (($is_parent && (abs(round($credits, 3)) > 0 || abs(round($debits, 3)) > 0)) || (abs(round($overall_balance, 3)) > 0) || ($options['Active'] == 0 && (((abs(round($credits, 3)) > 0) || (abs(round($debits, 3)) > 0))))
        ) {
            return array(
                "Name" => $acc_arr[$job_id]['job_name'], "Code" => $acc_arr[$job_id]['job_code'],
                "job_id" => $job_id,
                'open_balance' => $open_balance, 'close_balance' => $close_balance, 'prev_balance' => $prev_balance,
                "Debits" => $debits, "Credits" => $credits, "local_debits" => $debits_local, "local_credits" => $credits_local,
                "second_debits" => $debits_second, "second_credits" => $credits_second, "Balance" => $current_balance,
                "local_balance" => $current_balance_local, "second_balance" => $current_balance_second, "overall_balance" => $overall_balance,
                "is_parent" => $is_parent
            );
        }
        return null;
    }

    public function returnJobBalance($options) {
        //                echo"<pre>";
        //                die(print_r($options));
        $condition = ' ';

        if (!empty($options['left'])) {
            $condition .= ' AND LEFT(job_code,' . strlen($options['code']) . ') = "' . $options['code'] . '"';
        } else {
            $condition .= ' AND job_code IN ("' . $options['code'] . '")';
        }
        $acc_id_arr = array();
        $account_ids = '';
        $query = $this->db->query('SELECT  job_id,job_code
                                            FROM  tbl_accounting_jobs  
                                            WHERE true ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['job_id']] = $row['job_code'];
            $account_ids .= (empty($account_ids) ? '' : ',') . $row['job_id'];
        }
        $options['job_id'] = $account_ids;


        $condition = '';

        if (!empty($options['cond'])) {
            $condition .= $options['cond'];
        }
        if (!empty($options['job_id']))
            $condition .= ' AND t.job_id  in (' . $options['job_id'] . ') ';

        $currency_id = empty($options['Currency_ID']) ? CurrencyFactory::getDefaultCurrency() : $options['Currency_ID'];


        if (!empty($options['opening_only']) && $options['opening_only'] == 1)
            $condition .= '  and t.main_type="opy" ';
        elseif (!empty($options['Opening_Balance']) || $options['Opening_Balance'] == 0)
            $condition .= ' and t.main_type <> "opy" ';

        if (!empty($options['Opening_Balance'])) {
            if (!empty($options['From_Date']) && !empty($options['due_date_from']))
                $condition .= 'and (t.Transaction_Date < "' . $options['To_Date'] . '" or t.due_date < "' . $options['due_date_from'] . '") ';
            else {
                if (!empty($options['From_Date']))
                    $condition .= ' and t.Transaction_Date < "' . $options['To_Date'] . '"';
                if (!empty($options['due_date_from']))
                    $condition .= '  and t.due_date < "' . $options['due_date_from'] . '"';
            }
        }
        if (isset($options['close_only'])) {
            if ($options['close_only'] == 1)
                $condition .= '  and t.main_type="cly" ';
        }
        elseif (isset($options['with_close'])) {
            if ($options['with_close'] == 0)
                $condition .= ' and t.main_type <> "cly" ';
        }
        //
        if (!empty($options['From_Date']) && !empty($options['To_Date']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.Transaction_Date >= "' . $options['From_Date'] . '" 
                                and t.Transaction_Date <= "' . $options['To_Date'] . '" ';
        if (!empty($options['due_date_from']) && !empty($options['due_date_to']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.due_date >= "' . $options['due_date_from'] . '" 
                                and t.due_date <= "' . $options['due_date_to'] . '" ';
        if (isset($options['Is_Actual']) && $options['Is_Actual'] == 0) {
            $condition .= ' and t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '" ';
        } elseif (isset($options['Actual_Only']) && $options['Actual_Only']) {
            $condition .= ' and t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '" ';
        } else
            $condition .= ' and ((t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '") 
                    or ( t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '")) ';

        if (!empty($options['trans_type']) && $options['trans_type'] != '') {
            $condition .= ' and t.main_type in ("' . implode('","', $options['trans_type']) . '") ';
        }
        if (!empty($options['debit_credit_type']) && $options['debit_credit_type'] != 'All') {
            $condition .= ' and t.Transaction_Type = "' . $options['debit_credit_type'] . '" ';
        }
        //        if (!empty($options['from_jv'])) {
        //            $condition .= ' and t.JV_ID >= "' . $options['from_jv'] . '" ';
        //        }
        //        if (!empty($options['to_jv'])) {
        //            $condition .= ' and  t.JV_ID <= "' . $options['to_jv'] . '"';
        //        }
        //        if (!empty($options['from_account'])) {
        //            $condition .= ' and left(t.Transaction_Account,' . strlen($options['from_account']) . ') >= "' . $options['from_account'] . '" ';
        //        }
        //        if (!empty($options['to_account'])) {
        //            $condition .= ' and  left(t.Transaction_Account,' . strlen($options['from_account']) . ') <= "' . $options['to_account'] . '"';
        //        }
        if (!empty($options['from_amount'])) {
            $condition .= ' and t.Transaction_Amount >= "' . $options['from_amount'] . '" ';
        }
        if (!empty($options['to_amount'])) {
            $condition .= ' and  t.Transaction_Amount <= "' . $options['to_amount'] . '"';
        }
        //        if (!empty($options['job_ids'])) {
        //            $condition .=' and t.job_id in (' . $options['job_ids'] . ')';
        //        }
        //        if (!empty($options['multi_accounts'])) {
        //            $condition .=' and t.Account_ID in (' . $options['multi_accounts'] . ')';
        //        }
        //        if (!empty($options['family_acc'])) {
        //            $family_accs = CommonACC::get_family_accs_by_id($options['family_acc']);
        //            $condition .=' and t.Account_ID in (' . $family_accs . ')';
        //        }
        //        if (!empty($options['ref_type'])) {
        //            $condition .=' and t.subtype in ("' . implode('","', explode(",", $options['ref_type'])) . '") and t.main_type="mjv" ';
        //        }
        if (!empty($options['trans_currency'])) {
            $condition .= ' and t.Currency_ID ="' . $options['trans_currency'] . '"';
        }

        $acc_arr = array();
        $query = $this->db->query('SELECT 
                                                t.Transaction_Reference,
                                                t.Currency_ID,
                                                t.Account_ID,
                                                t.job_id,
                                                t.Transaction_Amount,
                                                t.Current_Ex_Rate,
                                                t.second_currency_rate,
                                                t.Exchange_Rate_ID,
                                                t.Transaction_Type,
                                                t.local_amount,
                                                (t.Transaction_Amount*t.second_currency_rate) as second_amount,
                                                t.main_type
                                            FROM tbl_accounting_transactions t  join tbl_accounting_jobs j on j.job_id = t.job_id
                                            WHERE 1=1
                                         ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $temp_amount = 0.0;
            if ($currency_id == smc_session()['local_currency']) {
                $temp_amount = $row['local_amount'];
            } else {
                $temp_amount = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
            }
            //
            $indx = $row['job_id'];
            if (!isset($acc_arr[$indx])) {
                $acc_arr[$indx] = array(
                    "Balance" => 0,
                    "Debits" => 0,
                    "Credits" => 0,
                    "local_debits" => 0,
                    "local_credits" => 0,
                    "second_debits" => 0,
                    "second_credits" => 0,
                    "local_balance" => 0,
                    "second_balance" => 0
                );
            }
            //
            if ($row['Transaction_Type'] == 'Debit') {
                $acc_arr[$indx]["Debits"] += $temp_amount;
                $acc_arr[$indx]["local_debits"] += $row['local_amount'];
                $acc_arr[$indx]["second_debits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] += $temp_amount;
                $acc_arr[$indx]["local_balance"] += $row['local_amount'];
                $acc_arr[$indx]["second_balance"] += $row['second_amount'];
            } elseif ($row['Transaction_Type'] == 'Credit') {
                $acc_arr[$indx]["Credits"] += $temp_amount;
                $acc_arr[$indx]["local_credits"] += $row['local_amount'];
                $acc_arr[$indx]["second_credits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] -= $temp_amount;
                $acc_arr[$indx]["local_balance"] -= $row['local_amount'];
                $acc_arr[$indx]["second_balance"] -= $row['second_amount'];
            }
        }
        return $acc_arr;
    }

    public function get_close_year_trans($actual, $next_year_id = null) {
        //        $this->db->query('START TRANSACTION');
        $year_id = smc_session()['current_year_id'];
        $local_currency_id = smc_session()['local_currency'];
        $year = smc_session()['current_year'];
        $second_year = "";  //$year + 1;
        $date_new = "";
        $next_year_id = empty($next_year_id) ? null : $next_year_id;
        if (!empty($next_year_id)) {
            $query_date = $this->db->query('SELECT current_year,`start_date` FROM `tbl_common_current_year`
            WHERE `current_year_id`="' . $next_year_id . '"');
            $date_row = $this->db->assoc($query_date);
            $date_new = $date_row['start_date'];
            $second_year = $date_row['current_year'];
        }
        $ref = ($year) . '-' . ($second_year);
        $query_branches = $this->db->query('select branch_id,branch_name from tbl_organization_branches ');
        $branches_arr = array();
        while ($row_branch = $this->db->assoc($query_branches))
            $branches_arr[$row_branch['branch_id']] = $row_branch;
        //        $open_acc_codes = array(1, 2, 3, 4, 5); //new year
        $close_acc_codes = smc_session()['account_setting']['close_year_acc_codes']; //'6,7'; //close year
        $transactions = array();
        //        $date_new = $second_year . '-01-01';
        $date_old = smc_session()['end_date'];
        $desc_old = 'Closing of year';
        $desc_new = 'Opening of year';
        //        foreach ($branches as $branch_id => $branch_name) {
        //            $jv_old = JV::returnJV($actual, $year_id);
        //            $jv_new = JV::returnJV($actual, $next_year_id);
        $query = $this->db->query('select t.Account_ID,c.Account_Code,c.Account_Name,t.job_id,
                    ifnull(j.job_name,"") as job_name,t.branch_id,t.pos_customer_id,
                    t.project_id,ifnull(pr.project_name,"") as project_name,c.Currency_ID as account_currency,
                    sum(if(t.Transaction_Type = "Credit",t.local_amount*-1,t.local_amount)) as local_amount,
                    sum(if(t.Transaction_Type="Credit",-1,1) * if(t.Currency_ID=c.Currency_ID,t.Transaction_Amount, if(c.Currency_ID="' . smc_session()['second_currency']['id'] . '", (t.Transaction_Amount*t.second_currency_rate), 0))) as acc_curr_amount,
                    sum(if(t.Transaction_Type="Credit",-1,1) * if(t.Currency_ID=c.Currency_ID or c.Currency_ID="' . smc_session()['second_currency']['id'] . '", 0, (t.local_amount))) as acc_curr_local_amount
                from tbl_accounting_transactions t 
                    inner join tbl_chart_of_accounts c on c.Account_ID = t.Account_ID 
                    left join tbl_accounting_jobs j on j.job_id = t.job_id
                    left join tbl_projects pr on pr.project_id = t.project_id
                where t.current_year_id = "' . $year_id . '" and t.is_actual = "' . $actual . '"
                group by t.Account_ID,t.branch_id,ifnull(t.job_id,0),ifnull(t.project_id,0),t.pos_customer_id having local_amount <> 0
                order by t.branch_id asc');
        $total_close_arr = array();
        while ($row = $this->db->assoc($query)) {
            $row['account_currency'] = empty($row['account_currency']) ? smc_session()['local_currency'] : $row['account_currency'];
            $local_curr_amount = $row['local_amount'];
            if ($row['account_currency'] == smc_session()['local_currency'])
                $acc_curr_amount = $local_curr_amount;
            else
                $acc_curr_amount = $row['acc_curr_amount'] + CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $row['account_currency'], $row['acc_curr_local_amount']);
            //
            $branch_id = $row['branch_id'];
            $branch_name = $branches_arr[$branch_id]['branch_name'];
            if (!isset($branches_arr[$branch_id]['is_init'])) {
                $branches_arr[$branch_id]['is_init'] = true;
                $branches_arr[$branch_id]['jv_old'] = JV::returnJV($actual, $year_id);
                $branches_arr[$branch_id]['jv_new'] = JV::returnJV($actual, $next_year_id);
            }
            $jv_old = $branches_arr[$branch_id]['jv_old'];
            $jv_new = $branches_arr[$branch_id]['jv_new'];
            //ex: 61,621,7 then /^61|^621|^7/
            $match_pattern = "/^" . str_replace(',', '|^', $close_acc_codes) . "/";
            $local_amount = abs($local_curr_amount);
            $trans_amount = abs($acc_curr_amount);
            //
            if ($trans_amount <= 0.0001 && $local_amount <= 0.0001)
                continue;
            //
            $current_rate = ($trans_amount == 0 ? 0 : ($local_amount / $trans_amount));
            $second_rate = "";
            //
            $is_close = preg_match($match_pattern, $row['Account_Code']);
            $trans_type = ((($is_close && $row['local_amount'] > 0) || (!$is_close && $row['local_amount'] < 0)) ? 'Credit' : 'Debit');
            $trans_type_inverse = ($trans_type == 'Debit' ? 'Credit' : 'Debit');
            $main_arr = ["JV_ID" => ($is_close ? $jv_old : $jv_new),
                "Transaction_Reference" => $ref,
                "Transaction_Date" => ($is_close ? $date_old : $date_new),
                "Transaction_Type" => $trans_type,
                "Transaction_Description" => ($is_close ? $desc_old : $desc_new),
                "main_type" => ($is_close ? "cly" : "opy"),
                "branch_id" => $branch_id,
                "job_id" => $row['job_id'],
                "job_name" => $row['job_name'],
                "project_id" => $row['project_id'],
                "project_name" => $row['project_name'],
                "branch_name" => $branch_name,
                "current_year_id" => ($is_close ? $year_id : $next_year_id),
                "main_id" => "0",
                "Transaction_Account" => $row['Account_ID'],
                "Account_Code" => $row['Account_Code'],
                "Account_Name" => $row['Account_Name'],
                "Currency_ID" => $row['account_currency'],
                "second_currency_rate" => $second_rate,
                "Logged_ID" => smc_session()['user_logged_id'],
                "pos_customer_id" => $row['pos_customer_id']
            ];
            if ($is_close) {
                if (empty($total_close_arr[$branch_id][$row['job_id']][$row['project_id']]))
                    $total_close_arr[$branch_id][$row['job_id']][$row['project_id']] = array('total' => 0, 'job_name' => $row['job_name'], 'project_name' => $row['project_name']);
                $total_close_arr[$branch_id][$row['job_id']][$row['project_id']]['total'] += $row['local_amount'];
            }
            //here we transfer amount in account currency and local currency, in case if user not submit exchage rate
            //here we may get account curr. amount in debit and local amount in crt. for that we must submit 2 transaction not one
            if (($local_curr_amount > 0 && $acc_curr_amount < 0) || ($local_curr_amount < 0 && $acc_curr_amount > 0)) {
                $transactions[] = array_merge($main_arr, [
                    "Transaction_Amount" => $trans_amount,
                    "local_amount" => 0,
                    "Current_Ex_Rate" => 0,
                    "Transaction_Type" => $trans_type_inverse
                ]);
                $transactions[] = array_merge($main_arr, [
                    "Transaction_Amount" => 0,
                    "local_amount" => $local_amount,
                    "Current_Ex_Rate" => CurrencyFactory::getLastExRate($row['account_currency'])
                ]);
            } else {  //normal case
                $transactions[] = array_merge($main_arr, [
                    "Transaction_Amount" => $trans_amount,
                    "local_amount" => $local_amount,
                    "Current_Ex_Rate" => $current_rate
                ]);
            }
        }
        //echo"<pre>";die(print_r($transactions));
        $loss_revenue_arr = array(
            'loss' => array('id' => smc_session()['account_setting']['loss_acc']
                , 'code' => JV::getAccountCodeByID(smc_session()['account_setting']['loss_acc'])
                , 'name' => JV::getAccountNameByID(smc_session()['account_setting']['loss_acc']))
            , 'revenue' => array('id' => smc_session()['account_setting']['revenue_acc']
                , 'code' => JV::getAccountCodeByID(smc_session()['account_setting']['revenue_acc'])
                , 'name' => JV::getAccountNameByID(smc_session()['account_setting']['revenue_acc']))
        );
        //
        foreach ($total_close_arr as $branch_id => $branch_trans_arr) {
            $branch_name = $branches_arr[$branch_id]['branch_name'];
            $jv_old = $branches_arr[$branch_id]['jv_old'];
            $jv_new = $branches_arr[$branch_id]['jv_new'];
            foreach ($branch_trans_arr as $job_id => $job_prjct_trans_arr) {
                foreach ($job_prjct_trans_arr as $prjct_id => $trans_row) {
                    $loss_revenue_indx = $trans_row['total'] > 0 ? 'loss' : 'revenue';
                    $account_id = $loss_revenue_arr[$loss_revenue_indx]['id'];
                    $trans_type = $trans_row['total'] > 0 ? 'Debit' : 'Credit';
                    $trans_row['total'] = abs($trans_row['total']);
                    $acc_name = $loss_revenue_arr[$loss_revenue_indx]['name'];
                    $acc_code = $loss_revenue_arr[$loss_revenue_indx]['code'];
                    $transactions[] = ["JV_ID" => $jv_old,
                        "Transaction_Reference" => $ref,
                        "Transaction_Account" => $account_id,
                        "Account_Name" => $acc_name,
                        "Account_Code" => $acc_code,
                        "Transaction_Type" => $trans_type,
                        "Transaction_Amount" => $trans_row['total'],
                        "Transaction_Date" => $date_old,
                        "Currency_ID" => $local_currency_id,
                        "Logged_ID" => smc_session()['user_logged_id'],
                        "Transaction_Description" => $desc_old,
                        "Current_Ex_Rate" => "",
                        "main_type" => "cly",
                        "branch_id" => $branch_id,
                        "branch_name" => $branch_name,
                        "job_id" => $job_id,
                        "job_name" => $trans_row['job_name'],
                        "project_id" => $prjct_id,
                        "project_name" => $trans_row['project_name'],
                        "current_year_id" => $year_id,
                        "main_id" => "0"
                    ];
                    $transactions[] = ["JV_ID" => $jv_new,
                        "Transaction_Reference" => $ref,
                        "Transaction_Account" => $account_id,
                        "Account_Name" => $acc_name,
                        "Account_Code" => $acc_code,
                        "Transaction_Type" => $trans_type,
                        "Transaction_Amount" => $trans_row['total'],
                        "Transaction_Date" => $date_new,
                        "Currency_ID" => $local_currency_id,
                        "Logged_ID" => smc_session()['user_logged_id'],
                        "Transaction_Description" => $desc_new,
                        "Current_Ex_Rate" => "",
                        "main_type" => "opy",
                        "branch_id" => $branch_id,
                        "branch_name" => $branch_name,
                        "job_id" => $job_id,
                        "job_name" => $trans_row['job_name'],
                        "project_id" => $prjct_id,
                        "project_name" => $trans_row['project_name'],
                        "current_year_id" => $next_year_id,
                        "main_id" => "0"
                    ];
                }
            }
        }
        //        }


        return $transactions;
    }

    public function close_year($actual, $next_year_id) {
        $this->db->query('START TRANSACTION');
        $transactions = $this->get_close_year_trans($actual, $next_year_id);
        $this->db->prepare_Stmt('delete from tbl_accounting_transactions 
                where (( main_type="cly" and current_year_id = "' . smc_session()['current_year_id'] . '" )
                    or ( main_type="opy" and current_year_id = "' . $next_year_id . '" ))
                    and is_actual = "' . $actual . '"');

        foreach ($transactions as $trans) {
            JV::addTransaction($trans, $actual);
        }
        $col = $actual ? 'is_act_closed' : 'is_closed';

        $this->db->prepare_Stmt("UPDATE tbl_common_current_year
                SET is_current = 0, " . $col . " = 1
                                    WHERE   
                                        current_year_id = ?", [&smc_session()['current_year_id']]);
        $this->db->prepare_Stmt("UPDATE tbl_common_current_year
                SET is_current = 1
                                    WHERE   
                                        current_year_id = ?  ", [&$next_year_id]);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return $error;
    }

    public function get_financial_years($actual = null) {
        $cond = ' ';
        if (!is_null($actual)) {
            $cond .= $actual == 1 ? ' and is_act_closed <> 1 ' : ' and is_closed <> 1 ';
        }
        $data = array();
        $query = $this->db->query('select * from tbl_common_current_year where current_year_id <> "' . smc_session()['current_year_id'] . '" ' . $cond);
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    public function open_financial_year($year_id, $actual) {
        $this->db->query('START TRANSACTION');
        $this->db->prepare_Stmt('delete from tbl_accounting_transactions 
                where main_type="cly" and current_year_id = "' . $year_id . '" and is_actual = "' . $actual . '"');
        //
        $col_name = $actual ? 'is_act_closed' : 'is_closed';
        $this->db->prepare_Stmt('update tbl_common_current_year set ' . $col_name . ' = 0 
                where current_year_id = "' . $year_id . '"');
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return array_unique($error);
    }

    public function customer_supplier_vat_report($type, $from_date, $to_date, $is_actual,$search_branch_id) {
        $data = array();
        $acc_ids = array();
        $sub_type = $type == 'cust' ? '"vat"' : '"exp_vat","fa_vat","pur_vat"';
        $query_acc = $this->db->query('select Account_ID,Account_Code,Account_Name,main_id
             from tbl_chart_of_accounts 
             where main_type="' . $type . '" and sub_type in (' . $sub_type . ')');
        while ($row_acc = $this->db->assoc($query_acc)) {
            $acc_ids[$row_acc['Account_ID']] = $row_acc;
        }
        $cond = '';
        if($this->permissions->hasPermission('Branches')){
            $cond .= !empty($search_branch_id) ? ' and branch_id ="' . ($search_branch_id) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        $total_vat = 0;
      //  $second_currency = 0;
        $query = $this->db->query('select Account_ID,sum(if(Transaction_Type = "Credit",-1,1)*local_amount) as amount
             from tbl_accounting_transactions where Account_ID in(' . implode(',', array_keys($acc_ids)) . ')
                 and Transaction_Date between "' . $from_date . '" and "' . $to_date . '"
                     and is_actual = "' . $is_actual . '" '.$cond.'
                 group by Account_ID');
        while ($row = $this->db->assoc($query)) {
            $row['amount'] = CommonFunctions::public_round_number($row['amount']); 
            $total_vat += $row['amount'];
          //  $second_currency += $row['amount'] * $row['second_currency_rate'];
            if (empty($data[$acc_ids[$row['Account_ID']]['main_id']])) {
                $data[$acc_ids[$row['Account_ID']]['main_id']]['account_code'] = $acc_ids[$row['Account_ID']]['Account_Code'];
                $data[$acc_ids[$row['Account_ID']]['main_id']]['account_name'] = $acc_ids[$row['Account_ID']]['Account_Name'];
                $data[$acc_ids[$row['Account_ID']]['main_id']]['amount'] = $row['amount'];                
            } else {
                $data[$acc_ids[$row['Account_ID']]['main_id']]['amount'] += $row['amount'];
            }
            unset($data[$acc_ids[$row['Account_ID']]['main_id']]['Account_ID']);
        }
        $result_arr = array();
        foreach ($data as $row) {
            $result_arr[] = array_values($row);
        }
        //     echo"<pre>";
        //     die(print_r($result_arr));
        return ['data' => $data, 'total' => $total_vat];
    }

    //    public function build_dynamic_report($report_id, $date_from, $date_to, $currency_id, $is_actual, $type) {
    //        $data = array('details' => array(), 'total' => 0);
    //        $report_dtls = array();
    //        $total = 0;
    //        $total_credit = 0;
    //        $total_debit = 0;
    //        $query = $this->db->query('select * from tbl_dynamic_report_template_details d
    //                join tbl_chart_of_accounts a on a.Account_ID = d.account_id
    //                join tbl_dynamic_report_template_sub s on s.sub_id = d.sub_id
    //                where s.report_id="' . $report_id . '" order by s.sub_id,d.detail_id');
    //        while ($row = $this->db->assoc($query)) {
    //            $report_dtls[$row['account_id']] = $row;
    //        }
    //        $sub_total = 0;
    //        $sub_credit = 0;
    //        $sub_debit = 0;
    //        $current_sub_id = 0;
    //        $sub_title = '';
    //        $counter = 0;
    //        foreach ($report_dtls as $acc_id => $row) {
    //            if ($current_sub_id != 0 && $current_sub_id != $row['sub_id'] && $type != 2) {
    //                $data['details'][] = array('--', $sub_title,
    //                    CommonFunctions::formatNumber($sub_debit),
    //                    CommonFunctions::formatNumber($sub_credit), '',
    //                    CommonFunctions::formatNumber($sub_total), 'class' => 'bold');
    //                $sub_total = 0;
    //                $sub_credit = 0;
    //                $sub_debit = 0;
    //                $current_sub_id = 0;
    //                $sub_title = '';
    //            }
    //            $parents_arr = array();
    //            $acc_arr = array();
    //            $acc_arr[$acc_id] = array('Parent_ID' => 0, 'Account_ID' => $acc_id, 'Account_Code' => $row['Account_Code'],
    //                'Account_Name' => $row['Account_Name']);
    //            $this->get_coa_tree($acc_id, $parents_arr, $acc_arr, []);
    //            //            echo "<pre>";
    //            //            echo print_r($acc_arr);
    //            if ($row['with_child'] == 1) {
    //                foreach ($acc_arr as $child_acc_id => $child_row) {
    //                    if ($child_acc_id != $acc_id) {
    //                        $acc_arr[$child_acc_id] = array('Parent_ID' => $child_row['Parent_ID'], 'Account_ID' => $child_acc_id, 'Account_Code' => $child_row['Account_Code'],
    //                            'Account_Name' => $child_row['Account_Name']);
    //                        $options = ["Account_ID" => $child_acc_id, "Currency_ID" => $currency_id,
    //                            "From_Date" => $date_from, "To_Date" => $date_to, "Opening_Balance" => 0, "Is_Actual" => $is_actual];
    //                        $balance = $this->returnExactBalanceByID($options);
    //                        $balance['Balance'] = $row['operation'] == '-' ? $balance['Balance'] * -1 : $balance['Balance'];
    //                        if ($type != 1) {
    //                            $account_code = JV::getAccountCodeByID($child_acc_id);
    //                            $account_name = JV::getAccountNameByID($child_acc_id);
    //                            $data['details'][] = array($account_code, $account_name,
    //                                CommonFunctions::formatNumber($balance['Debits']), CommonFunctions::formatNumber($balance['Credits']), $row['operation'],
    //                                CommonFunctions::formatNumber($balance['Balance']));
    //                        }
    //                        $sub_total+=$balance['Balance'];
    //                        $sub_debit+=$balance['Debits'];
    //                        $sub_credit+=$balance['Credits'];
    //                        $current_sub_id = $row['sub_id'];
    //                        $sub_title = $row['sub_title'];
    //                        $total+=$balance['Balance'];
    //                        $total_credit+=$balance['Credits'];
    //                        $total_debit+=$balance['Debits'];
    //                    }
    //                }
    //            } else {
    //                $options = ["Account_ID" => implode(',', array_keys($acc_arr)), "Currency_ID" => $currency_id,
    //                    "From_Date" => $date_from, "To_Date" => $date_to, "Opening_Balance" => 0, "Is_Actual" => $is_actual];
    //                $balance = $this->returnExactBalanceByID($options);
    //
    //                $balance['Balance'] = $row['operation'] == '-' ? $balance['Balance'] * -1 : $balance['Balance'];
    //                if ($type != 1) {
    //                    $data['details'][] = array($row['Account_Code'], $row['Account_Name'],
    //                        CommonFunctions::formatNumber($balance['Debits']), CommonFunctions::formatNumber($balance['Credits']), $row['operation'],
    //                        CommonFunctions::formatNumber($balance['Balance']));
    //                }
    //
    //                $sub_total+=$balance['Balance'];
    //                $sub_debit+=$balance['Debits'];
    //                $sub_credit+=$balance['Credits'];
    //                $current_sub_id = $row['sub_id'];
    //                $sub_title = $row['sub_title'];
    //                $total+=$balance['Balance'];
    //                $total_credit+=$balance['Credits'];
    //                $total_debit+=$balance['Debits'];
    //            }
    //            $counter++;
    //            if (count($report_dtls) == $counter && $type != 2) {
    //                //                if ($current_sub_id != 0 && $current_sub_id != $row['sub_id']) {
    //                $data['details'][] = array('--', $row['sub_title'],
    //                    CommonFunctions::formatNumber($sub_debit), CommonFunctions::formatNumber($sub_credit), '',
    //                    CommonFunctions::formatNumber($sub_total), 'class' => 'bold');
    //
    //                //                }
    //            }
    //        }
    //        $data['total'] = $total;
    //        $data['total_credit'] = $total_credit;
    //        $data['total_debit'] = $total_debit;
    //        //        echo"<pre>";
    //        //        die(print_r($data));
    //        return $data;
    //    }

    public function project_trial_balance($options) {

        $num_digits = $options['digits'];
        $group_num = $options['Grouping'];
        $from_date = $options['From_Date'];
        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 0;
        $with_close = !empty($options['with_close']) ? $options['with_close'] : 0;
        $back_up = $options['Is_Actual'] == 1 ? true : false;
        $len_zeros_nines = $num_digits - $group_num;
        $nines = str_repeat("9", $len_zeros_nines);
        //        echo $nines.'==';die();

        $start_date = $back_up ? smc_session()['start_date_act'] : smc_session()['start_date']; //used as start for opening balance
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day')); // used as end of opening balance

        $parents_arr = array();
        $acc_arr = array();
        $this->get_project_tree(0, $parents_arr, $acc_arr, $options);
        //        echo"<pre>";
        //        die(print_r($parents_arr));
        $data = array();
        foreach ($parents_arr[0] as $project_id) {
            $min = $acc_arr[$project_id]['project_code']; // min acc to retreive e.g. ($i=1 => 1)
            $max = $acc_arr[$project_id]['project_code'] . $nines; // max acc to retreive e.g. ($i=1 = >19999..)
            $options['code'] = $min;
            $options['left'] = true;
            $options['is_arr'] = true;
            $options['index_acc_id'] = true;
            $options['cond'] = " and length(project_code) <= '" . strlen($max) . "' ";
            //
            $open_balance_3_arr = array();
            $close_balance_3_arr = array();
            $prev_balance_3_arr = array();
            $current_array_arr = array();
            if ($opening_balance == 1) {
                $options_opening = $options;
                $options_opening['opening_only'] = 1;
                $options_opening['close_only'] = 0;
                $open_balance_3_arr = self::returnProjectBalance($options_opening);
            }
            if ($with_close == 1) {
                $options_close = $options;
                $options_close['opening_only'] = 0;
                $options_close['close_only'] = 1;
                $close_balance_3_arr = self::returnProjectBalance($options_close);
            }
            if ($start_date != $from_date) {

                $options_prev = $options;
                $options_prev['From_Date'] = empty($options_prev['From_Date']) ? '' : $start_date;
                $options_prev['To_Date'] = empty($options_prev['To_Date']) ? '' : $day_before;
                $options_prev['Opening_Balance'] = 1;
                $options_prev['opening_only'] = 0;
                $prev_balance_3_arr = self::returnProjectBalance($options_prev);
            }
            //            echo "<pre>";
            //            die(print_r($prev_balance_3_arr));
            $current_options = $options;
            $current_options['with_close'] = 0;
            $current_options['Opening_Balance'] = 0;
            $current_array_arr = self::returnProjectBalance($current_options);
            //            echo"<pre>";print_r($current_array_arr);
            $this->build_project_trial_arr($data, $project_id, $open_balance_3_arr, $prev_balance_3_arr, $current_array_arr, $close_balance_3_arr, $parents_arr, $acc_arr, $options);
        }

        return $data;
    }

    public function get_project_tree($parent_ids, &$parents_arr, &$acc_arr, $options) {
        $new_parent_ids = array();
        $cond = ' ';
        if (!empty($options['from_account']))
            $cond .= ' and left(project_code,length(LEAST(project_code,"' . $options['from_account'] . '"))) >= left("' . $options['from_account'] . '",length(LEAST(project_code,"' . $options['from_account'] . '"))) ';
        if (!empty($options['to_account']))
            $cond .= ' and left(project_code,length(LEAST(project_code,"' . $options['to_account'] . '"))) <= left("' . $options['to_account'] . '",length(LEAST(project_code,"' . $options['to_account'] . '"))) ';
        $query = $this->db->query("select parent_id,project_id,project_code,project_name
                from tbl_projects where parent_id in ({$parent_ids}) " . $cond);
        while ($row = $this->db->assoc($query)) {
            $acc_arr[$row['project_id']] = $row;
            if (!isset($parents_arr[$row['parent_id']]))
                $parents_arr[$row['parent_id']] = array();
            $new_parent_ids[$row['project_id']] = $row['project_id'];
            $parents_arr[$row['parent_id']][] = $row['project_id'];
        }
        if (!empty($new_parent_ids))
            $this->get_project_tree(implode(',', $new_parent_ids), $parents_arr, $acc_arr, $options);
    }

    public function build_project_trial_arr(&$data, $project_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $acc_total = $this->get_project_group_totals($project_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
        //       echo $project_id.'==<br>';
        //       echo"<pre>";
        //       print_r($acc_arr);
        if (!empty($acc_total)) {
            $data[] = $acc_total;
        }
        if (!empty($parents_arr[$project_id])) {
            foreach ($parents_arr[$project_id] as $child_id) {

                $this->build_project_trial_arr($data, $child_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
            }
        }
    }

    public function get_project_group_totals($project_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $open_balance = $prev_balance = $close_balance = $debits = $credits = $debits_local = $credits_local = 0;
        $debits_second = $credits_second = $current_balance = $current_balance_local = $current_balance_second = $overall_balance = 0;
        $projects = array($project_id);
        $this->get_acc_childs($project_id, $projects, $parents_arr);
        $is_parent = false;
        if (!empty($parents_arr[$project_id]))
            $is_parent = true;
        foreach ($projects as $current_id) {
            if (!empty($current_arr[$current_id])) {
                $current_balance += $current_arr[$current_id]['Balance'];
                $overall_balance += $current_arr[$current_id]['Balance'];
                $debits += $current_arr[$current_id]['Debits'];
                $credits += $current_arr[$current_id]['Credits'];
                $debits_local += $current_arr[$current_id]['local_debits'];
                $credits_local += $current_arr[$current_id]['local_credits'];
                $debits_second += $current_arr[$current_id]['second_debits'];
                $credits_second += $current_arr[$current_id]['second_credits'];
                $current_balance_local += $current_arr[$current_id]['local_balance'];
                $current_balance_second += $current_arr[$current_id]['second_balance'];
            }
            if (!empty($open_arr[$current_id])) {
                $open_balance += $open_arr[$current_id]['Balance'];
                $overall_balance += $open_arr[$current_id]['Balance'];
            }
            if (!empty($prev_arr[$current_id])) {
                $prev_balance += $prev_arr[$current_id]['Balance'];
                $overall_balance += $prev_arr[$current_id]['Balance'];
            }
            if (!empty($close_arr[$current_id])) {
                $close_balance += $close_arr[$current_id]['Balance'];
                $overall_balance += $close_arr[$current_id]['Balance'];
            }
        }
        if ($is_parent && mb_strlen($acc_arr[$project_id]['project_code']) > $options['Grouping'])
            return null;
        if (mb_strlen($acc_arr[$project_id]['project_code']) > $options['digits'])
            return null;
        if (($is_parent && (abs(round($credits, 3)) > 0 || abs(round($debits, 3)) > 0)) || (abs(round($overall_balance, 3)) > 0) || ($options['Active'] == 0 && (((abs(round($credits, 3)) > 0) || (abs(round($debits, 3)) > 0))))
        ) {
            return array(
                "Name" => $acc_arr[$project_id]['project_name'], "Code" => $acc_arr[$project_id]['project_code'],
                "project_id" => $project_id,
                'open_balance' => $open_balance, 'close_balance' => $close_balance, 'prev_balance' => $prev_balance,
                "Debits" => $debits, "Credits" => $credits, "local_debits" => $debits_local, "local_credits" => $credits_local,
                "second_debits" => $debits_second, "second_credits" => $credits_second, "Balance" => $current_balance,
                "local_balance" => $current_balance_local, "second_balance" => $current_balance_second, "overall_balance" => $overall_balance,
                "is_parent" => $is_parent
            );
        }
        return null;
    }

    public function returnProjectBalance($options) {
        //        echo"<pre>";
        //        die(print_r($options));
        $condition = ' ';

        if (!empty($options['left'])) {
            $condition .= ' AND LEFT(project_code,' . strlen($options['code']) . ') = "' . $options['code'] . '"';
        } else {
            $condition .= ' AND project_code IN ("' . $options['code'] . '")';
        }
        $acc_id_arr = array();
        $account_ids = '';
        $query = $this->db->query('SELECT  project_id,project_code
                                            FROM  tbl_projects  
                                            WHERE true ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['project_id']] = $row['project_code'];
            $account_ids .= (empty($account_ids) ? '' : ',') . $row['project_id'];
        }
        $options['project_id'] = $account_ids;


        $condition = '';

        if (!empty($options['cond'])) {
            $condition .= $options['cond'];
        }
        if (!empty($options['project_id']))
            $condition .= ' AND t.project_id  in (' . $options['project_id'] . ') ';

        $currency_id = empty($options['Currency_ID']) ? CurrencyFactory::getDefaultCurrency() : $options['Currency_ID'];


        if (!empty($options['opening_only']) && $options['opening_only'] == 1)
            $condition .= '  and t.main_type="opy" ';
        elseif (!empty($options['Opening_Balance']) || $options['Opening_Balance'] == 0)
            $condition .= ' and t.main_type <> "opy" ';

        if (!empty($options['Opening_Balance'])) {
            if (!empty($options['From_Date']) && !empty($options['due_date_from']))
                $condition .= 'and (t.Transaction_Date < "' . $options['To_Date'] . '" or t.due_date < "' . $options['due_date_from'] . '") ';
            else {
                if (!empty($options['From_Date']))
                    $condition .= ' and t.Transaction_Date < "' . $options['To_Date'] . '"';
                if (!empty($options['due_date_from']))
                    $condition .= '  and t.due_date < "' . $options['due_date_from'] . '"';
            }
        }
        if (isset($options['close_only'])) {
            if ($options['close_only'] == 1)
                $condition .= '  and t.main_type="cly" ';
        }
        elseif (isset($options['with_close'])) {
            if ($options['with_close'] == 0)
                $condition .= ' and t.main_type <> "cly" ';
        }
        //
        if (!empty($options['From_Date']) && !empty($options['To_Date']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.Transaction_Date >= "' . $options['From_Date'] . '" 
                                and t.Transaction_Date <= "' . $options['To_Date'] . '" ';
        if (!empty($options['due_date_from']) && !empty($options['due_date_to']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.due_date >= "' . $options['due_date_from'] . '" 
                                and t.due_date <= "' . $options['due_date_to'] . '" ';
        if (isset($options['Is_Actual']) && $options['Is_Actual'] == 0) {
            $condition .= ' and t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '" ';
        } elseif (isset($options['Actual_Only']) && $options['Actual_Only']) {
            $condition .= ' and t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '" ';
        } else
            $condition .= ' and ((t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '") 
                    or ( t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '")) ';

        if (!empty($options['trans_type']) && $options['trans_type'] != '') {
            $condition .= ' and t.main_type in ("' . implode('","', $options['trans_type']) . '") ';
        }
        if (!empty($options['debit_credit_type']) && $options['debit_credit_type'] != 'All') {
            $condition .= ' and t.Transaction_Type = "' . $options['debit_credit_type'] . '" ';
        }
        //        if (!empty($options['from_jv'])) {
        //            $condition .= ' and t.JV_ID >= "' . $options['from_jv'] . '" ';
        //        }
        //        if (!empty($options['to_jv'])) {
        //            $condition .= ' and  t.JV_ID <= "' . $options['to_jv'] . '"';
        //        }
        //        if (!empty($options['from_account'])) {
        //            $condition .= ' and left(t.Transaction_Account,' . strlen($options['from_account']) . ') >= "' . $options['from_account'] . '" ';
        //        }
        //        if (!empty($options['to_account'])) {
        //            $condition .= ' and  left(t.Transaction_Account,' . strlen($options['from_account']) . ') <= "' . $options['to_account'] . '"';
        //        }
        if (!empty($options['from_amount'])) {
            $condition .= ' and t.Transaction_Amount >= "' . $options['from_amount'] . '" ';
        }
        if (!empty($options['to_amount'])) {
            $condition .= ' and  t.Transaction_Amount <= "' . $options['to_amount'] . '"';
        }
        //        if (!empty($options['project_ids'])) {
        //            $condition .=' and t.project_id in (' . $options['project_ids'] . ')';
        //        }
        //        if (!empty($options['multi_accounts'])) {
        //            $condition .=' and t.Account_ID in (' . $options['multi_accounts'] . ')';
        //        }
        //        if (!empty($options['family_acc'])) {
        //            $family_accs = CommonACC::get_family_accs_by_id($options['family_acc']);
        //            $condition .=' and t.Account_ID in (' . $family_accs . ')';
        //        }
        //        if (!empty($options['ref_type'])) {
        //            $condition .=' and t.subtype in ("' . implode('","', explode(",", $options['ref_type'])) . '") and t.main_type="mjv" ';
        //        }
        if (!empty($options['trans_currency'])) {
            $condition .= ' and t.Currency_ID ="' . $options['trans_currency'] . '"';
        }

        $acc_arr = array();
        $query = $this->db->query('SELECT 
                                                t.Transaction_Reference,
                                                t.Currency_ID,
                                                t.Account_ID,
                                                t.project_id,
                                                t.Transaction_Amount,
                                                t.Current_Ex_Rate,
                                                t.second_currency_rate,
                                                t.Exchange_Rate_ID,
                                                t.Transaction_Type,
                                                t.local_amount,
                                                (t.Transaction_Amount*t.second_currency_rate) as second_amount,
                                                t.main_type
                                            FROM tbl_accounting_transactions t  join tbl_projects j on j.project_id = t.project_id
                                            WHERE 1=1
                                         ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $temp_amount = 0.0;
            if ($currency_id == smc_session()['local_currency']) {
                $temp_amount = $row['local_amount'];
            } else {
                $temp_amount = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
            }
            //
            $indx = $row['project_id'];
            if (!isset($acc_arr[$indx])) {
                $acc_arr[$indx] = array(
                    "Balance" => 0,
                    "Debits" => 0,
                    "Credits" => 0,
                    "local_debits" => 0,
                    "local_credits" => 0,
                    "second_debits" => 0,
                    "second_credits" => 0,
                    "local_balance" => 0,
                    "second_balance" => 0
                );
            }
            //
            if ($row['Transaction_Type'] == 'Debit') {
                $acc_arr[$indx]["Debits"] += $temp_amount;
                $acc_arr[$indx]["local_debits"] += $row['local_amount'];
                $acc_arr[$indx]["second_debits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] += $temp_amount;
                $acc_arr[$indx]["local_balance"] += $row['local_amount'];
                $acc_arr[$indx]["second_balance"] += $row['second_amount'];
            } elseif ($row['Transaction_Type'] == 'Credit') {
                $acc_arr[$indx]["Credits"] += $temp_amount;
                $acc_arr[$indx]["local_credits"] += $row['local_amount'];
                $acc_arr[$indx]["second_credits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] -= $temp_amount;
                $acc_arr[$indx]["local_balance"] -= $row['local_amount'];
                $acc_arr[$indx]["second_balance"] -= $row['second_amount'];
            }
        }
        return $acc_arr;
    }

    public function get_block_details($block_id, &$data, &$accs_arr, &$stock_arr) {
        $block_det_arr = array();
        //           echo('select d.*,
        //            if(d.detail_sub_title="",if(d.account_id=0,s.sub_title,concat_ws(" - ",a.Account_Code,a.Account_Name)),d.detail_sub_title) as title
        //            from tbl_dynamic_report_template_details d
        //            left join tbl_dynamic_report_template_sub s on s.sub_id = d.detail_sub_id
        //            left join tbl_chart_of_accounts a on a.Account_ID = d.account_id
        //            where d.sub_id = "' . $block_id . '" order by d.detail_id<br>');
        $query = $this->db->query('select d.*,
            if(d.detail_sub_title="",if(d.account_id=0,s.sub_title,concat_ws(" - ",a.Account_Code,a.Account_Name)),d.detail_sub_title) as title
            from tbl_dynamic_report_template_details d
            left join tbl_dynamic_report_template_sub s on s.sub_id = d.detail_sub_id
            left join tbl_chart_of_accounts a on a.Account_ID = d.account_id
            where d.sub_id = "' . $block_id . '" order by d.detail_id');
        //echo $block_id . '===';
        while ($row = $this->db->assoc($query)) {
            //block
            if (!empty($row['detail_sub_id']))
                $row['details'] = $this->get_block_details($row['detail_sub_id'], $data, $accs_arr, $stock_arr);
            //stock
            elseif ($row['sub_type'] == 3) {
                $stock_arr[$row['detail_id']] = 0;
            }
            //account
            elseif (!empty($row['account_id'])) {
                $tmp_blnc_optns = array('acc_id' => $row['account_id'], 'trans_types' => $row['trans_types']);
                $tmp_blnc_indx = sha1(json_encode($tmp_blnc_optns));
                $accs_arr['balances'][$row['account_id']][$tmp_blnc_indx] = array();
                $row['tmp_blnc_indx'] = $tmp_blnc_indx;
                $tmp_blnc_optns['tmp_blnc_indx'] = $tmp_blnc_indx;
                $accs_arr['others'][$row['account_id']][$tmp_blnc_indx] = $tmp_blnc_optns;
                if ($row['with_child'])
                    $accs_arr['child'][$row['account_id']] = array();
            }
            $block_det_arr[] = $row;
        }
        return $block_det_arr;
    }

    public function get_block_balances($row, &$last_data, $accs_arr, $stock_arr, $with_child = true, $level = 0, $is_hide_unmoved = true, $is_inverse_sort = true) {
        $space = "&nbsp;&nbsp;&nbsp;";
        $title = str_repeat($space, $level) . (empty($row['sub_title']) ? $row['title'] : $row['sub_title']);
        $temp_row = ['name' => $title, 'total_debit' => 0, 'total_credit' => 0, 'operation' => '+', 'balance' => 0];
        //here for totals row to get it's balance we loop on the children but herre we reserver index for it at first to be at top
        $last_row_indx = null;
        if ($with_child && $is_inverse_sort) {
            $last_data[] = array();
            $last_row_indx = count($last_data) - 1;
        }
        if (!empty($row['operation']))
            $temp_row['operation'] = $row['operation'];
        //block case
        if (!empty($row['details'])) {
            foreach ($row['details'] as $child_row) {
                //block case
                if (!empty($child_row['details'])) {
                    $balance_row = $this->get_block_balances($child_row, $last_data, $accs_arr, $stock_arr, ($with_child && $row['with_child']), ($level + 1), $is_hide_unmoved);
                    $balance = $balance_row['balance'];
                    $total_debit = $balance_row['total_debit'];
                    $total_credit = $balance_row['total_credit'];
                }
                //stock case
                elseif ($child_row['sub_type'] == 3) {
                    $balance = $stock_arr[$child_row['detail_id']];
                    $total_debit = $child_row['operation'] == '-' ? 0 : $balance;
                    $total_credit = $child_row['operation'] == '-' ? $balance : 0;
                    $balance = $balance * ($child_row['operation'] == '-' ? -1 : 1);
                    if ($with_child && $row['with_child'])
                        $last_data[] = array(str_repeat($space, ($level + 1)) . $child_row['title'],
                            CommonFunctions::formatNumber($total_debit),
                            CommonFunctions::formatNumber($total_credit), $child_row['operation'],
                            CommonFunctions::formatNumber($balance));
                }
                //account case
                else {
                    $tmp_blnc_indx = $child_row['tmp_blnc_indx'];
                    $balance_row = $accs_arr['balances'][$child_row['account_id']][$tmp_blnc_indx];
                    $balance = $balance_row['Balance'] * ($child_row['operation'] == '-' ? -1 : 1);
                    $total_debit = $balance_row['Debits'];
                    $total_credit = $balance_row['Credits'];
                    if ($is_hide_unmoved && $total_debit == 0 && $total_credit == 0)
                        continue;
                    $child_row_indx = null;
                    if ($with_child && $row['with_child']) {
                        if ($is_inverse_sort) {
                            $last_data[] = array();
                            $child_row_indx = count($last_data) - 1;
                        }
                        if ($child_row['with_child']) {
                            foreach ($accs_arr['child'][$child_row['account_id']] as $child_acc) {
                                $child_balance_row = $accs_arr['balances'][$child_acc['Account_ID']][$tmp_blnc_indx];
                                $child_balance = $child_balance_row['Balance'] * ($child_row['operation'] == '-' ? -1 : 1);
                                if ($is_hide_unmoved && $child_balance_row['Debits'] == 0 && $child_balance_row['Credits'] == 0)
                                    continue;
                                $last_data[] = array(str_repeat($space, ($level + 2)) . $child_acc['Account_Name'],
                                    CommonFunctions::formatNumber($child_balance_row['Debits']),
                                    CommonFunctions::formatNumber($child_balance_row['Credits']), $child_row['operation'],
                                    CommonFunctions::formatNumber($child_balance));
                            }
                        }
                        if (is_null($child_row_indx))
                            $child_row_indx = count($last_data);
                        $last_data[$child_row_indx] = array(str_repeat($space, ($level + 1)) . $child_row['title'],
                            CommonFunctions::formatNumber($total_debit),
                            CommonFunctions::formatNumber($total_credit), $child_row['operation'],
                            CommonFunctions::formatNumber($balance));
                    }
                }
                $balance_oprtn = ($temp_row['operation'] == '-' ? -1 : 1);
                $temp_row['balance'] += ($balance * $balance_oprtn);
                $temp_row['total_debit'] += $total_debit;
                $temp_row['total_credit'] += $total_credit;
            }
        }
        //
        $rtrn_row = $temp_row;  //need it before number format
        if ($with_child) {
            $temp_row['balance'] = CommonFunctions::formatNumber($temp_row['balance']);
            $temp_row['total_debit'] = CommonFunctions::formatNumber($temp_row['total_debit']);
            $temp_row['total_credit'] = CommonFunctions::formatNumber($temp_row['total_credit']);
            $last_row = array_values($temp_row);
            if ($level == 0)
                $last_row['class'] = 'bold';
            if (is_null($last_row_indx)) //isset not empty since maybe zero
                $last_row_indx = count($last_data);
            $last_data[$last_row_indx] = $last_row;
        }
        return $rtrn_row;
    }

    public function build_dynamic_report($opts) {
        //        echo"<pre>";die(print_r($options));
        $report_id = $opts['report_id'];
        $date_from = $opts['from_date'];
        $date_to = $opts['to_date'];
        $currency_id = $opts['currency_id'];
        $is_actual = $opts['is_actual'];
        $type = $opts['type'];
        $actual_only = $opts['actual_only'];
        $data = array('details' => array(), 'total' => 0);
        $report_dtls = array();
        $total = 0;
        $total_credit = 0;
        $total_debit = 0;
        $is_hide_unmoved = true;
        $query = $this->db->query('select s.*,r.is_hide_unmoved from tbl_dynamic_report_template_sub s 
            join tbl_dynamic_report_template r using(report_id)
                where s.report_id="' . $report_id . '" order by s.sub_id');
        $accs_arr = array('balances' => array(), 'child' => array(), 'others' => array());
        $stock_arr = array();
        while ($row = $this->db->assoc($query)) {
            $is_hide_unmoved = $row['is_hide_unmoved'] == 1 ? true : false;
            $row_data = array();
            $row['details'] = $this->get_block_details($row['sub_id'], $row_data, $accs_arr, $stock_arr);
            $report_dtls[$row['sub_id']] = $row;
        }
        //get stock data
        //        $i = 0;
        //        foreach ($stock_arr as &$stock_balance)
        //            $stock_balance = ( ++$i * 100);
        if (!empty($opts['stock_arr'])) {
            foreach ($opts['stock_arr'] as $stock_row) {
                $stock_value = 0;
                if ($stock_row['method'] == "acc") {
                    $acc_id = smc_session()['account_setting'][$stock_row['stock_period'] == 'begin' ? 'begining_stock_account_id' : 'end_stock_account_id'];
                    $opts['code'] = JV::getAccountCodeByID($acc_id);
                    $opts['Currency_ID'] = $opts['currency_id'];
                    $stock_value = self::returnExactBalance($opts)['Balance'];
                    //            $stock_value = ( self::getExactBalance($keys, $acc_code, strlen($acc_code))['Balance'] );
                } else if ($stock_row['method'] === 'manual') {
                    $stock_value = $stock_row['stock_value'];
                } else {
                    //                    echo'heree';
                    $product = new Product();
                    $stock_value = ($product->costing_report(['date' => $opts['to_date'], 'type' => $stock_row['method'], 'type_id' => $stock_row['stock_type']])['total']);
                    $stock_value = CurrencyFactory::returnExchangedValueBetweenTwoCurrencies(smc_session()['local_currency'], $opts['currency_id'], $stock_value);
                    //                               echo $stock_value.'==='.smc_session()['local_currency'].'==='.$options['currency_id'];
                }
                $stock_arr[$stock_row['detail_id']] = $stock_value;
            }
        }
        //        echo"<pre>";die(print_r($stock_arr));
        //get accounts balances
        foreach ($accs_arr['balances'] as $account_id => $acc_balances_arr) {
            foreach ($acc_balances_arr as $tmp_blnc_indx => $tmp_balance_row) {
                $balance_row = &$accs_arr['balances'][$account_id][$tmp_blnc_indx];
                $parents_arr = array();
                $child_acc_arr = array();
                $this->get_coa_tree($account_id, $parents_arr, $child_acc_arr, []);
                $acc_trans_types = $accs_arr['others'][$account_id][$tmp_blnc_indx]['trans_types'];
                $acc_trans_types = !empty($acc_trans_types) ? explode(',', $acc_trans_types) : array();
                $is_child_balance = false;
                //if there is children need to show all children accounts
                if (isset($accs_arr['child'][$account_id])) {
                    $accs_arr['child'][$account_id] = $child_acc_arr;
                    //if with child but no children for that account then get 
                    if (!empty($child_acc_arr)) {
                        $is_child_balance = true;
                        foreach ($child_acc_arr as $child_acc_id => $child_row) {
                            //here we need concat code with name
                            $accs_arr['child'][$account_id][$child_acc_id]['Account_Name'] = $child_row['Account_Code'] . ' - ' . $child_row['Account_Name'];
                            $child_balance_row = &$accs_arr['balances'][$child_acc_id][$tmp_blnc_indx];
                            if (empty($child_balance_row)) {
                                $options = ["Account_ID" => $child_acc_id, "Currency_ID" => $currency_id, "trans_type" => $acc_trans_types,
                                    "From_Date" => $date_from, "To_Date" => $date_to, "Opening_Balance" => 0, "Is_Actual" => $is_actual, "Actual_Only" => $actual_only];
                                $child_balance_row = $this->returnExactBalanceByID($options);
                            }
                            //fill current parent balance from children balances
                            if (empty($balance_row))
                                $balance_row = $accs_arr['balances'][$child_acc_id][$tmp_blnc_indx];
                            else
                                foreach ($child_balance_row as $key => $val)
                                    $balance_row[$key] += $val;
                        }
                    }
                }
                if (!$is_child_balance) {
                    $child_acc_arr[$account_id] = array('Parent_ID' => 0, 'Account_ID' => $account_id, 'Account_Name' => JV::getAccountNameByID($account_id));
                    $options = ["Account_ID" => implode(',', array_keys($child_acc_arr)), "Currency_ID" => $currency_id, "trans_type" => $acc_trans_types,
                        "From_Date" => $date_from, "To_Date" => $date_to, "Opening_Balance" => 0, "Is_Actual" => $is_actual, "Actual_Only" => $actual_only];
                    $balance_row = $this->returnExactBalanceByID($options);
                }
                $balance_row['Account_Name'] = JV::getAccountNameByID($account_id);
            }
        }
        $last_data = array();
        foreach ($report_dtls as $sub_id => $row) {
            if (!empty($row['details'])) {
                $row['with_child'] = true;
                $this->get_block_balances($row, $last_data, $accs_arr, $stock_arr, true, 0, $is_hide_unmoved, $opts['inverse_report']);
            }
        }
        $data['details'] = $last_data;
        $data['total'] = $total;
        $data['total_credit'] = $total_credit;
        $data['total_debit'] = $total_debit;
        //        print_r($last_data);
        return $last_data;
    }

    public function aging_report() {
        $cond_inv = '';
        $cond_trans = '';
        $cond_common = '';
        $cond_note = '';
        if (empty($this->info['is_actual'])) {
            $cond_common .= ' and is_actual=0 ';
        }
        $to_date = date("Y-m-d");
        if (!empty($this->info['date']))
            $to_date = $this->info['date'];
        $is_local = 1;
        if (isset($this->info['currency_id']))
            $is_local = $this->info['currency_id'];
        $is_customer = 0;
        if (isset($this->info['is_customer']))
            $is_customer = $this->info['is_customer'];
        //
        if (!empty($this->info['salesman_id'])) {
            $cond_inv .= ' and Sales_ID = "' . $this->info['salesman_id'] . '" ';
            $cond_trans .= ' and salesman_id = "' . $this->info['salesman_id'] . '" ';
        }
        $cust_sales_group = array();
        $cust_id_arr = array();
        if (!empty($this->info['cust_salesman'])) {
            $query = $this->db->query('select customer_id from tbl_salesman_customers 
                where employee_id = "' . $this->info['cust_salesman'] . '"');
            while ($row = $this->db->assoc($query)) {
                $cust_id_arr[] = $row['customer_id'];
            }
            if (!empty($cust_id_arr)) {
                $cond_inv .= ' and Customer_ID in (' . implode(',', $cust_id_arr) . ') ';
                $cond_trans .= ' and a.main_id in (' . implode(',', $cust_id_arr) . ') ';
                $cond_note .= ' and Supplier_Customer_ID in (' . implode(',', $cust_id_arr) . ') ';
            } else {
                $cond_inv .= ' and 1=2 ';
                $cond_trans .= ' and 1=2 ';
            }
        }
        if (!empty($this->info['customer_group_id']) && $is_customer) {
            $cond_inv .= ' and customer_group_id = "' . $this->info['customer_group_id'] . '"';
        }
        //        echo $is_customer.'===';
        $data = array();
        $cust_supp_arr = array();
        $inv_arr = array();
        $trans_arr = array();
        if ($is_customer) {
            $query = $this->db->query('SELECT `Invoice_ID_Auto` as auto_id,`Invoice_Shipping`,
            `Customer_ID`,`Invoice_Net_Total`,`Invoice_Due_Date` as due_date,`Invoice_Paid_Amount`,`is_actual`,
            `Payment_Paid_Amount`,`second_currency_rate`,`current_rate`,
            (((`Invoice_Net_Total`+`Invoice_Shipping`) - (`Payment_Paid_Amount`+`Invoice_Paid_Amount`))*' . ($is_local == 1 ? 'current_rate' : 'second_currency_rate') . ') as amount,
            Customer_Name as person_name,customer_group_id
            FROM `tbl_invoices` i join tbl_customers  using(Customer_ID) 
            WHERE ((`Invoice_Net_Total`+`Invoice_Shipping`) > (`Payment_Paid_Amount`+`Invoice_Paid_Amount`)) 
            ' . $cond_common . ' ' . $cond_inv . '
            order by Invoice_Due_Date asc');
            while ($row = $this->db->assoc($query)) {
                $inv_arr[$row['Customer_ID']][$row['auto_id']] = $row;
                $cust_supp_arr[$row['Customer_ID']] = $row['person_name'];
            }
        } else {
            $query = $this->db->query('SELECT `Purchase_ID_Auto` as auto_id,`Purchase_Shipping`,
           `Supplier_ID`,`Purchase_Net_Total`,`Purchase_Due_Date` as due_date,`Purchase_Paid_Amount`,`is_actual`,
            `second_currency_rate`,`current_rate`,
            (((`Purchase_Net_Total`+`Purchase_Shipping`) - (`Purchase_Paid_Amount`))*' . ($is_local == 1 ? 'current_rate' : 'second_currency_rate') . ') as amount,
            Supplier_Name as person_name,null as group_id
            FROM `tbl_inventory_purchases` i join tbl_stock_suppliers using(Supplier_ID) 
            WHERE ((`Purchase_Net_Total`+`Purchase_Shipping`)  > `Purchase_Paid_Amount`) 
            ' . $cond_common . '
            order by `Purchase_Due_Date` asc');
            while ($row = $this->db->assoc($query)) {
                $inv_arr[$row['Supplier_ID']][$row['auto_id']] = $row;
                $cust_supp_arr[$row['Supplier_ID']] = $row['person_name'];
            }
        }
        //
        $main_type = $is_customer ? 'cust' : 'supp';
        $trans_type = $is_customer ? 'inv' : 'pur';
        if (!empty($this->info['acc_due_inv'])) {
            if (!empty($cust_supp_arr)) {
                $cond_trans .= ' and a.main_id in (' . implode(',', array_keys($cust_supp_arr)) . ')';
            } else {
                $cond_trans .= ' and 1=2 ';
            }
        }
        $query_trans = $this->db->query('select 
            sum(' . ($is_local == 1 ? 'local_amount' : 'Transaction_Amount*second_currency_rate') . '*if(Transaction_Type="Debit",1,-1)) as amount,
            a.main_id,a.Account_Name
            from tbl_accounting_transactions t join tbl_chart_of_accounts a on a.Account_ID = t.Account_ID
            and a.main_type="' . $main_type . '" and a.sub_type="main" 
                join tbl_customers c on c.Customer_ID = a.main_id
                where t.main_type<>"' . $trans_type . '"  
            ' . $cond_common . ' ' . $cond_trans . ' ' . $cond_inv . '
            group by t.Account_ID
            ');
        while ($row = $this->db->assoc($query_trans)) {
            $trans_arr[$row['main_id']] = $row;
            $cust_supp_arr[$row['main_id']] = $row['Account_Name'];
        }
        //
        // to add pay/rec on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.current_rate' : 'p.second_currency_rate') . ') as amount,
            a.Account_Name,a.main_id 
            FROM `tbl_invoice_payments` ip join tbl_payment_receipt p on p.pay_rec_id = ip.`record_id` 
            join tbl_chart_of_accounts a on a.Account_ID = p.Account_ID and a.main_type="' . $main_type . '" 
            and a.sub_type="main" 
               join tbl_customers c on c.Customer_ID = a.main_id
            WHERE ip.type="' . ($is_customer ? 'rec' : 'pay') . '" and p.is_return=0 
            ' . $cond_common . ' ' . $cond_trans . ' ' . $cond_inv . '
            group by p.Account_ID');
        while ($row = $this->db->assoc($query_rec))
            $trans_arr[$row['main_id']]['amount'] += $row['amount'];
//        echo"<pre>";die(print_r($trans_arr));
        // to add pay/rec on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.current_rate' : 'p.second_currency_rate') . ') as amount,
            p.Supplier_Customer_ID 
            FROM `tbl_invoice_payments` ip join tbl_accounting_debit_credit_note p on p.Note_ID = ip.`record_id` 
              join tbl_customers c on c.Customer_ID = p.Supplier_Customer_ID
            WHERE ip.type="' . ($is_customer ? 'cre' : 'deb') . '" and p.Is_Debit_Note="' . ($is_customer ? '0' : '1') . '" 
            ' . $cond_common . ' ' . $cond_note . ' ' . $cond_inv . '
            group by p.Supplier_Customer_ID');
        while ($row = $this->db->assoc($query_rec))
            $trans_arr[$row['Supplier_Customer_ID']]['amount'] += $row['amount'];


        // to add pay/rec on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.Current_Ex_Rate' : 'p.second_currency_rate') . ') as amount,
            a.main_id 
            FROM `tbl_invoice_payments` ip join tbl_accounting_transactions p on p.Transaction_ID = ip.`record_id` 
            join tbl_chart_of_accounts a on a.Account_ID = p.Account_ID and a.main_type="' . $main_type . '" 
            and a.sub_type="main"  join tbl_customers c on c.Customer_ID = a.main_id
            WHERE ip.type="' . ($is_customer ? 'cmjv' : 'smjv') . '" 
            ' . $cond_common . ' ' . $cond_trans . ' ' . $cond_inv . '
            group by p.Account_ID');
        while ($row = $this->db->assoc($query_rec))
            $trans_arr[$row['main_id']]['amount'] += $row['amount'];
        //        }
        //        echo"<pre>";
        //        print_r($trans_arr);
        //        echo"<pre>";
        //        print_r($inv_arr);
        //
        $total_arr = array(
            "0" => 0,
            "30" => 0,
            "60" => 0,
            "90" => 0,
            "120" => 0,
            "more" => 0,
            "balance" => 0
        );
        $cust_sales_arr = array();
        $cust_group_arr = array();
        if ($is_customer) {
            $query = $this->db->query('select c.Customer_ID,g.group_name from tbl_customers c join tbl_general_groups g 
            on g.group_id = c.customer_group_id 
            where Customer_ID in (' . implode(',', array_keys($cust_supp_arr)) . ')');
            while ($row = $this->db->assoc($query)) {
                $cust_group_arr[$row['Customer_ID']] = $row['group_name'];
            }
            //
            $query = $this->db->query('select c.customer_id,
                concat_ws(" ",e.Employee_FirstName,e.Employee_MiddleName,e.Employee_LastName) as employee_name
                from tbl_salesman_customers c 
                join tbl_hrm_employee e on e.Employee_ID = c.employee_id
                where c.customer_id in (' . implode(',', array_keys($cust_supp_arr)) . ')');
            while ($row = $this->db->assoc($query)) {
                $cust_sales_arr[$row['customer_id']] = $row['employee_name'];
            }
        }

//        echo"<pre>";die(print_r($cust_supp_arr));
        foreach ($cust_supp_arr as $cust_id => $cust_name) {
            $empty_cstmr_arr = array("customer_name" => $cust_name);
            if ($is_customer) {
                $empty_cstmr_arr["salesman"] = !empty($cust_sales_arr[$cust_id]) ? $cust_sales_arr[$cust_id] : '';
                $empty_cstmr_arr["group"] = !empty($cust_group_arr[$cust_id]) ? $cust_group_arr[$cust_id] : '';
            }
            $empty_cstmr_arr["0"] = 0;
            $empty_cstmr_arr["30"] = 0;
            $empty_cstmr_arr["60"] = 0;
            $empty_cstmr_arr["90"] = 0;
            $empty_cstmr_arr["120"] = 0;
            $empty_cstmr_arr["more"] = 0;
            $empty_cstmr_arr["balance"] = 0;

            if (!empty($inv_arr[$cust_id])) {
                foreach ($inv_arr[$cust_id] as $inv_id => &$inv_row) {
                    $is_opn_blnc = false;
                    if (!empty($trans_arr[$cust_id]) && abs($trans_arr[$cust_id]['amount']) > 0.000001) {
                        if (($is_customer && $trans_arr[$cust_id]['amount'] < 0) || (!$is_customer && $trans_arr[$cust_id]['amount'] > 0)) {
                            $close_amount = min(abs($trans_arr[$cust_id]['amount']), abs($inv_row['amount']));
                            $inv_row['amount'] -= $close_amount;
                            $trans_arr[$cust_id]['amount'] += $close_amount * ($is_customer ? 1 : -1);
                        } else
                            $is_opn_blnc = true;
                    }
                    if ($is_opn_blnc || abs($inv_arr[$cust_id][$inv_id]['amount']) > 0.000001) {
                        if (empty($data[$cust_id]))
                            $data[$cust_id] = $empty_cstmr_arr;
                        if ($is_opn_blnc) {
                            $data[$cust_id]["balance"] += $trans_arr[$cust_id]['amount'];
                            //                            $total_arr["balance"]+=$trans_arr[$cust_id]['amount'];
                            $data[$cust_id][0] += $trans_arr[$cust_id]['amount'];
                            //                            $total_arr[0]+=$trans_arr[$cust_id]['amount'];
                            $trans_arr[$cust_id]['amount'] = 0;
                        }
                        if (!empty($inv_arr[$cust_id][$inv_id]['amount'])) {
                            $date_diff = CommonFunctions::calc_date_diff($to_date, $inv_row['due_date']);
                            if ($date_diff <= 0)
                                $indx = 0;
                            elseif ($date_diff < 30)
                                $indx = 30;
                            elseif ($date_diff < 60)
                                $indx = 60;
                            elseif ($date_diff < 90)
                                $indx = 90;
                            elseif ($date_diff < 120)
                                $indx = 120;
                            else
                                $indx = 'more';
                            //
                            $data[$cust_id][$indx] += $inv_arr[$cust_id][$inv_id]['amount'];
                            //                            $total_arr[$indx]+=$inv_arr[$cust_id][$inv_id]['amount'];
                            //for totals
                            $data[$cust_id]["balance"] += $inv_arr[$cust_id][$inv_id]['amount'];
                            //                            $total_arr["balance"]+=$inv_arr[$cust_id][$inv_id]['amount'];
                        }
                    }
                }
            }
            //
            if (!empty($trans_arr[$cust_id]) && abs($trans_arr[$cust_id]['amount']) > 0.000001) {
                if (empty($data[$cust_id]))
                    $data[$cust_id] = $empty_cstmr_arr;
                $data[$cust_id]["balance"] += $trans_arr[$cust_id]['amount'] * ($is_customer ? 1 : -1);
                //                $total_arr["balance"]+=$trans_arr[$cust_id]['amount'] * ($is_customer ? 1 : -1);
                $data[$cust_id][0] += $trans_arr[$cust_id]['amount'] * ($is_customer ? 1 : -1);
                //                $total_arr[0]+=$trans_arr[$cust_id]['amount'] * ($is_customer ? 1 : -1);
                $trans_arr[$cust_id]['amount'] = 0;
            }
        }
        $data_final = array();
        foreach ($data as $indx => $row) {
            if ($row['balance'] < 0 && empty($this->info['negative_balance']))
                continue;

            $total_arr[0] += $row[0];
            $total_arr[30] += $row[30];
            $total_arr[60] += $row[60];
            $total_arr[90] += $row[90];
            $total_arr[120] += $row[120];
            $total_arr['balance'] += $row['balance'];
            $total_arr['more'] += $row['more'];
            //
            $row[0] = CommonFunctions::formatNumber($row[0]);
            $row[30] = CommonFunctions::formatNumber($row[30]);
            $row[60] = CommonFunctions::formatNumber($row[60]);
            $row[90] = CommonFunctions::formatNumber($row[90]);
            $row[120] = CommonFunctions::formatNumber($row[120]);
            $row['balance'] = CommonFunctions::formatNumber($row['balance']);
            $row['more'] = CommonFunctions::formatNumber($row['more']);
            $data_final[] = array_values($row);
        }
        //        $data_final = array_map(function($row) {
        //            if ($row['balance'] < 0)
        //                unset($row);
        //            $row[0] = CommonFunctions::formatNumber($row[0]);
        //            $row[30] = CommonFunctions::formatNumber($row[30]);
        //            $row[60] = CommonFunctions::formatNumber($row[60]);
        //            $row[90] = CommonFunctions::formatNumber($row[90]);
        //            $row[120] = CommonFunctions::formatNumber($row[120]);
        //            $row['balance'] = CommonFunctions::formatNumber($row['balance']);
        //            $row['more'] = CommonFunctions::formatNumber($row['more']);
        //            return array_values($row);
        //        }, $data);
        $total_arr[0] = CommonFunctions::formatNumber($total_arr[0]);
        $total_arr[30] = CommonFunctions::formatNumber($total_arr[30]);
        $total_arr[60] = CommonFunctions::formatNumber($total_arr[60]);
        $total_arr[90] = CommonFunctions::formatNumber($total_arr[90]);
        $total_arr[120] = CommonFunctions::formatNumber($total_arr[120]);
        $total_arr['balance'] = CommonFunctions::formatNumber($total_arr['balance']);
        $total_arr['more'] = CommonFunctions::formatNumber($total_arr['more']);
        //                echo"<pre>";
        //        die(print_r($data_final));
        return array('data' => array_values($data_final), 'totals' => $total_arr);
        //        echo"<pre>";
        //        print_r($data);
        ////        print_r($inv_arr);
        //        die();
    }

    public function pos_Customer_trial_balance($options) {


        $from_date = $options['From_Date'] ? $options['From_Date'] : smc_session()['start_date'];
        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 0;
        $with_close = !empty($options['with_close']) ? $options['with_close'] : 0;
        $back_up = $options['Is_Actual'] == 1 ? true : false;


        $start_date = $back_up ? smc_session()['start_date_act'] : smc_session()['start_date']; //used as start for opening balance
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day')); // used as end of opening balance
        //        $parents_arr = array();
        $query = $this->db->query('select customer_id,customer_name from tbl_pos_customers');
        while ($row = $this->db->assoc($query)) {
            $cust_arr[$row['customer_id']] = $row['customer_name'];
        }
        //        echo $start_date.'==='.$day_before;die();
        //        echo"<pre>";
        //        die(print_r($parents_arr));
        $data = array();
        foreach ($cust_arr as $customer_id => $customer_name) {
            //            $min = $acc_arr[$project_id]['project_code']; // min acc to retreive e.g. ($i=1 => 1)
            //            $max = $acc_arr[$project_id]['project_code'] . $nines; // max acc to retreive e.g. ($i=1 = >19999..)
            //            $options['code'] = $min;
            //            $options['left'] = true;
            //            $options['is_arr'] = true;
            $options['is_trial_balance'] = 1;
            //            $options['index_acc_id'] = true;
            //            $options['cond'] = " and length(project_code) <= '" . strlen($max) . "' ";
            //
            $options['pos_customer_id'] = $customer_id;
            $open_balance_3_arr = array();
            $close_balance_3_arr = array();
            $prev_balance_3_arr = array();
            $current_array_arr = array();
            if ($opening_balance == 1) {
                $options_opening = $options;
                $options_opening['opening_only'] = 1;
                $options_opening['close_only'] = 0;
                $open_balance_3_arr = self::returnExactBalanceByID($options_opening);
            }
            if ($with_close == 1) {
                $options_close = $options;
                $options_close['opening_only'] = 0;
                $options_close['close_only'] = 1;
                $close_balance_3_arr = self::returnExactBalanceByID($options_close);
            }
            if ($start_date != $from_date) {

                $options_prev = $options;
                $options_prev['From_Date'] = empty($options_prev['From_Date']) ? '' : $start_date;
                $options_prev['To_Date'] = empty($options_prev['To_Date']) ? '' : $day_before;
                $options_prev['Opening_Balance'] = 1;
                $options_prev['opening_only'] = 0;
                echo"<pre>";
                die(print_r($options_prev));
                $prev_balance_3_arr = self::returnExactBalanceByID($options_prev);
            }
            //            echo "<pre>";
            //            die(print_r($prev_balance_3_arr));
            $current_options = $options;
            $current_options['with_close'] = 0;
            $current_options['Opening_Balance'] = 0;
            $current_array_arr = self::returnExactBalanceByID($current_options);
            $opening_balance = !empty($open_balance_3_arr['Balance']) ? $open_balance_3_arr['Balance'] : 0;
            $closing_balance = !empty($close_balance_3_arr['Balance']) ? $close_balance_3_arr['Balance'] : 0;
            $prev_balance = !empty($prev_balance_3_arr['Balance']) ? $prev_balance_3_arr['Balance'] : 0;
            $overall_balance = $opening_balance + $closing_balance + $prev_balance + $current_array_arr['Balance'];
            $data[] = array(
                "Name" => $customer_name,
                "Code" => '',
                "pos_customer_id" => $customer_id,
                'open_balance' => $opening_balance,
                'close_balance' => $closing_balance,
                'prev_balance' => $prev_balance,
                "Debits" => $current_array_arr['Debits'],
                "Credits" => $current_array_arr['Credits'],
                "local_debits" => $current_array_arr['local_debits'],
                "local_credits" => $current_array_arr['local_credits'],
                "second_debits" => $current_array_arr['second_debits'],
                "second_credits" => $current_array_arr['second_credits'],
                "Balance" => $current_array_arr['Balance'],
                "local_balance" => $current_array_arr['local_balance'],
                "second_balance" => $current_array_arr['second_balance'],
                "overall_balance" => $overall_balance,
                "is_parent" => 0
            );
        }

        return $data;
    }

    public function activity_trial_balance($options) {

        $num_digits = $options['digits'];
        $group_num = $options['Grouping'];
        $from_date = $options['From_Date'];
        $opening_balance = !empty($options['Opening_Balance']) ? $options['Opening_Balance'] : 0;
        $with_close = !empty($options['with_close']) ? $options['with_close'] : 0;
        $back_up = $options['Is_Actual'] == 1 ? true : false;
        $len_zeros_nines = $num_digits - $group_num;
        $nines = str_repeat("9", $len_zeros_nines);
        //        echo $nines.'==';die();

        $start_date = $back_up ? smc_session()['start_date_act'] : smc_session()['start_date']; //used as start for opening balance
        $day_before = date('Y-m-d', strtotime($from_date . ' -1 day')); // used as end of opening balance

        $parents_arr = array();
        $acc_arr = array();
        $this->get_activity_tree(0, $parents_arr, $acc_arr, $options);
        //        echo"<pre>";
        //        die(print_r($parents_arr));
        $data = array();
        if(!empty($parents_arr[0]))
        foreach ($parents_arr[0] as $activity_id) {
            $min = $acc_arr[$activity_id]['activity_code']; // min acc to retreive e.g. ($i=1 => 1)
            $max = $acc_arr[$activity_id]['activity_code'] . $nines; // max acc to retreive e.g. ($i=1 = >19999..)
            $options['code'] = $min;
            $options['left'] = true;
            $options['is_arr'] = true;
            $options['index_acc_id'] = true;
            $options['cond'] = " and length(activity_code) <= '" . strlen($max) . "' ";
            //
            $open_balance_3_arr = array();
            $close_balance_3_arr = array();
            $prev_balance_3_arr = array();
            $current_array_arr = array();
            if ($opening_balance == 1) {
                $options_opening = $options;
                $options_opening['opening_only'] = 1;
                $options_opening['close_only'] = 0;
                $open_balance_3_arr = self::returnActivityBalance($options_opening);
            }
            if ($with_close == 1) {
                $options_close = $options;
                $options_close['opening_only'] = 0;
                $options_close['close_only'] = 1;
                $close_balance_3_arr = self::returnActivityBalance($options_close);
            }
            if ($start_date != $from_date) {

                $options_prev = $options;
                $options_prev['From_Date'] = empty($options_prev['From_Date']) ? '' : $start_date;
                $options_prev['To_Date'] = empty($options_prev['To_Date']) ? '' : $day_before;
                $options_prev['Opening_Balance'] = 1;
                $options_prev['opening_only'] = 0;
                $prev_balance_3_arr = self::returnActivityBalance($options_prev);
            }
            //            echo "<pre>";
            //            die(print_r($prev_balance_3_arr));
            $current_options = $options;
            $current_options['with_close'] = 0;
            $current_options['Opening_Balance'] = 0;
            $current_array_arr = self::returnActivityBalance($current_options);
            //            echo"<pre>";print_r($current_array_arr);
            $this->build_activity_trial_arr($data, $activity_id, $open_balance_3_arr, $prev_balance_3_arr, $current_array_arr, $close_balance_3_arr, $parents_arr, $acc_arr, $options);
        }

        return $data;
    }

    public function get_activity_tree($parent_ids, &$parents_arr, &$acc_arr, $options) {
        $new_parent_ids = array();
        $cond = ' ';
        if (!empty($options['from_account']))
            $cond .= ' and left(activity_code,length(LEAST(activity_code,"' . $options['from_account'] . '"))) >= left("' . $options['from_account'] . '",length(LEAST(activity_code,"' . $options['from_account'] . '"))) ';
        if (!empty($options['to_account']))
            $cond .= ' and left(activity_code,length(LEAST(activity_code,"' . $options['to_account'] . '"))) <= left("' . $options['to_account'] . '",length(LEAST(activity_code,"' . $options['to_account'] . '"))) ';
        $query = $this->db->query("select parent_id,activity_id,activity_code,activity_title
                from tbl_activity_tree where parent_id in ({$parent_ids}) " . $cond);
        while ($row = $this->db->assoc($query)) {
            $acc_arr[$row['activity_id']] = $row;
            if (!isset($parents_arr[$row['parent_id']]))
                $parents_arr[$row['parent_id']] = array();
            $new_parent_ids[$row['activity_id']] = $row['activity_id'];
            $parents_arr[$row['parent_id']][] = $row['activity_id'];
        }
        if (!empty($new_parent_ids))
            $this->get_activity_tree(implode(',', $new_parent_ids), $parents_arr, $acc_arr, $options);
    }

    public function build_activity_trial_arr(&$data, $activity_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $acc_total = $this->get_activity_group_totals($activity_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);

        if (!empty($acc_total)) {
            $data[] = $acc_total;
        }
        if (!empty($parents_arr[$activity_id])) {
            foreach ($parents_arr[$activity_id] as $child_id) {

                $this->build_activity_trial_arr($data, $child_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options);
            }
        }
    }

    public function get_activity_group_totals($activity_id, $open_arr, $prev_arr, $current_arr, $close_arr, $parents_arr, $acc_arr, $options) {
        $open_balance = $prev_balance = $close_balance = $debits = $credits = $debits_local = $credits_local = 0;
        $debits_second = $credits_second = $current_balance = $current_balance_local = $current_balance_second = $overall_balance = 0;
        $activities = array($activity_id);
        $this->get_acc_childs($activity_id, $activities, $parents_arr);
        $is_parent = false;
        if (!empty($parents_arr[$activity_id]))
            $is_parent = true;
        foreach ($activities as $current_id) {
            if (!empty($current_arr[$current_id])) {
                $current_balance += $current_arr[$current_id]['Balance'];
                $overall_balance += $current_arr[$current_id]['Balance'];
                $debits += $current_arr[$current_id]['Debits'];
                $credits += $current_arr[$current_id]['Credits'];
                $debits_local += $current_arr[$current_id]['local_debits'];
                $credits_local += $current_arr[$current_id]['local_credits'];
                $debits_second += $current_arr[$current_id]['second_debits'];
                $credits_second += $current_arr[$current_id]['second_credits'];
                $current_balance_local += $current_arr[$current_id]['local_balance'];
                $current_balance_second += $current_arr[$current_id]['second_balance'];
            }
            if (!empty($open_arr[$current_id])) {
                $open_balance += $open_arr[$current_id]['Balance'];
                $overall_balance += $open_arr[$current_id]['Balance'];
            }
            if (!empty($prev_arr[$current_id])) {
                $prev_balance += $prev_arr[$current_id]['Balance'];
                $overall_balance += $prev_arr[$current_id]['Balance'];
            }
            if (!empty($close_arr[$current_id])) {
                $close_balance += $close_arr[$current_id]['Balance'];
                $overall_balance += $close_arr[$current_id]['Balance'];
            }
        }
        if ($is_parent && mb_strlen($acc_arr[$activity_id]['activity_code']) > $options['Grouping'])
            return null;
        if (mb_strlen($acc_arr[$activity_id]['activity_code']) > $options['digits'])
            return null;
        if (($is_parent && (abs(round($credits, 3)) > 0 || abs(round($debits, 3)) > 0)) || (abs(round($overall_balance, 3)) > 0) || ($options['Active'] == 0 && (((abs(round($credits, 3)) > 0) || (abs(round($debits, 3)) > 0))))
        ) {
            return array(
                "Name" => $acc_arr[$activity_id]['activity_title'], "Code" => $acc_arr[$activity_id]['activity_code'],
                "activity_id" => $activity_id,
                'open_balance' => $open_balance, 'close_balance' => $close_balance, 'prev_balance' => $prev_balance,
                "Debits" => $debits, "Credits" => $credits, "local_debits" => $debits_local, "local_credits" => $credits_local,
                "second_debits" => $debits_second, "second_credits" => $credits_second, "Balance" => $current_balance,
                "local_balance" => $current_balance_local, "second_balance" => $current_balance_second, "overall_balance" => $overall_balance,
                "is_parent" => $is_parent
            );
        }
        return null;
    }

    public function returnActivityBalance($options) {
        //        echo"<pre>";
        //        die(print_r($options));
        $condition = ' ';

        if (!empty($options['left'])) {
            $condition .= ' AND LEFT(activity_code,' . strlen($options['code']) . ') = "' . $options['code'] . '"';
        } else {
            $condition .= ' AND activity_code IN ("' . $options['code'] . '")';
        }
        $acc_id_arr = array();
        $account_ids = '';
        $query = $this->db->query('SELECT  activity_id,activity_code
                                            FROM  tbl_activity_tree  
                                            WHERE true ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $acc_id_arr[$row['activity_id']] = $row['activity_code'];
            $account_ids .= (empty($account_ids) ? '' : ',') . $row['activity_id'];
        }
        $options['activity_id'] = $account_ids;


        $condition = '';

        if (!empty($options['cond'])) {
            $condition .= $options['cond'];
        }
        if (!empty($options['activity_id']))
            $condition .= ' AND t.activity_id  in (' . $options['activity_id'] . ') ';

        $currency_id = empty($options['Currency_ID']) ? CurrencyFactory::getDefaultCurrency() : $options['Currency_ID'];


        if (!empty($options['opening_only']) && $options['opening_only'] == 1)
            $condition .= '  and t.main_type="opy" ';
        elseif (!empty($options['Opening_Balance']) || $options['Opening_Balance'] == 0)
            $condition .= ' and t.main_type <> "opy" ';

        if (!empty($options['Opening_Balance'])) {
            if (!empty($options['From_Date']) && !empty($options['due_date_from']))
                $condition .= 'and (t.Transaction_Date < "' . $options['To_Date'] . '" or t.due_date < "' . $options['due_date_from'] . '") ';
            else {
                if (!empty($options['From_Date']))
                    $condition .= ' and t.Transaction_Date < "' . $options['To_Date'] . '"';
                if (!empty($options['due_date_from']))
                    $condition .= '  and t.due_date < "' . $options['due_date_from'] . '"';
            }
        }
        if (isset($options['close_only'])) {
            if ($options['close_only'] == 1)
                $condition .= '  and t.main_type="cly" ';
        }
        elseif (isset($options['with_close'])) {
            if ($options['with_close'] == 0)
                $condition .= ' and t.main_type <> "cly" ';
        }
        //
        if (!empty($options['From_Date']) && !empty($options['To_Date']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.Transaction_Date >= "' . $options['From_Date'] . '" 
                                and t.Transaction_Date <= "' . $options['To_Date'] . '" ';
        if (!empty($options['due_date_from']) && !empty($options['due_date_to']) && empty($options['opening_only']) && empty($options['close_only']) && empty($options['Opening_Balance']))
            $condition .= ' and t.due_date >= "' . $options['due_date_from'] . '" 
                                and t.due_date <= "' . $options['due_date_to'] . '" ';
        if (isset($options['Is_Actual']) && $options['Is_Actual'] == 0) {
            $condition .= ' and t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '" ';
        } elseif (isset($options['Actual_Only']) && $options['Actual_Only']) {
            $condition .= ' and t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '" ';
        } else
            $condition .= ' and ((t.is_actual = 0 and t.current_year_id = "' . $this->year_id . '") 
                    or ( t.is_actual = 1 and t.current_year_id = "' . $this->year_id_actual . '")) ';

        if (!empty($options['trans_type']) && $options['trans_type'] != '') {
            $condition .= ' and t.main_type in ("' . implode('","', $options['trans_type']) . '") ';
        }
        if (!empty($options['debit_credit_type']) && $options['debit_credit_type'] != 'All') {
            $condition .= ' and t.Transaction_Type = "' . $options['debit_credit_type'] . '" ';
        }

        if (!empty($options['from_amount'])) {
            $condition .= ' and t.Transaction_Amount >= "' . $options['from_amount'] . '" ';
        }
        if (!empty($options['to_amount'])) {
            $condition .= ' and  t.Transaction_Amount <= "' . $options['to_amount'] . '"';
        }

        if (!empty($options['trans_currency'])) {
            $condition .= ' and t.Currency_ID ="' . $options['trans_currency'] . '"';
        }
        if (!empty($options['project_id'])) {
            $condition .= ' and t.project_id ="' . $options['project_id'] . '"';
        }

        $acc_arr = array();
        $query = $this->db->query('SELECT 
                                                t.Transaction_Reference,
                                                t.Currency_ID,
                                                t.Account_ID,
                                                t.activity_id,
                                                t.Transaction_Amount,
                                                t.Current_Ex_Rate,
                                                t.second_currency_rate,
                                                t.Exchange_Rate_ID,
                                                t.Transaction_Type,
                                                t.local_amount,
                                                (t.Transaction_Amount*t.second_currency_rate) as second_amount,
                                                t.main_type
                                            FROM tbl_accounting_transactions t  join tbl_activity_tree j on j.activity_id = t.activity_id
                                            WHERE 1=1
                                         ' . $condition);
        while ($row = $this->db->assoc($query)) {
            $temp_amount = 0.0;
            if ($currency_id == smc_session()['local_currency']) {
                $temp_amount = $row['local_amount'];
            } else {
                $temp_amount = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
            }
            //
            $indx = $row['activity_id'];
            if (!isset($acc_arr[$indx])) {
                $acc_arr[$indx] = array(
                    "Balance" => 0,
                    "Debits" => 0,
                    "Credits" => 0,
                    "local_debits" => 0,
                    "local_credits" => 0,
                    "second_debits" => 0,
                    "second_credits" => 0,
                    "local_balance" => 0,
                    "second_balance" => 0
                );
            }
            //
            if ($row['Transaction_Type'] == 'Debit') {
                $acc_arr[$indx]["Debits"] += $temp_amount;
                $acc_arr[$indx]["local_debits"] += $row['local_amount'];
                $acc_arr[$indx]["second_debits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] += $temp_amount;
                $acc_arr[$indx]["local_balance"] += $row['local_amount'];
                $acc_arr[$indx]["second_balance"] += $row['second_amount'];
            } elseif ($row['Transaction_Type'] == 'Credit') {
                $acc_arr[$indx]["Credits"] += $temp_amount;
                $acc_arr[$indx]["local_credits"] += $row['local_amount'];
                $acc_arr[$indx]["second_credits"] += $row['second_amount'];
                $acc_arr[$indx]["Balance"] -= $temp_amount;
                $acc_arr[$indx]["local_balance"] -= $row['local_amount'];
                $acc_arr[$indx]["second_balance"] -= $row['second_amount'];
            }
        }
        return $acc_arr;
    }

    public function fill_aging_debit_arr(&$debit_arr, $row, $to_date) {
        $debit_arr[$row['main_id']]['name'] = $row['person_name'];
        $debit_arr[$row['main_id']]['group_name'] = $row['group_name'];
        $debit_arr[$row['main_id']]['employee_name'] = $row['employee_name'];
        $debit_arr[$row['main_id']]['limit_days'] = $row['limit_days'];
        $debit_arr[$row['main_id']]['limit_balance'] = $row['limit_balance'];
        $debit_arr[$row['main_id']]['currency'] = $row['acc_currency'];
        if (!empty($row['amount'])) {
            $date_diff = CommonFunctions::calc_date_diff($row['date'], $to_date);
            if ($date_diff <= 0)
                $indx = 0;
            elseif ($date_diff < 15)
                $indx = 15;
            elseif ($date_diff < 30)
                $indx = 30;
            elseif ($date_diff < 60)
                $indx = 60;
            elseif ($date_diff < 90)
                $indx = 90;
            elseif ($date_diff < 120)
                $indx = 120;
            else
                $indx = 'more';
            //
            $debit_arr[$row['main_id']][$indx] += $row['amount'];
            $debit_arr[$row['main_id']]["balance"] += $row['amount'];
        }
    }

    public function aging_report_bydate() {
        $cond_inv = '';
        $cond_inv_sales='';
        $cond_trans = '';
        $cond_common = '';
        if (empty($this->info['is_actual'])) {
            $cond_common .= ' and is_actual=0 ';
        }
        $to_date = date("Y-m-d");
        if (!empty($this->info['date']))
            $to_date = $this->info['date'];
        $is_local = 1;
        if (isset($this->info['currency_id']))
            $is_local = $this->info['currency_id'];
        $is_customer = 0;
        if (isset($this->info['is_customer']))
            $is_customer = $this->info['is_customer'];
        //
        if (!empty($this->info['salesman_id'])) {
            $cond_inv_sales .= ' and Sales_ID = "' . $this->info['salesman_id'] . '" ';
            $cond_trans .= ' and salesman_id = "' . $this->info['salesman_id'] . '" ';
        }
        $cust_id_arr = array();
        if (!empty($this->info['cust_salesman'])) {
            $query = $this->db->query('select customer_id from tbl_salesman_customers 
                where employee_id = "' . $this->info['cust_salesman'] . '"');
            while ($row = $this->db->assoc($query)) {
                $cust_id_arr[] = $row['customer_id'];
            }
            if (!empty($cust_id_arr)) {
                $cond_inv .= ' and Customer_ID in (' . implode(',', $cust_id_arr) . ') ';
                $cond_trans .= ' and a.main_id in (' . implode(',', $cust_id_arr) . ') ';
            } else {
                $cond_inv .= ' and 1=2 ';
                $cond_trans .= ' and 1=2 ';
            }
        }
        $group_cond = '';
        if (!empty($this->info['customer_group_id']) && $is_customer) {
            $group_cond .= ' and customer_group_id = "' . $this->info['customer_group_id'] . '" ';
        }
        //        echo $is_customer.'===';
        $data = array();
        $cust_supp_arr = array();

        $credit_arr = array();
        $debit_arr = array();
        $tmp_arr = array("name" => "", "employee_name" => "", "group_name" => "", "limit_days" => 0, "limit_balance" => 0,
            "credit" => 0, "0" => 0, "15" => 0, "30" => 0, "60" => 0, "90" => 0, "120" => 0,
            "more" => 0, "balance" => 0, "pending" => 0, "overall_balance" => 0, "currency" => "");
        if ($is_customer) {
            $query = $this->db->query('SELECT `Invoice_ID_Auto` as auto_id,`Invoice_Shipping`,
            c.`Customer_ID` as main_id,`Invoice_Net_Total`,`Invoice_Date` as date,`Invoice_Paid_Amount`,`is_actual`,
            `Payment_Paid_Amount`,`second_currency_rate`,`current_rate`,
            (((`Invoice_Net_Total`+`Invoice_Shipping`) - (`Payment_Paid_Amount`+`Invoice_Paid_Amount`))*' . ($is_local == 1 ? 'current_rate' : 'second_currency_rate') . ') as amount,
            Customer_Name as person_name,Customer_Limit_Balance as limit_balance,customer_due_date_period as limit_days,
            customer_group_id,c.Currency_ID as acc_currency,g.group_name,
            concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name
            FROM `tbl_invoices` i join tbl_customers c  on c.Customer_ID = i.Customer_ID 
            left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id
            WHERE ((`Invoice_Net_Total`+`Invoice_Shipping`) > (`Payment_Paid_Amount`+`Invoice_Paid_Amount`)) 
            ' . $cond_common . ' ' . $cond_inv . ' ' .$cond_inv_sales.' '. $group_cond . ' and Invoice_Date <= "' . $to_date . '"
            order by Invoice_Date asc');
            while ($row = $this->db->assoc($query)) {
                if (!isset($debit_arr[$row['main_id']]))
                    $debit_arr[$row['main_id']] = $tmp_arr;
                $this->fill_aging_debit_arr($debit_arr, $row, $to_date);
            }
        } else {
            $query = $this->db->query('SELECT `Purchase_ID_Auto` as auto_id,`Purchase_Shipping`,
           `Supplier_ID` as main_id,`Purchase_Net_Total`,`Purchase_Date` as date,`Purchase_Paid_Amount`,`is_actual`,
            `second_currency_rate`,`current_rate`,
            (((`Purchase_Net_Total`+`Purchase_Shipping`) - (`Purchase_Paid_Amount`))*' . ($is_local == 1 ? 'current_rate' : 'second_currency_rate') . ') as amount,
            Supplier_Name as person_name,0 as limit_balance,supplier_due_date_period as limit_days,
            null as group_id,s.Currency_ID as acc_currency,"" as group_name,"" as employee_name
            FROM `tbl_inventory_purchases` i join tbl_stock_suppliers s using(Supplier_ID) 
            WHERE ((`Purchase_Net_Total`+`Purchase_Shipping`)  > `Purchase_Paid_Amount`) 
            ' . $cond_common . ' and Purchase_Date <= "' . $to_date . '"
            order by `Purchase_Date` asc');
            while ($row = $this->db->assoc($query)) {
                if (!isset($debit_arr[$row['main_id']]))
                    $debit_arr[$row['main_id']] = $tmp_arr;
                $this->fill_aging_debit_arr($debit_arr, $row, $to_date);
//                $debit_arr[$row['Supplier_ID']]['name'] = $row['person_name'];
//                $debit_arr[$row['Supplier_ID']]['limit_days'] = $row['limit_days'];
//                $debit_arr[$row['Supplier_ID']]['limit_balance'] = $row['limit_balance'];
//                $debit_arr[$row['Supplier_ID']]['currency'] = $row['acc_currency'];
//                if (!empty($row['amount'])) {
//                    $date_diff = CommonFunctions::calc_date_diff($row['date'], $to_date);
//                    if ($date_diff <= 0)
//                        $indx = 0;
//                    elseif ($date_diff < 15)
//                        $indx = 15;
//                    elseif ($date_diff < 30)
//                        $indx = 30;
//                    elseif ($date_diff < 60)
//                        $indx = 60;
//                    elseif ($date_diff < 90)
//                        $indx = 90;
//                    elseif ($date_diff < 120)
//                        $indx = 120;
//                    else
//                        $indx = 'more';
//                    //
//                    $debit_arr[$row['Supplier_ID']][$indx]+= $row['amount'];
//                    $debit_arr[$row['Supplier_ID']]["balance"]+= $row['amount'];
//                }
//                $cust_supp_arr[$row['Supplier_ID']] = array('name' => $row['person_name'], 'currency' => $row['acc_currency'],
//                    'limit_days' => $row['limit_days'], 'limit_balance' => $row['limit_balance'], 'pending' => 0);
            }
        }
        //
        $main_type = $is_customer ? 'cust' : 'supp';
        $trans_type = $is_customer ? 'inv' : 'pur';

        $query_trans = $this->db->query('select 
            sum(' . ($is_local == 1 ? 'local_amount' : 'Transaction_Amount*second_currency_rate') . '*if(Transaction_Type="Debit",1,-1)) as amount,
            a.main_id,a.Account_Name,a.Currency_ID as acc_currency,' . ($main_type == 'cust' ? 'c.Customer_Limit_Balance' : '0') . ' as limit_balance,
                ' . ($main_type == 'cust' ? 'c.customer_due_date_period as limit_days,g.group_name,concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name,' : 'c.supplier_due_date_period as limit_days,"" as group_name,"" as employee_name,') . 't.Transaction_Date as date,
                    t.Transaction_Type
            from tbl_accounting_transactions t join tbl_chart_of_accounts a on a.Account_ID = t.Account_ID
            and a.main_type="' . $main_type . '" and a.sub_type="main"
                ' . ($main_type == 'cust' ?
                        ' join tbl_customers c on c.Customer_ID = a.main_id 
                  left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id  ' : ' join tbl_stock_suppliers c on c.Supplier_ID = a.main_id ') . '
                where t.main_type<>"' . $trans_type . '"  
            ' . $cond_common . ' ' . $cond_trans . ' ' . $group_cond . ' and Transaction_Date <= "' . $to_date . '"
            group by t.Account_ID,t.Transaction_Date,t.Transaction_Type
            ');
        while ($row = $this->db->assoc($query_trans)) {

            if (!isset($debit_arr[$row['main_id']]))
                $debit_arr[$row['main_id']] = $tmp_arr;
            $debit_arr[$row['main_id']]['name'] = $row['Account_Name'];
            $debit_arr[$row['main_id']]['group_name'] = $row['group_name'];
            $debit_arr[$row['main_id']]['employee_name'] = $row['employee_name'];
            $debit_arr[$row['main_id']]['limit_days'] = $row['limit_days'];
            $debit_arr[$row['main_id']]['limit_balance'] = $row['limit_balance'];
            $debit_arr[$row['main_id']]['currency'] = $row['acc_currency'];
            if (($is_customer && $row['Transaction_Type'] == 'Debit') || (!$is_customer && $row['Transaction_Type'] == 'Credit')) {
                if (!empty($row['amount'])) {
                    $date_diff = CommonFunctions::calc_date_diff($row['date'], $to_date);
                    if ($date_diff <= 0)
                        $indx = 0;
                    elseif ($date_diff < 15)
                        $indx = 15;
                    elseif ($date_diff < 30)
                        $indx = 30;
                    elseif ($date_diff < 60)
                        $indx = 60;
                    elseif ($date_diff < 90)
                        $indx = 90;
                    elseif ($date_diff < 120)
                        $indx = 120;
                    else
                        $indx = 'more';
                    //
                    $debit_arr[$row['main_id']][$indx] += $row['amount'];
                    $debit_arr[$row['main_id']]["balance"] += $row['amount'];
                }
            }else {
                if (!isset($credit_arr[$row['main_id']]))
                    $credit_arr[$row['main_id']] = 0;
                $credit_arr[$row['main_id']] += $row['amount'];
            }
            //
//            $cust_supp_arr[$row['main_id']] = array('name' => $row['Account_Name'], 'currency' => $row['acc_currency'],
//                'limit_days' => $row['limit_days'], 'limit_balance' => $row['limit_balance'], 'pending' => 0);
        }
        //
        // to add pay/rec on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.current_rate' : 'p.second_currency_rate') . ') as amount,
            a.Account_Name as person_name,a.main_id,p.payment_date as date,' . ($is_customer ? 'c.Customer_Limit_Balance' : '0') . ' as limit_balance,
                ' . ($is_customer ? 'c.customer_due_date_period as limit_days,g.group_name,concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name,' : 'c.supplier_due_date_period as limit_days,"" as group_name,"" as employee_name,') . ' a.Currency_ID as acc_currency 
            FROM `tbl_invoice_payments` ip join tbl_payment_receipt p on p.pay_rec_id = ip.`record_id` 
            join tbl_chart_of_accounts a on a.Account_ID = p.Account_ID and a.main_type="' . $main_type . '" 
            and a.sub_type="main"
            ' . ($main_type == 'cust' ? ' join tbl_customers c on c.Customer_ID = a.main_id
                left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id ' : ' join tbl_stock_suppliers c on c.Supplier_ID = a.main_id ') . '
                WHERE ip.type="' . ($is_customer ? 'rec' : 'pay') . '" and p.is_return=0 
                and p.payment_date <= "' . $to_date . '" 
            ' . $cond_common . ' ' . $cond_trans . ' ' . $group_cond . '
            group by p.Account_ID');
        while ($row = $this->db->assoc($query_rec)) {
            if (!isset($debit_arr[$row['main_id']]))
                $debit_arr[$row['main_id']] = $tmp_arr;
            $this->fill_aging_debit_arr($debit_arr, $row, $to_date);
//            $debit_arr[$row['main_id']]['name'] = $row['Account_Name'];
//            $debit_arr[$row['main_id']]['limit_days'] = $row['limit_days'];
//            $debit_arr[$row['main_id']]['limit_balance'] = $row['limit_balance'];
//            $debit_arr[$row['main_id']]['currency'] = $row['acc_currency'];
//            if (!empty($row['amount'])) {
//                $date_diff = CommonFunctions::calc_date_diff($row['date'], $to_date);
//                if ($date_diff <= 0)
//                    $indx = 0;
//                elseif ($date_diff < 15)
//                    $indx = 15;
//                elseif ($date_diff < 30)
//                    $indx = 30;
//                elseif ($date_diff < 60)
//                    $indx = 60;
//                elseif ($date_diff < 90)
//                    $indx = 90;
//                elseif ($date_diff < 120)
//                    $indx = 120;
//                else
//                    $indx = 'more';
//                //
//                $debit_arr[$row['main_id']][$indx]+= $row['amount'];
//                $debit_arr[$row['main_id']]["balance"]+= $row['amount'];
//            }
        }
        // to add debit/credit notes on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.current_rate' : 'p.second_currency_rate') . ') as amount,
            ' . ($is_customer ? 'c.Customer_Name' : 'c.Supplier_Name') . ' as person_name,
                p.Supplier_Customer_ID as main_id,p.Note_Date as date,' . ($is_customer ? 'c.Customer_Limit_Balance' : '0') . ' as limit_balance,
                ' . ($is_customer ? 'c.customer_due_date_period as limit_days,g.group_name,concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name,' : 'c.supplier_due_date_period as limit_days,"" as group_name,"" as employee_name,') . 'c.Currency_ID as acc_currency 
            FROM `tbl_invoice_payments` ip join tbl_accounting_debit_credit_note p on p.Note_ID = ip.`record_id` 
            ' . ($main_type == 'cust' ? ' join tbl_customers c on c.Customer_ID = p.Supplier_Customer_ID 
                left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id ' : ' join tbl_stock_suppliers c on c.Supplier_ID = p.Supplier_Customer_ID ') . '
                WHERE ip.type="' . ($is_customer ? 'cre' : 'deb') . '" and p.Is_Debit_Note="' . ($is_customer ? 0 : 1) . '" 
                and p.Note_Date <= "' . $to_date . '" 
            ' . $cond_common . ' ' . $cond_inv . ' ' . $group_cond . '
            group by p.Supplier_Customer_ID');
        while ($row = $this->db->assoc($query_rec)) {
            if (!isset($debit_arr[$row['main_id']]))
                $debit_arr[$row['main_id']] = $tmp_arr;
            $this->fill_aging_debit_arr($debit_arr, $row, $to_date);
        }
        // to add manual jv on invoices already subtracted in debit transaction query
        $query_rec = $this->db->query('SELECT sum(`Payment_Amount`*' . ($is_local == 1 ? 'p.Current_Ex_Rate' : 'p.second_currency_rate') . ') as amount,
            a.Account_Name as person_name,
                a.main_id,p.Transaction_Date as date,' . ($is_customer ? 'c.Customer_Limit_Balance' : '0') . ' as limit_balance,
                ' . ($is_customer ? 'c.customer_due_date_period as limit_days,g.group_name,concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name,' : 'c.supplier_due_date_period as limit_days,"" as group_name,"" as employee_name,') . ' a.Currency_ID as acc_currency 
            FROM `tbl_invoice_payments` ip join tbl_accounting_transactions p on p.TRansaction_ID = ip.`record_id` 
            join tbl_chart_of_accounts a on a.Account_ID = p.Account_ID and a.main_type="' . $main_type . '" 
            and a.sub_type="main"
            ' . ($main_type == 'cust' ? ' join tbl_customers c on c.Customer_ID = a.main_id 
                left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id ' : ' join tbl_stock_suppliers c on c.Supplier_ID = a.main_id ') . '
                WHERE ip.type="' . ($is_customer ? 'cmjv' : 'smjv') . '"  
                and p.Transaction_Date <= "' . $to_date . '" 
            ' . $cond_common . ' ' . $cond_inv . ' ' . $group_cond . '
            group by p.Account_ID');
        while ($row = $this->db->assoc($query_rec)) {
            if (!isset($debit_arr[$row['main_id']]))
                $debit_arr[$row['main_id']] = $tmp_arr;
            $this->fill_aging_debit_arr($debit_arr, $row, $to_date);
        }
        //pending rec/pay
        $query_pay = $this->db->query('select 
            sum(' . ($is_local == 1 ? 'total_amount*current_rate' : 'total_amount*second_currency_rate') . ') as amount,
            a.main_id,a.Account_Name,' . ($is_customer == 1 ? 'c.Customer_Limit_Balance' : '0') . ' as limit_balance,
                ' . ($is_customer ? 'c.customer_due_date_period as limit_days,g.group_name,concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as employee_name,' : 'c.supplier_due_date_period as limit_days,"" as group_name,"" as employee_name,') . ' 
                    c.Currency_ID as acc_currency
            from tbl_payment_receipt p join tbl_chart_of_accounts a on a.Account_ID = p.Account_ID
            and a.main_type="' . $main_type . '" and a.sub_type="main" 
                ' . ($is_customer == 1 ? ' join tbl_customers c on c.Customer_ID = a.main_id 
                    left join tbl_general_groups g on g.group_id = c.customer_group_id
            left join tbl_salesman_customers sc on sc.customer_id = c.Customer_ID
            left join tbl_hrm_employee e on e.Employee_ID = sc.employee_id  ' : ' join tbl_stock_suppliers c on c.Supplier_ID = a.main_id ') . '
                where p.is_receipt="' . $is_customer . '"   and p.is_pending = 1  and p.is_return=0 
            ' . $cond_common . ' ' . $cond_trans . ' ' . $group_cond . ' 
            group by p.Account_ID
            ');
        while ($row = $this->db->assoc($query_pay)) {
            if (!isset($debit_arr[$row['main_id']]))
                $debit_arr[$row['main_id']] = $tmp_arr;
            $debit_arr[$row['main_id']]['name'] = $row['Account_Name'];
            $debit_arr[$row['main_id']]['group_name'] = $row['group_name'];
            $debit_arr[$row['main_id']]['employee_name'] = $row['employee_name'];
            $debit_arr[$row['main_id']]['limit_days'] = $row['limit_days'];
            $debit_arr[$row['main_id']]['limit_balance'] = $row['limit_balance'];
            $debit_arr[$row['main_id']]['pending'] = ($row['amount'] * -1);
            $debit_arr[$row['main_id']]['currency'] = $row['acc_currency'];
        }

        $total_arr = array(
            "credit" => 0,
            "0" => 0,
            "15" => 0,
            "30" => 0,
            "60" => 0,
            "90" => 0,
            "120" => 0,
            "more" => 0,
            "balance" => 0,
            "pending" => 0,
            "overall_balance" => 0
        );

//        echo"<pre>";
////        print_r($credit_arr);
//        echo"===========<br>";
//        die(print_r($debit_arr));
        foreach ($debit_arr as $cust_id => $cust_row) {
            if ($is_customer!=1) {
                unset($cust_row['group_name']);
                unset($cust_row['employee_name']);
            }
            $limit_balance = 0;
            if ($is_local == 1 && $cust_row['currency'] == smc_session()['default_setting']['local_currency'] || $is_local == 2 && $cust_row['currency'] == smc_session()['default_setting']['second_currency'])
                $limit_balance = $cust_row['limit_balance'];
            elseif ($is_local == 1)
                $limit_balance = (CurrencyFactory::getLastExRate($cust_row['currency']) * $cust_row['limit_balance']);
            elseif ($is_local == 2)
                $limit_balance = (CurrencyFactory::getSecondCurrencyLastExRate($cust_row['currency']) * $cust_row['limit_balance']);

            $tmp_row = $cust_row;
            $tmp_row['limit_balance'] = CommonFunctions::formatNumber($limit_balance);
            if (!empty($credit_arr[$cust_id])) {
                $credit_tmp = $credit_arr[$cust_id] * -1;
//                echo $credit_tmp.'===';
                if (!empty($debit_arr[$cust_id])) {
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][0]);
                        $credit_tmp -= $tmp;
                        $tmp_row[0] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][15]);
                        $credit_tmp -= $tmp;
                        $tmp_row[15] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][30]);
                        ;
                        $credit_tmp -= $tmp;
                        $tmp_row[30] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][60]);
                        $credit_tmp -= $tmp;
                        $tmp_row[60] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][90]);
                        $credit_tmp -= $tmp;
                        $tmp_row[90] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id][120]);
                        $credit_tmp -= $tmp;
                        $tmp_row[120] -= $tmp;
                    }
                    if ($credit_tmp > 0) {
                        $tmp = min($credit_tmp, $debit_arr[$cust_id]['more']);
                        $credit_tmp -= $tmp;
                        $tmp_row['more'] -= $tmp;
                    }
                }
                $tmp_row['credit'] = ($credit_tmp * -1);
            }
            $tmp_row['balance'] = ($tmp_row[0] + $tmp_row[15] + $tmp_row[30] + $tmp_row[60] + $tmp_row[90] + $tmp_row[120] + $tmp_row['credit']);
            $total_arr['credit'] += $tmp_row['credit'];
            $total_arr[0] += $tmp_row[0];
            $total_arr[15] += $tmp_row[15];
            $total_arr[30] += $tmp_row[30];
            $total_arr[60] += $tmp_row[60];
            $total_arr[90] += $tmp_row[90];
            $total_arr[120] += $tmp_row[120];
            $total_arr['balance'] += $tmp_row['balance'];
            $total_arr['more'] += $tmp_row['more'];
            $total_arr['pending'] += $tmp_row['pending'];
            $total_arr['overall_balance'] += ($tmp_row['pending'] + $tmp_row['balance']);
            //

            $tmp_row[0] = CommonFunctions::formatNumber($tmp_row[0]);
            $tmp_row[15] = CommonFunctions::formatNumber($tmp_row[15]);
            $tmp_row[30] = CommonFunctions::formatNumber($tmp_row[30]);
            $tmp_row[60] = CommonFunctions::formatNumber($tmp_row[60]);
            $tmp_row[90] = CommonFunctions::formatNumber($tmp_row[90]);
            $tmp_row[120] = CommonFunctions::formatNumber($tmp_row[120]);
            $tmp_row['overall_balance'] = CommonFunctions::formatNumber($tmp_row['balance'] + $tmp_row['pending']);
            $tmp_row['credit'] = CommonFunctions::formatNumber($tmp_row['credit']);
            $tmp_row['balance'] = CommonFunctions::formatNumber($tmp_row['balance']);
            $tmp_row['pending'] = CommonFunctions::formatNumber($tmp_row['pending']);
            $tmp_row['more'] = CommonFunctions::formatNumber($tmp_row['more']);
            unset($tmp_row['currency']);
//            echo "<pre>";print_r($tmp_row);
            $data[] = array_values($tmp_row);
        }


        $total_arr['credit'] = CommonFunctions::formatNumber($total_arr['credit']);
        $total_arr[0] = CommonFunctions::formatNumber($total_arr[0]);
        $total_arr[15] = CommonFunctions::formatNumber($total_arr[15]);
        $total_arr[30] = CommonFunctions::formatNumber($total_arr[30]);
        $total_arr[60] = CommonFunctions::formatNumber($total_arr[60]);
        $total_arr[90] = CommonFunctions::formatNumber($total_arr[90]);
        $total_arr[120] = CommonFunctions::formatNumber($total_arr[120]);
        $total_arr['balance'] = CommonFunctions::formatNumber($total_arr['balance']);
        $total_arr['overall_balance'] = CommonFunctions::formatNumber($total_arr['overall_balance']);
        $total_arr['more'] = CommonFunctions::formatNumber($total_arr['more']);
        return array('data' => array_values($data), 'totals' => $total_arr);
    }

    public function get_account_transactions($account_id, $options_arr = array()) {
        $currency_id = empty($options_arr['currency_id']) ? smc_session()['local_currency'] : $options_arr['currency_id'];
        $is_actual = isset($options_arr['is_actual']) ? $options_arr['is_actual'] : false;
        $balance_only = isset($options_arr['balance_only']) ? $options_arr['balance_only'] : false;
        $from_date = isset($options_arr['from_date']) ? $options_arr['from_date'] : null;
        $to_date = isset($options_arr['to_date']) ? $options_arr['to_date'] : null;
        //
        $transactions_arr = array();
        $balance_arr = array('report_act_balance' => 0, 'report_off_balance' => 0, 'report_balance' => 0, 'local_balance' => 0, 'second_balance' => 0
            , 'report_previous_balance' => 0, 'local_previous_balance' => 0, 'second_previous_balance' => 0);
        //
        $cond = " and t.Account_ID = ? and t.is_actual = ? and t.current_year_id = ? ";
        $param_arr = array($account_id, $is_actual, $this->year_id);
        //get previous balance
        if (!empty($from_date)) {
            $query = $this->db->query("SELECT t.* from tbl_accounting_transactions t
                        where 1=1 {$cond} and t.Transaction_Date < ?
                        order by Transaction_Date asc, t.JV_ID asc "
                    , array_merge($param_arr, array($from_date)));
            while ($row = $this->db->assoc($query)) {
                $row['report_amount'] = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
                //
                $second_amount = ($row['Transaction_Amount'] * $row['second_currency_rate']);
                $balance_arr['report_previous_balance'] += $row['current_amount'];
                $balance_arr['local_previous_balance'] += $row['local_amount'];
                $balance_arr['second_previous_balance'] += $second_amount;
                //add it to the total balance
                $balance_arr['report_balance'] += $row['current_amount'];
                $balance_arr['local_balance'] += $row['local_amount'];
                $balance_arr['second_balance'] += $second_amount;
                //
            }
            //here we must add a row containing the previous balance total as first row
//            if (!$balance_only)
//                $transactions_arr[] = $row;
        }
        //add date conditions here after get the previous balance to don't change in the cond and param arr in above query
        if (!empty($from_date)) {
            $cond .= " and t.Transaction_Date >= ? ";
            $param_arr[] = $from_date;
        }
        if (!empty($to_date)) {
            $cond .= " and t.Transaction_Date <= ? ";
            $param_arr[] = $to_date;
        }
        //get current balance
        $query = $this->db->query("SELECT t.* from tbl_accounting_transactions t
                    where 1=1 {$cond}
                    order by Transaction_Date asc, t.JV_ID asc "
                , $param_arr);
        while ($row = $this->db->assoc($query)) {
            $row['report_amount'] = self::getExchangedAmount($currency_id, $row['Currency_ID'], $row['Transaction_Amount'], $row['Current_Ex_Rate'], $row['second_currency_rate'], $row['Exchange_Rate_ID']);
            //
            $second_amount = ($row['Transaction_Amount'] * $row['second_currency_rate']);
            $balance_arr['report_balance'] += $row['current_amount'];
            $balance_arr['local_balance'] += $row['local_amount'];
            $balance_arr['second_balance'] += $second_amount;
            //
            $act_off_indx = ( $row['is_actual'] == 1 ? 'report_act_balance' : 'report_off_balance');
            $balance_arr[$act_off_indx] += $row[$act_off_indx];
            //$abrv = CommonBusiness::get_trans_main_type($row_current['main_type'], true);
            if (!$balance_only)
                $transactions_arr[] = $row;
        }
        //we may return also Account_Code, Account_Name
        $data = array('balances' => $balance_arr);
        if (!$balance_only)
            $data ['transactions'] = $transactions_arr;
        return $data;
    }

}
