<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ACCAjax
 *
 * @author Ola
 */
class ACCAjax extends mainController {

    private $year_id;
    private $year_id_actual;
    private $db;

    public function __construct() {
        parent::__construct();
        $this->year_id = Session::getCurrentYearID();
        $this->year_id_actual = Session::getCurrentYearIDActual();
        $this->db = DBConnectorFactory::loadDriver();
        $this->load->model('ACC');
    }

    public function landing() {

    }

    public function PaymentListRequest() {
        $_GET['tmp__all_ids'] = array();
        $condition = ' 1=1 ';
        $IsReceipt = '';
        
        
        if (isset($_GET['Payment_Date_From']) && isset($_GET['Payment_Date_To'])) {
            $IsReceipt = $_GET["Is_Receipt"];
            $FromDate = $_GET['Payment_Date_From'];
            $ToDate = $_GET['Payment_Date_To'];
            $condition .= ' and Payment_Date >= "' . $FromDate . '" AND Payment_Date <= "' . $ToDate . '"';
        }
        if($this->_registry->permissions->hasPermission('Branches')){
            $condition .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $condition .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }

        if(!empty($_GET['salesman_id']))
            $condition.=' and salesman_id = "'.$_GET['salesman_id'].'" ';
        if(!empty($_GET['user_id']))
            $condition.=' and Logged_ID = "'.$_GET['user_id'].'" ';
        if(isset($_GET['link_filter']) && $_GET['link_filter']!=''){
            if($_GET['link_filter']==0){
                $condition .=' and Payment_Auto_ID in (select record_id from tbl_invoice_payments where type="'.($IsReceipt ? 'rec' : 'pay').'") ';
            }else{
               $condition .=' and Payment_Auto_ID not in (select record_id from tbl_invoice_payments where type="'.($IsReceipt ? 'rec' : 'pay').'") ';
            }
            
        }
        $condition .= ' AND Status_ID= "' . $_GET['Is_Actual'] . '" AND current_year_id = "' . $this->year_id . '"';
        $condition .= $IsReceipt ? ' AND IsReceipt = 1' : ' AND IsReceipt = 0';
        $condition .= ' AND is_return =  "' . $_GET['is_return'] . '"';
        if(isset($_GET['is_pending']) && $_GET['is_pending']!=''){
            $condition.=' and is_pending = "'.$_GET['is_pending'].'" ';
        }
        $columns = array(array("db"=>"ID","formatter"=>function($d,$row){
                    return '<input type="checkbox" data-id="' . $row['Payment_Auto_ID'] . '" data-nb="' . $d . '"  class="del_td pull-left multi_delete"/>' . $d;
               
        }), "Account_Code", "Account_Name",
                         array("db" => "Payment_Amount", "formatter" => function($d) {
                             return CommonFunctions::formatNumber($d);
                         }), "Currency_Symbol", "Payment_Type_Name", "user_ref", "Payment_Note", "Payment_Date",
                            array("db" => "is_pending",  "formatter" => function($d, $row) {
                        $Statuses = [   CommonLanguage::getMessage('settled')."#label-info",CommonLanguage::getMessage('pending')."#label-warning"];
                        return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
                    }),
                         array("db" => "Payment_Auto_ID",
                               "formatter" => function($d, $row) {
                                   $options = [
                                       [
                                           "title" => CommonLanguage::getMessage("view"),
                                           "class" => "View openFrame",
                                           "icon" => "fa-eye",
                                           "permission" =>$_GET['is_return']?
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'view_actual_return_receipt' : 'view_actual_return_payment') : ($_GET['Is_Receipt'] ? 'view_return_receipt' : 'view_return_payment')):
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'ViewReceiptActual' : 'ViewPaymentActual') : ($_GET['Is_Receipt'] ? 'ViewReceipt' : 'ViewPayment')),
                                           // "href" => "ACC/ViewReceipt" . ($_GET['Is_Receipt'] ? '/Receipt' : '' ) . ($_GET['Is_Actual'] ? '/act/' : '/') . $d . '/' . $row['payment_prefix'],
                                           "attr" => "data-src='ACC/ViewReceipt" . ($_GET['Is_Receipt'] ? '/Receipt' : '' ).($_GET['is_return'] ? '/return' : '' ) . ($_GET['Is_Actual'] ? '/act/' : '/') . $d . "'"
                                       ],[
                                           "title" => CommonLanguage::getMessage("copy"),
                                           "class" => "View",
                                           "icon" => "fa-copy",
                                           "permission" =>$_GET['is_return']?
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'copy_actual_return_receipt' : 'copy_actual_return_payment') : ($_GET['Is_Receipt'] ? 'copy_return_receipt' : 'copy_return_payment')):
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'copy_actual_receipt' : 'copy_actual_payment') : ($_GET['Is_Receipt'] ? 'copy_receipt' : 'copy_payment')),
                                           // "href" => "ACC/ViewReceipt" . ($_GET['Is_Receipt'] ? '/Receipt' : '' ) . ($_GET['Is_Actual'] ? '/act/' : '/') . $d . '/' . $row['payment_prefix'],
                                           "href" => "ACC/addpayment/copy" . ($_GET['Is_Receipt'] ? '/Receipt' : '' ).($_GET['is_return'] ? '/return' : '' ) . ($_GET['Is_Actual'] ? '/act/' : '/') . $d
                                       ]
                                   ];
                                   if ((smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer'])) && empty($row['payment_app_id']) && empty($row['subscription_fees_id'])) {
                                       $options[] = [
                                           "title" => CommonLanguage::getMessage("Delete"),
                                           "class" => "delete_pay",
                                           "icon" => "fa-trash",
                                           "attr" => " data-inv-linked='" . (!empty($_GET['tmp__all_ids'][$row['Payment_Auto_ID']]) ? 1 : 0) . "'  data-prefix='{$row['payment_prefix']}' data-payment-app-id='{$row['payment_app_id']}' data-subscription-fees-id={$row['subscription_fees_id']}",
                                           "permission" => $_GET['is_return'] ? 
                                           $_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'delete_actual_return_receipt' : 'delete_actual_return_payment') : ($_GET['Is_Receipt'] ? 'delete_return_receipt' : 'delete_return_payment') : 
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'delete_act_receipt' : 'delete_act_payment') : ($_GET['Is_Receipt'] ? 'delete_receipt' : 'delete_payment'))
                                       ];
                                       //                                       if (empty($row['pos_customer_id'])) {
                                       $options[] = [
                                           "title" => CommonLanguage::getMessage("Edit"),
                                           "class" => "Edit",
                                           "icon" => "fa-pencil",
                                           "permission" => $_GET['is_return'] ? 
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'edit_actual_return_receipt' : 'edit_actual_return_payment') : ($_GET['Is_Receipt'] ? 'edit_return_receipt' : 'edit_return_payment')) :
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'EditReceiptActual' : 'EditPaymentActual') : ($_GET['Is_Receipt'] ? 'EditReceipt' : 'amendPaymentAccount')),
                                           "href" => "ACC/addpayment" . ($_GET['Is_Receipt'] ? '/Receipt' : '' ).($_GET['is_return'] ? '/return' : '' ) . ($_GET['Is_Actual'] ? '/act/' : '/') . $d
                                       ];
                                       
                                       //                                       }

                                   }
                                   if(empty($row['payment_app_id']) && empty($row['payment_app_id']) && empty($row['subscription_fees_id'])){
                                        $options[] = ["title" => CommonLanguage::getMessage($_GET['Is_Actual'] == 1 ? "to_official" : "to_actual"),
                                            "class" => "change_actual",
                                            "permission" => $_GET['is_return'] ? 
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'convert_act_ret_receipt_to_official' : 'convert_act_ret_payment_to_official') : ($_GET['Is_Receipt'] ? 'convert_ret_receipt_to_actual' : 'convert_ret_payment_to_actual')) :
                                           ($_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'convert_act_receipt_to_official' : 'convert_act_payment_to_official') : ($_GET['Is_Receipt'] ? 'convert_receipt_to_actual' : 'convert_payment_to_actual')),
                                            "icon" => "fa-retweet"];

                                       }
                                   $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                                  "ActionOption" => $options
                                                                 ]);
                                   return $html;
                               }
                              ), "payment_prefix", "pos_customer_id", "payment_app_id", "is_main_transfer", "subscription_fees_id"
                        );
        $key = "Payment_Auto_ID";
        $table = "payment_list";
        $row_cb = array();
        //        if ($_GET['Is_Receipt'] == 1) {
        $row_cb = ['fetch_row_callback' => ['ft' => [$this, 'pay_rec_list_ftch_row']]
                   , 'fetch_all_callback' => ['ft' => [$this, 'pay_rec_list_ftch_all']]];
        //        }
        //        $row_cb['is_debug']=1;
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition, null, null, $row_cb);
        echo json_encode($data);
    }

    public function pay_rec_list_ftch_row(&$data, &$row) {
        $_GET['tmp__all_ids'][$row['Payment_Auto_ID']] = false;
    }

    public function pay_rec_list_ftch_all(&$data) {
        if (empty($_GET['tmp__all_ids']))
            return true;
        $query = $this->db->query('SELECT record_id FROM tbl_invoice_payments
            where record_id in (' . implode(',', array_keys($_GET['tmp__all_ids'])) . ') and type in ("rec","pay")');
        while ($row = $this->db->assoc($query)) {
            $_GET['tmp__all_ids'][$row['record_id']] = true;
        }
    }
    public function get_total_payments_receipt(){
        $data = $this->_registry->payment->setData($_GET)->get_total_payments_receipt();
        die($data);
    }

    public function scheduleBillsList() {
        $condition = ' is_actual= "' . $_GET['is_actual'] . '" AND current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['bill_date_from']) && isset($_GET['bill_date_to'])) {
            $FromDate = $_GET['bill_date_from'];
            $ToDate = $_GET['bill_date_to'];
            $condition .= 'and  bill_date between "' . $FromDate . '" AND "' . $ToDate . '"';
        }
        if (is_numeric($_GET['customer_id']))
            $condition .= ' and customer_id ="' . $_GET['customer_id'] . '"';
        $columns = array("bill_nb", "Customer_Name", "bill_date", "start_date",
                         array("db" => "main_total", "dt" => 4,
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber($d - $row['first_bill']) . ' ' . $row['Currency_Symbol'];
                               }
                              ), "nb_of_bills",
                         array("db" => "bill_id", "dt" => 6,
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber(Payment::getScheduleBillPaidAmount($d)) . ' ' . $row['Currency_Symbol'];
                               }
                              ),
                         array("db" => "first_bill", "dt" => 7,
                               "formatter" => function($d, $row) {
                                   $paid_amount = Payment::getScheduleBillPaidAmount($row['bill_id']);
                                   return CommonFunctions::formatNumber($row['main_total'] - $row['first_bill'] - $paid_amount) . ' ' . $row['Currency_Symbol'];
                               }
                              ),
                         "bill_description",
                         array("db" => "bill_id", "dt" => 9,
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(["color" => "complete",
                                                                  "isDropDown" => true,
                                                                  "data_id" => $d,
                                                                  "ActionOption" => [
                                                                      ["title" => CommonLanguage::getMessage("view"),
                                                                       "class" => "View openFrame",
                                                                       "icon" => "fa-eye",
                                                                       "permission" => "view_schedule_bills",
                                                                       "attr" => "data-src='ACC/view_schedule_bills/{$d}'"
                                                                      ],
                                                                      ["title" => CommonLanguage::getMessage("Edit"),
                                                                       "class" => "Edit",
                                                                       "icon" => "fa-pencil",
                                                                       "permission" => "edit_schedule_bills",
                                                                       "href" => "ACC/schedule_bills/{$d}"
                                                                      ],
                                                                      ["title" => CommonLanguage::getMessage("Delete"),
                                                                       "class" => "delete",
                                                                       "icon" => "fa-trash",
                                                                       "permission" => "delete_schedule_bills"
                                                                      ]
                                                                  ]
                                                                 ]);
                                   return $html;
                               }
                              ), "Currency_Symbol");
        $key = "bill_id";
        $table = "schedule_bills_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function PaymentDueDates() {
        $condition = '';
        $IsReceipt = '';
        $year_id = $_GET['Is_Actual'] ? $this->year_id_actual : $this->year_id;
        if (isset($_GET['Payment_Date_From']) && isset($_GET['Payment_Date_To'])) {
            $IsReceipt = $_GET["Is_Receipt"];
            $FromDate = $_GET['Payment_Date_From'];
            $ToDate = $_GET['Payment_Date_To'];
            $condition .= ' Payment_Due_Date >= "' . $FromDate . '" AND Payment_Due_Date <= "' . $ToDate . '"';
        }
        if (isset($_GET['is_pending'])) {
            //            echo $_GET['is_pending'].'==';
            if ($_GET['is_pending'] == '1') {
                $condition.=' and is_pending=1';
            }
        }
        if (isset($_GET['is_check'])) {
            if ($_GET['is_check'] == 1) {
                $condition.=' and Cheque_Number <> "" ';
            }
        }
        $condition .= ' AND Status_ID= "' . $_GET['Is_Actual'] . '" AND current_year_id = "' . $year_id . '" and is_return =0 ';
        $condition .= $IsReceipt ? ' AND IsReceipt = 1' : ' AND IsReceipt = 0';
        //        echo $condition.'==';
        $columns = array(
            array("db" => "Payment_ID", "formatter" => function($d, $row) {
                if ($row['is_pending'] == 1)
                    return '<input type="checkbox" class="change_status" data-id="' . $row['Payment_Auto_ID'] . '"/>&nbsp;' . $d;
                else
                    return $d;
            }),
            array("db" => "Account_Name", "formatter" => function($d, $row) {
                return $d . ' - ' . $row['Account_Code'];
            }), "Cheque_Number",
            array("db" => "Payment_Amount", "dt" => 3, "formatter" => function($d, $row) {
                return $row['Currency_Symbol'] . ' ' . CommonFunctions::public_round_number($d);
            }), "Payment_Type_Name", "Payment_Due_Date", "Payment_Note",
            array("db"=>"is_pending","formatter"=>function($d,$row){
                return '<span class="label label-' . ($d == 1 ? 'warning' : ($row['is_returned'] ==1 ? 'danger':'success')) . '">' . CommonLanguage::getMessage($d == 1 ? 'pending' : ($row['is_returned'] ==1 ? 'returned': 'settled')) . '</span>';

            }),
            array("db" => "Payment_Auto_ID", "formatter" => function($d, $row) {
                $options=[
                    ["title" => CommonLanguage::getMessage("Edit"),
                     "class" => "Edit",
                     "icon" => "fa-pencil",
                     "permission" => $_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'EditReceiptActual' : 'EditPaymentActual') : ($_GET['Is_Receipt'] ? 'EditReceipt' : 'amendPaymentAccount'),
                     "href" => "ACC/addpayment/" . ($_GET["Is_Receipt"] == 1 ? 'Receipt/' : '') . ($_GET['Is_Actual'] == 1 ? 'act/' : '') . $d
                    ]];
                if($row['is_returned']==0 && $row['is_pending']==0){
                    $options[]=["title" => CommonLanguage::getMessage("return"),
                                "class" => "return_pay",
                                "icon" => "fa-retweet",
                                "permission" => $_GET['Is_Actual'] == 1 ? ($_GET['Is_Receipt'] ? 'add_actual_return_receipt' : 'add_actual_return_payment') : ($_GET['Is_Receipt'] ? 'add_return_receipt' : 'add_return_payment'),
                                "href" => "ACC/addpayment/return/detail/" . ($_GET["Is_Receipt"] == 1 ? 'Receipt/' : '') . ($_GET['Is_Actual'] == 1 ? 'act/' : '') . $row['payment_detail_id']

                               ];
                    if($_GET['Is_Receipt']){
                        $options[]=["title" => CommonLanguage::getMessage("collect"),
                                    "class" => "collect_pay",
                                    "icon" => "fa-check",
                                    "attr"=>" data-id='".$row['payment_detail_id']."' ",
                                    "permission" => $_GET['Is_Actual'] == 1 ?  'act_collect_receipt' : 'collect_receipt',

                                   ];
                        $options[]=["title" => CommonLanguage::getMessage("payment"),
                                    "class" => "to_pay",
                                    "href"=>"ACC/addpayment/collect/". ($_GET['Is_Actual'] == 1 ? 'act/' : '') . $row['payment_detail_id'],
                                    "icon" => "fa-money",
                                    "permission" => $_GET['Is_Actual'] == 1 ?  'act_receipt_to_payment' : 'receipt_to_payment',

                                   ];
                    }
                }
                $html = Forms::action_snippet(["color" => "complete",
                                               "isDropDown" => true,
                                               "data_id" => $d,
                                               "ActionOption" => $options
                                              ]);
                return $html;
            }),
            "Account_Code", "Currency_Symbol", "Payment_Auto_ID","payment_detail_id","is_returned"
        );
        $key = "Payment_ID";
        $table = "payment_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function ContraListRequest() {
        $condition = '';
        if (isset($_GET['Contra_List_Date_From']) && isset($_GET['Contra_List_Date_To'])) {
            $FromDate = $_GET['Contra_List_Date_From'];
            $ToDate = $_GET['Contra_List_Date_To'];
            $condition .= ' Contra_Date >= "' . $FromDate . '" AND Contra_Date <= "' . $ToDate . '"';
        }
        $columns = array(
            array("db" => "T_FROM", "dt" => 0),
            array("db" => "Transfer_Amount", "dt" => 1),
            array("db" => "T_TO", "dt" => 2),
            array("db" => "Transfered_Amount", "dt" => 3),
            array("db" => "Contra_Date", "dt" => 4),
            array("db" => "Contra_Note", "dt" => 5)
        );
        $condition .= ' AND current_year_id = "' . $this->year_id . '"';
        $key = "Contra_ID";
        $table = "contra_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function ExpenseListRequest() {
        //        $year_id = $_GET['Is_Actual'] ? $this->year_id_actual : $this->year_id;
        $condition = '';
        if (isset($_GET['Expense_List_Date_From']) && isset($_GET['Expense_List_Date_To'])) {
            $FromDate = $_GET['Expense_List_Date_From'];
            $ToDate = $_GET['Expense_List_Date_To'];
            $condition = ' Expense_Date >= "' . $FromDate . '" AND Expense_Date <= "' . $ToDate . '"';
        }

        if($this->_registry->permissions->hasPermission('Branches')){
            $condition .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $condition .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        if(isset($_GET['is_pending']))
            $condition.=' and is_pending = "'.$_GET['is_pending'].'" ';
        if(isset($_GET['is_cash']))
            $condition.=' and is_cash = "'.$_GET['is_cash'].'" ';
        if(!empty($_GET['search_note']))
            $condition.=' and Expense_Note like "%'.$_GET['search_note'].'%" ';
        $condition .= ' AND Is_Hidden = "' . $_GET['Is_Actual'] . '" AND current_year_id = "' . $this->year_id . '"';
        $columns = array(array("db"=>"expense_nb","formatter"=>function($d,$row){
                    return '<input type="checkbox" data-id="' . $row['Expense_ID'] . '" data-nb="' . $d . '"  class="del_td pull-left multi_delete"/>' . $d;
               
        }), "Supplier_Name","Expense_Date","Expense_Note", 
                         array("db" => "Expense_Total_Price",  "formatter" => function($d, $row) {
                             return $row["Currency_Symbol"] . ' ' . CommonFunctions::public_round_number($d);
                         }),
                         array("db" => "Expense_VAT",  "formatter" => function($d, $row) {
                             return $row["Currency_Symbol"] . ' ' . CommonFunctions::public_round_number($d);
                         }),
                         array("db" => "Expense_VAT",  "formatter" => function($d, $row) {
                             return $row["Currency_Symbol"] . ' ' . CommonFunctions::public_round_number($d + $row["Expense_Total_Price"]);
                         }),
                         array("db" => "Expense_ID", 
                               "formatter" => function($d,$row) {
                                   $options_arr = [
                                       [
                                           "title" => CommonLanguage::getMessage("view"),
                                           "class" => "View openFrame",
                                           "permission" => ($_GET['Is_Actual'] == 1 ? ($row['is_pending']==1 ? ($row['is_cash']==1 ? "view_act_pending_cash_expense":"view_act_pending_expense"): ($row['is_cash']==1 ? "view_act_cash_expense":"view_expense_actual")) : ($row['is_pending']==1 ? ($row['is_cash']==1 ? "view_pending_cash_expense":"view_pending_expense"):($row['is_cash']==1 ? "view_cash_expense":"view_expense"))),
                                           "icon" => "fa-eye",
                                           "attr" => "data-src='ACC/view_expense/{$d}?is_pop=1'"
                                       ],
                                       [
                                           "title" => CommonLanguage::getMessage("Edit"),
                                           "class" => "edit",
                                           "permission" => ($_GET['Is_Actual'] == 1 ?  ($row['is_pending']==1 ? ($row['is_cash']==1 ? "edit_act_pending_cash_expense":"edit_act_pending_expense"):($row['is_cash']==1 ? "edit_act_cash_expense":"amendExpensesActual")) : ($row['is_pending']==1 ? ($row['is_cash']==1 ? "edit_pending_cash_expense":"edit_pending_expense"):($row['is_cash']==1 ? "edit_cash_expense":"amendExpenses"))),
                                           "icon" => "fa-pencil",
                                           "href" => "ACC/add_expense/" . ($_GET['Is_Actual'] ? 'act/' : '') .($row['is_pending']==1 ? 'pen/' : ''). $d
                                       ],
                                       [
                                           "title" => CommonLanguage::getMessage("Delete"),
                                           "class" => "delete_exp",
                                           "permission" => ($_GET['Is_Actual'] == 1 ? ($row['is_pending']==1 ? ($row['is_cash']==1 ? "delete_act_pending_cash_expense":"delete_act_pending_expense"):($row['is_cash']==1 ? "delete_act_cash_expense":"delete_act_expense")) : ($row['is_pending']==1 ? ($row['is_cash']==1 ? "delete_cash_expense":"delete_pending_expense"):($row['is_cash']==1 ? "delete_cash_expense":"delete_expense"))),
                                           "icon" => "fa-trash"
                                       ],
                                       [
                                           "title" => CommonLanguage::getMessage($_GET['Is_Actual'] == 1 ? "to_official" : "to_actual"),
                                           "class" => "change_actual",
                                           "permission" => ($_GET['Is_Actual'] == 1 ? ($row['is_pending']==1 ? ($row['is_cash']==1 ? "convert_act_pending_cash_expense_to_official":"convert_act_pending_expense_to_official"):($row['is_cash']==1 ? "convert_act_cash_expense_to_official":"convert_expense_to_official")) : ($row['is_pending']==1 ? ($row['is_cash']==1 ? "convert_pending_cash_expense_to_act":"convert_pending_expense_to_actual"):($row['is_cash']==1 ? "convert_cash_expense_to_act":"convert_expense_to_actual"))),
                                           "icon" => "fa-retweet"
                                       ]
                                   ];
                                   if($row['is_pending']==1){
                                       $options_arr[] = [
                                           "title" => CommonLanguage::getMessage("settle"),
                                           "class" => "settle_exp",
                                           "permission" => ($_GET['Is_Actual'] == 1 ? ($row['is_cash']==1 ? "settle_act_pending_cash_expense":"settle_act_expense") : ($row['is_cash']==1 ? "settle_pending_cash_expense":"settle_expense")),
                                           "icon" => "fa-money"
                                       ];
                                   }
                                   $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                                  "ActionOption" => $options_arr
                                                                 ]);
                                   return $html;
                               }
                              ),"Currency_Symbol","is_pending","is_cash"
                        );
        $key = "Expense_ID";
        $table = "expenses_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }
    public function get_total_expenses(){
        $data = $this->_registry->expense->setData($_GET)->get_total_expense_list();
        die($data);
    }

    //            public function addExpense() {
    //                if (isset($_POST["PurchaseInvoiceDate"])) {
    //                    $logged_id = Session::getUserID();
    //                    $_POST['Expenses'] = json_decode($_POST["Expenses"], true);
    //                    array_push($_POST, $logged_id);
    //                    $is_actual = $_POST['Is_Actual'] ? true : false;
    //                    $result = $this->_registry->expense->setData($_POST)->create($is_actual);
    //                    die(empty($result) ? "success" : $result[0]);
    //                }
    //            }
    public function add_expense() {
        $result = $this->_registry->expense->setData($_POST)->add_expense();
        die(json_encode(is_numeric($result[0]) ? ["success",$result[0],$result[1]] : $result[0]));
    }

    public function edit_expense() {
        $result = $this->_registry->expense->setData($_POST)->edit_expense();
        die(json_encode(is_numeric($result[0]) ? ["success",$result[0],$result[1]] : $result[0]));
    }

    public function addPayment() {
        if (isset($_POST["Account_Code"])) {
            $RET = $this->_registry->payment->setData($_POST)->create(true);
            die(json_encode(is_numeric($RET[0]) ? ['OK', $RET[0], $RET[1], $RET[2]] : $RET));
        }
    }

    public function addContra() {
        if (isset($_POST["Transfer_Amount"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->contra->setData($_POST)->create();
            die(empty($RET) ? "success" : $RET[0]);
        }
    }

    public function createCurrencySettings() {
        $create = true;
        if (isset($_POST["Currency"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $create = $this->_registry->currency->setdata($_POST)->updateCurrency();
        }
        if (isset($_POST["AddCurrency"])) {
            $logged_id = @Session::getUserID();
            array_push($_POST, $logged_id);
            $create = $this->_registry->currency->setdata($_POST)->createCurrency();
        }
        if (isset($_POST['ExRate'])) {
            $logged_id = @Session::getUserID();
            array_push($_POST, $logged_id);
            $create = $this->_registry->currency->setdata($_POST)->createExRate();
        }
        die(empty($create) ? 'success' : 'error');
    }

    public function DebitListRequest() {
        $condition = ' current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['Date_From']) && isset($_GET['Date_To'])) {
            $condition .= ' and Note_Date >= "' . $_GET['Date_From'] . '" AND Note_Date <= "' . $_GET['Date_To'] . '"';
        }
        if (isset($_GET['is_actual'])) {
            $condition .= ' and is_actual = "' . $_GET['is_actual'] . '"';
        }
        
        if($this->_registry->permissions->hasPermission('Branches')){
            $condition .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $condition .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        
        $columns = array(
            array("db" => "note_nb", "dt" => 0),
            array("db" => "Name", "dt" => 1),
            array("db" => "Note_Date", "dt" => 2),
            array("db" => "Note_Amount_Curr", "dt" => 3),
            array("db" => "Note_Description", "dt" => 4),
            array("db" => "Note_ID", "dt" => 5,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(["color" => "complete",
                                                     "isDropDown" => true, "data_id" => $d,
                                                     "ActionOption" => [
                                                         [
                                                             "title" => CommonLanguage::getMessage("Edit"),
                                                             "class" => "edit",
                                                             "icon" => "fa-pencil",
                                                             "permission" => ($_GET['is_actual'] == 1 ? ($_GET['Is_Debit_Note'] == 1 ? "EditActualDebitNote" : "EditActualCreditNote") : ($_GET['Is_Debit_Note'] == 1 ? "EditDebitNote" : "EditCreditNote")),
                                                             "href" => "ACC/DebitNote/" . (($_GET['Is_Debit_Note'] == 0) ? '' : 'vendor/' ) . ($_GET['is_actual'] ? 'act/' : '') . $d
                                                         ],
                                                         [
                                                             "title" => CommonLanguage::getMessage("view"),
                                                             "class" => "View",
                                                             "icon" => "fa-eye",
                                                             "permission" => ($_GET['is_actual'] == 1 ? ($_GET['Is_Debit_Note'] == 1 ? "view_debit_note_actual" : "view_credit_note_actual") : ($_GET['Is_Debit_Note'] == 1 ? "view_debit_note" : "view_credit_note")),
                                                             "href" => "ACC/ViewNote/" . (($_GET['Is_Debit_Note'] == 1) ? '' : 'credit/' ) . $d
                                                         ],
                                                         [
                                                             "title" => CommonLanguage::getMessage("Delete"),
                                                             "class" => "delete_cre",
                                                             "icon" => "fa-trash",
                                                             "permission" => ($_GET['is_actual'] == 1 ? ($_GET['Is_Debit_Note'] == 1 ? "delete_debit_note_actual" : "delete_credit_note_actual") : ($_GET['Is_Debit_Note'] == 1 ? "delete_debit_note" : "delete_credit_note")),
                                                         ]
                                                     ]
                                                    ]);
                      return $html;
                  }
                 )
        );
        $key = "Note_ID";
        if ($_GET['Is_Debit_Note'] == 1)
            $table = "debit_list";
        else
            $table = "credit_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function DebitListPerCustomerRequest() {
        $condition = ' current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['id'])) {
            $condition .= 'AND Account_ID = "' . $_GET['id'] . '" ORDER BY Transaction_ID DESC';
        }
        $columns = array(
            array("db" => "JV_ID", "dt" => 0),
            array("db" => "Transaction_Type", "dt" => 1),
            array("db" => "Transaction_Date", "dt" => 2),
            array("db" => "Transaction_Amount", "dt" => 3, "formatter" => function($d, $row) {
                return $d . ' ' . $row[5];
            }),
            array("db" => "Transaction_Description", "dt" => 4),
            array("db" => "Currency_Symbol", "dt" => 5),
        );
        $key = "Transaction_ID";
        $table = "transactions_info";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function editDebitNote() {
        if (isset($_POST["Is_Debit_Note"])) {
            $update = $this->_registry->debitnote->setData($_POST)->editdebitnote();
            die(empty($update) ? 'OK' : $update[0]);
        }
    }

    public function addDebitNote() {
        if (isset($_POST["Is_Debit_Note"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $create = $this->_registry->debitnote->setData($_POST)->create();
            die(empty($create) ? 'OK' : $create[0]);
        }
        if (isset($_GET['id'])) {
            if ($_GET['mode'] === 'true') {
                $details = Customer::getCustomerByID($_GET['id'], 1, $_GET['is_actual']);
            } else {
                $details = Supplier::getSupplierByID($_GET['id'], 1, $_GET['is_actual']);
            }
            die(json_encode($details));
        }
    }

    //                    public function editExpense() {
    //                        if (isset($_POST['Account_Code']) && isset($_POST['Expense_ID'])) {
    //                            $logged_id = Session::getUserID();
    //                            array_push($_POST, $logged_id);
    //                            $Expense_Id = $_POST['Expense_ID'];
    //                            $Extension = '';
    //                            if ($_FILES['image_user']['name'] != "") {
    //                                $Fileextension = $_FILES['image_user']['name'];
    //                                $SaveAsExtention = explode(".", $Fileextension);
    //                                $Extension = $SaveAsExtention[1];
    //                            }
    //
    //                            $ret1 = $this->_registry->expense->setData($_POST)->updateExpense($Expense_Id, $Extension);
    //
    //
    //                            if ($ret1 && $_FILES['image_user']['name'] != "") {
    //                                $uploaddir = dirname(__FILE__) . '/../../uploads/expenses/';
    //                                $RET = $this->_registry->expense->setData($_POST)->SaveUploadedPhoto("image_user", $uploaddir . $Expense_Id . '.' . $Extension);
    //                            }
    //
    //                            die(empty($ret1) ? 'success' : 'error');
    //                        }
    //                    }
    public function editOrganization() {
        if (isset($_POST["Organization_Name"])) {
            $Orgs = $this->_registry->Organization->setData($_POST)->update();
            if (empty($Orgs))
                die("success");
            else
                die("error");
        }
    }
    public function org_upolad_file() {
            $RET = $this->_registry->Organization->setData($_POST)->org_upolad_file();
            die(json_encode(!is_array($RET) ? ['OK', $RET] : [$RET[0]] ));
    }


    public function ExchangeRateListRequest() {
        $condition = '';
        if (isset($_GET['Exchange_List_Date']) && isset($_GET['CheckedValue'])) {
            $Check = $_GET['CheckedValue'];
            $condition .= ' from_currency = "' . $_GET['From_Currency'] . '" AND to_currency = "' . $_GET['To_Currency'] . '" AND';
            if ($Check == 1) {
                $Year = $_GET['Exchange_List_Date'][0];
                $Month = $_GET['Exchange_List_Date'][1];
                $Day = $_GET['Exchange_List_Date'][2];
                $CurrentDate = $_GET['Exchange_List_Date'];
                $condition .= ' Exchange_Rate_Date = "' . $CurrentDate . '"';
            } else if ($Check == 2) {
                $Year = $_GET['Exchange_List_Date'][0];
                $Month = $_GET['Exchange_List_Date'][1];
                $condition .= ' MONTH(Exchange_Rate_Date) = "' . $Month . '" AND YEAR(Exchange_Rate_Date) = "' . $Year . '"';
            } else if ($Check == 3) {
                $Year = $_GET['Exchange_List_Date'][0];
                $condition .= ' YEAR(Exchange_Rate_Date) = "' . $Year . '"';
            }
        }
        if (isset($_GET['Exchange_List_Date_From']) && isset($_GET['Exchange_List_Date_To']) && isset($_GET['CheckedValue'])) {
            $condition .= ' from_currency = "' . $_GET['From_Currency'] . '" AND to_currency = "' . $_GET['To_Currency'] . '" ';
            $Check = $_GET['CheckedValue'];
            $FromDate = $_GET['Exchange_List_Date_From'];
            $ToDate = $_GET['Exchange_List_Date_To'];
            if ($Check == 4) {
                $condition .= ' AND Exchange_Rate_Date >= "' . $FromDate . '" AND Exchange_Rate_Date <= "' . $ToDate . '"';
            }
        }
        $columns = array(
            array("db" => "ExchRate", "dt" => 0),
            array("db" => "Exchange_Rate_Date", "dt" => 1)
        );
        $key = "Exchange_Rate_ID";
        $table = "exchangeratelist";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function TransactionsByJVRequest() {
        $condition = 'current_year_id = "' . $this->year_id . '"';
        if (isset($_GET['JV_ID'])) {
            $condition .= ' AND JV_ID = "' . $_GET['JV_ID'] . '" ORDER BY Transaction_ID DESC';
        }
        $columns = array(
            array("db" => "JV_ID", "dt" => 0),
            array("db" => "Transaction_Date", "dt" => 1),
            array("db" => "Transaction_Reference", "dt" => 2),
            array("db" => "Transaction_Account", "dt" => 3),
            array("db" => "Account_Name", "dt" => 4),
            array("db" => "Transaction_Type", "dt" => 5),
            array("db" => "Transaction_Amount", "dt" => 6),
            array("db" => "Transaction_Description", "dt" => 7)
        );
        $key = "Transaction_ID";
        $table = "transactions_info";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function viewPrepaidExpenseRequest() {
        $cond = ' ';
        $year_id = $_GET['is_actual'] ? $this->year_id_actual : $this->year_id;
        if (isset($_GET['Income'])) {
            if ($_GET['Income'] === "Expense") {
                $cond .= ' is_expense = 1';
            } else {
                $cond .= ' is_expense = 0';
            }
        }
        if (isset($_GET['Prepaid_Date_From'])) {
            $cond .= ' AND Start_Date >= "' . $_GET['Prepaid_Date_From'] . '" AND Start_Date <= "' . $_GET['Prepaid_Date_To'] . '"';
        }
        $cond .= ' AND Is_Actual = "' . $_GET['is_actual'] . '" AND current_year_id = "' . $year_id . '"';
        $columns = array(
            array("db" => "Prepaid_Account", "dt" => 0),
            array("db" => "Supplier_Name", "dt" => 1),
            array("db" => "Total_Amount", "dt" => 2),
            array("db" => "Amount_PerMonth", "dt" => 3),
            array("db" => "Description", "dt" => 4),
            array("db" => "Start_Date", "dt" => 5),
            array("db" => "End_Date", "dt" => 6),
            array('db' => 'Prepaid_ID',
                  'dt' => 7,
                  'formatter' => function( $d ) {
                      $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                     "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                         "class" => "EditEntry",
                                                                         "icon" => "fa-pencil",
                                                                         "href"=>"ACC/addPrepaid/" . ($_GET['Income'] === "Expense" ? '': 'Income/').($_GET['is_actual']==1 ? 'act/' : '') . $d,
                                                                         "permission" => $_GET['is_actual'] == 1 ? 'EditPrepaidExpenseActual' : 'EditPrepaidExpense'
                                                                        ],
                                                                        ["title" => CommonLanguage::getMessage("Delete"),
                                                                         "class" => "delete_prepaid",
                                                                         "icon" => "fa-trash",
                                                                         "permission" => $_GET['is_actual'] == 1 ? ($_GET['Income'] === "Expense" ? 'act_delete_prepaid_expense':'act_delete_prepaid_income'):($_GET['Income'] === "Expense" ? 'delete_prepaid_expense' : 'delete_prepaid_income')
                                                                        ]
                                                                       ]]);
                      return $html;
                  }
                 )
        );
        $key = "Prepaid_ID";
        $table = "prepaid_expense_income";
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function viewPrepaidExpenseAjax() {
        if (isset($_GET['ToEditID'])) {
            $list = $this->_registry->jv->viewPrepaidByType($_GET['EditType'], $_GET['ToEditID']);
            die(json_encode($list));
        }
    }

    public function addPrepaidAjax() {
        if (isset($_POST['Prepaid_Account'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            if (($_POST['Prepaid_ID']) == 0) {
                $ret = $this->_registry->jv->setData($_POST)->addPrepaid();
            } else {
                $ret = $this->_registry->jv->setData($_POST)->updatePrepaid();
            }
            die(empty($ret) ? "OK" : $ret[0]);
        }
    }

    public function viewDepreciation() {
        $condition = ' ';
        if (isset($_GET['DepID']))
            $condition .= '  Depreciation_Rate_ID = "' . smc_escape($_GET['DepID']) . '"';
        if (isset($_GET['DateFrom']) && isset($_GET['DateTo']))
            $condition .= ' AND Depreciation_Date >= "' . $_GET['DateFrom'] . '" AND Depreciation_Date <= "' . $_GET['DateTo'] . '" ';
        $columns = array(
            array("db" => "Depreciation_Date", "dt" => 0),
            array("db" => "Depreciation_Amount", "dt" => 1),
            array('db' => 'Is_Done', 'dt' => 2,
                  'formatter' => function($d) {
                      $Statuses = [CommonLanguage::getMessage('pending') . "#label-warning", CommonLanguage::getMessage('done') . "#label-info"];
                      return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
                  }),
        );
        $key = "Depreciation_Date_ID";
        $table = "fixed_assets_register";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function viewDepositeWithDrawalActual() {
        $year_id = $_GET['hidden'] ? $this->year_id_actual : $this->year_id;
        $condition = ' ';
        if (isset($_GET['DW_List_Date_From'])) {
            $condition .= ' Deposit_WithDrawal_Date >= "' . $_GET['DW_List_Date_From'] . '" AND Deposit_WithDrawal_Date <= "' . $_GET['DW_List_Date_To'] . '"';
        }
        $condition .= ' AND Is_Hidden = "' . $_GET['hidden'] . '" and current_year_id = "' . $year_id . '"';
        $columns = array(
            array('db' => 'dw_nb', "formatter" => function($d, $row) {
                    return '<input type="checkbox" data-id="' . $row['Deposit_WithDrawal_ID'] . '" data-nb="' . $d . '" class="del_td pull-left multi_delete"/>' . $d;
            }),"T_FROM",array('db' => 'Deposit_WithDrawal_Amount', "formatter" => function($d, $row) {
                return  CommonFunctions::public_round_number($d);
            }),"T_TO",array('db' => 'Deposit_WithDrawal_Amount_To', "formatter" => function($d, $row) {
                return  CommonFunctions::public_round_number($d);
            }),"Deposit_WithDrawal_Description", 
            "Deposit_WithDrawal_Date",
            array('db' => 'Deposit_WithDrawal_ID',
                  'formatter' => function( $d, $row ) {
                      $options = [
                          ["title" => CommonLanguage::getMessage("View"),
                           "class" => "view",
                           "icon" => "fa-eye",
                           "permission" => (($_GET['hidden'] == 1) ? "viewDepositeWithDrawalActual" : "viewDepositeWithDrawal"),
                           "href" => "ACC/view_deposit_withdrawal/" . $d
                          ]
                      ];
                      if (empty($row['app_dep_id']) && (smc_session()['default_setting']['activate_edit_after_sync'] == 1 || empty($row['is_main_transfer']))) {
                          $options[] = ["title" => CommonLanguage::getMessage("Edit"),
                                        "class" => "EditEntry",
                                        "permission" => (($_GET['hidden'] == 1) ? "editDepositWithDrawalActual" : "editDepositWithDrawal"),
                                        "icon" => "fa-pencil",
                                        "href" => "ACC/addDepositWithdrawal/" . (($_GET['hidden'] == 1) ? "act/" : "") . $d
                                       ];
                          $options[] = ["title" => CommonLanguage::getMessage("Delete"),
                                        "class" => "delete_dep",
                                        "permission" => (($_GET['hidden'] == 1) ? "delete_act_dep_with" : "delete_dep_with"),
                                        "icon" => "fa-trash"
                                       ];
                            
                      }
                      if( empty($row['invoice_app_id'])){
                                $options[] = ["title" => CommonLanguage::getMessage($_GET['hidden'] == 1 ? "to_official" : "to_actual"),
                                                 "class" => "change_actual",
                                                 "permission" =>($_GET['hidden'] == 1 ? "convert_act_deposit_to_official" : "convert_deposit_to_actual"),
                                                 "icon" => "fa-retweet"];
                            }

                      $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                     "ActionOption" => $options]);
                      return $html;
                  }), 'app_dep_id', 'is_main_transfer'
        );
        $key = "Deposit_WithDrawal_ID";
        $table = "deposite_withdrawal";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function viewBankAccountRequest() {
        $columns = array(
            array("db" => "Bank_Name", "dt" => 0),
            array("db" => "Bank_Account_Name", "dt" => 1),
            array("db" => "Bank_Account_Number", "dt" => 2),
            array("db" => "Credit_Card_Number", "dt" => 3),
            array("db" => "Currency_Name", "dt" => 4)
                       ,array(
                                'db' => 'Bank_Account_ID',
                                'dt' => 5,
                                'formatter' => function( $d, $row ) {
                                    $html = Forms::action_snippet(["color" => "primary",
                                                "data_id" => $d,
                                                "isDropDown" => true,
                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                "class" => "EditBank",
                                                "icon" => "fa-pencil",
                                                "data-target" => "#add_AccountBank",
                                                "permission" => "editBankAccount"
                                                    ] 
                                    ]]);
                                    return $html;
                                }
                        )
        );
        $key = "Bank_Account_ID";
        $table = "bank_list";
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function viewAccruedExpenseRequest() {
        $cond = ' ';
        $year_id = $_GET['is_actual'] ? $this->year_id_actual : $this->year_id;
        if (isset($_GET['Acrrued_Expense_From'])) {
            $cond .= '  Start_Date >= "' . $_GET['Acrrued_Expense_From'] . '" AND Start_Date <= "' . $_GET['Acrrued_Expense_To'] . '"';
        }
        $cond .= ' AND Is_Actual = "' . $_GET['is_actual'] . '" AND current_year_id = "' . $year_id . '"';
        $columns = array(
            array("db" => "Accrued_Code", "dt" => 0),
            array("db" => "Supplier_Name", "dt" => 1),
            array("db" => "Expected_Amount", "dt" => 2),
            array("db" => "Real_Amount", "dt" => 3),
            array("db" => "Description", "dt" => 4),
            array("db" => "Start_Date", "dt" => 5),
            array("db" => "End_Date", "dt" => 6),
            array('db' => 'Accrued_Expense_ID',
                  'dt' => 7,
                  'formatter' => function( $d, $row) {
                      $html = "<div class='btn-group Action' data-id='{$d}' >";
                      if (($this->_registry->permissions->hasPermission('payForAccruedExpense') && $_GET['is_actual'] == 0) || ($this->_registry->permissions->hasPermission('payForAccruedExpenseActual') && $_GET['is_actual'] == 1)) {
                          $html .= "<a style='opacity: 1;' href='#' data-toggle='modal' class='btn btn-complete payAmount " . ($row[8] == 1 ? 'disabled' : '') . "' data-target='#payForAccruedExpense'><i class='fa fa-dollar'></i></a>";
                      }if (($this->_registry->permissions->hasPermission('EditAccruedExpense') && $_GET['is_actual'] == 0) || ($this->_registry->permissions->hasPermission('EditAccruedExpenseActual') && $_GET['is_actual'] == 1)) {
                          $html .= "<a  style='opacity: 1;'  class='btn btn-complete EditEntry'><i class='fa fa-pencil'></i></a>";
                      }
                      $html .= "</div>";
                      return $html;
                  }
                 ),
            array("db" => "Status_ID", "dt" => 8)
        );
        $key = "Accrued_Expense_ID";
        $table = "accrued_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function viewAccruedExpenseAjax() {
        if (isset($_GET['ToEditID'])) {
            $list = $this->_registry->jv->viewAccruedExpense($_GET['ToEditID']);
            die(json_encode($list));
        }
    }

    public function transferJVToActualAjax() {
        if (isset($_GET['JV_ID'])) {
            $list = $this->_registry->jv->returnTransactionsByJV($_GET['JV_ID']);
            die(json_encode($list));
        }
        if (isset($_POST['JVID'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $result = $this->_registry->jv->setData($_POST)->transferJVToActual();
            die(empty($result) ? "OK" : "error");
        }
    }

    //                    public function fixedAssetsRegister() {
    //                        if (isset($_POST['DateFrom']) && isset($_POST['DateTo'])) {
    //                            $Ret = $_POST['actual'] ? $this->_registry->report->viewDepreciationMainDetails($_POST['DateFrom'], $_POST['DateTo'], true) : $this->_registry->report->viewDepreciationMainDetails($_POST['DateFrom'], $_POST['DateTo'], false);
    //                            die(json_encode($Ret));
    //                        }
    //                    }
    public function transferJVListRequest() {
        $cond = '';
        if (isset($_GET['Transfer_Date_From'])) {
            $cond .= '  Transfer_Date >= "' . $_GET['Transfer_Date_From'] . '" AND Transfer_Date <= "' . $_GET['Transfer_Date_To'] . '"';
        }
        $columns = array(
            array("db" => "Old_JV_ID", "dt" => 0),
            array("db" => "New_JV_ID", "dt" => 1),
            array("db" => "Transfer_Date", "dt" => 2),
            array("db" => "Transfer_Description", "dt" => 3),
            array("db" => "Employee_Name", "dt" => 4)
        );
        $key = "Transfer_ID";
        $table = "transfer_jvs_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function payForAccruedExpenseAjax() {
        if (isset($_POST['Real_Amount'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->jv->setData($_POST)->payForAccruedExpense();
            die(empty($RET) ? "OK" : "error");
        }
    }

    public function mergeAccountsAjax() {
        if (isset($_POST['Merged_On'])) {
            $_POST['is_actual'] = 0;
            $ret = $this->_registry->jv->setData($_POST)->mergeAccounts();
            die($ret ? "success" : "error");
        }
    }

    public function addOrganizationAjax() {
        if (isset($_POST["Organization_Name"])) {
            $org = $this->_registry->Organization->setData($_POST)->create();
            die(print_r($org));
            die($org ? "OK" : "error");
        }
    }

    public function addJVAjax() {
        if (isset($_POST["Transaction_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            if ($_POST['is_actual'] == 1)
                $flag = 1;
            else
                $flag = null;
            $ret = $this->_registry->jv->setData($_POST)->createTransaction($flag);
            die(json_encode(!is_array($ret) ? ["OK", $ret] : ['error', $ret[0]] ));
        }
    }

    public function adDepositeWithDrawalActualAjax() {
        if (isset($_POST['Deposit_WithDrawal_Amount'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->addDepositWithDrawal(true);
            die(is_numeric($ret[0]) ? json_encode(['ok',$ret[0]]) : $ret[0] );
        }
    }

    public function addDepositeWithDrawalAjax() {
        if (isset($_POST['Deposit_WithDrawal_Amount'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->addDepositWithDrawal();
            die(is_numeric($ret[0]) ? json_encode(['ok',$ret[0]]) : $ret[0] );
        }
    }

    public function editDepositeWithDrawalAjax() {
        if (isset($_POST['Deposit_WithDrawal_Amount'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->editDepositWithDrawal();
            die(is_numeric($ret[0]) ? json_encode(['ok',$ret[0]]) : $ret[0] );
        }
    }

    public function addBankAccountAjax() {
        if (isset($_POST["Credit_Card_Number"])) {
            $logged_id = @Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->bank->setData($_POST)->addNew();
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }
    public function updateBankAccountAjax() {
        if (isset($_POST["Credit_Card_Number"])) {
            $logged_id = @Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->bank->setData($_POST)->updateInfo($_POST['Bank_Account_ID']);
            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }

    public function addAccruedExpenseAjax() {
        if (isset($_POST['AccruedlExpense_Code']) && !$_POST['ifEdit']) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->addAccruedExpense();
            die(empty($ret) ? "OK" : $ret[0]);
        }
        if (isset($_POST['Accrued_Expense_ID']) && $_POST['ifEdit']) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->updateAccruedExpense();
            die(empty($ret) ? "OK" : $ret[0]);
        }
    }

    public function trialBalanceAjax() {
        $trialList = $this->_registry->report->trial_balance_report($_GET['data']);
        $actual = $_GET['data']['Is_Actual'] == 1 ? 1 : null;
        $form = Forms::gettrialBalance($trialList, $actual);
        die($form);
    }

    public function ledgerAjax() {
        if(isset($_GET['from_multi_accounts']) && $_GET['from_multi_accounts'] == 'yes')
            $list = $this->_registry->report->general_ledger_report($_GET);
        else
            $list = $this->_registry->report->general_ledger_report($_GET['data']);

        die(json_encode($list));
    }

    public function statement_of_job_ajax() {
        $list = $this->_registry->report->general_ledger_report($_GET['data']);
        die(json_encode($list));
    }

    public function statement_of_project_ajax() {
        $list = $this->_registry->report->general_ledger_report($_GET['data']);
        die(json_encode($list));
    }



    public function expenseReportAjax() {
        if (isset($_GET['Opening_Balance'])) {
            $from_date = $_GET['From_Date'];
            $to_date = $_GET['To_Date'];
            $currency_id = $_GET['Currency_ID'];
            $opening_balance = $_GET['Opening_Balance'];
            $accounts = empty($_GET['Expense_Accounts']) ? array() : $_GET['Expense_Accounts'];
            $defCurrencySymbol = CurrencyFactory::getCurrencySymbol($currency_id);
            $expenselist = $this->_registry->report->expenseReport($from_date, $to_date, $accounts, $opening_balance, $currency_id, $_GET['is_actual']);
            die(json_encode([$expenselist, $defCurrencySymbol]));
        }
    }

    //to be fixed
    public function currencyExchangeRateAjax() {
        if (isset($_POST['Submit_Close'])) {
            $logged_id = Session::getUserID();
            $_POST['Logged_ID'] = $logged_id;
            $ret = $this->_registry->currency->submitDifferenceOfExchange($_POST);
            die(empty($ret) ? "OK" : $ret[0]);
        }
    }

    public function closeYearAjax() {
        //                                                        if (isset($_POST['Submit_Close'])) {
        $ret = $this->_registry->report->close_year($_POST['actual'], $_POST['next_year']);
        die(empty($ret) ? "OK" : $ret[0]);
        //                                                        }
    }

    public function open_financial_year() {
        $ret = $this->_registry->report->open_financial_year($_POST['year_id'], $_POST['actual']);
        die(empty($ret) ? "OK" : "error");
    }

    public function closeVATAjax() {
        if (isset($_POST['Submit_Vat'])) {
            $logged_id = Session::getUserID();
            $ret = $this->_registry->vat->closeVAT($_POST['Date'], $logged_id);
            die(empty($ret) ? "OK" : "error");
        }
    }

    public function get_close_vat_trans(){
        $data = $this->_registry->vat->viewVATTransactions($_GET['date']);
        die(json_encode($data));
    }

    public function checkAccountTransactions() {
        $ret = $this->_registry->jv->setData($_GET)->checkAccountTransactions();
        die(json_encode($ret));
    }

    public function checkJobTransactions() {
        $ret = $this->_registry->jv->setData($_GET)->checkJobTransactions();
        die(json_encode($ret));
    }

    public function IncomeStatementAjax() {
        if (isset($_GET['From_Date'])) {
            $options = ['from_date' => $_GET['From_Date'],
                        'to_date' => $_GET['To_Date'], 'currency' => $_GET['Currency_ID'],
                        'is_actual' => $_GET['actual'], 'stock_value' => $_GET['stock_value'], 'stock_type' => $_GET['stock_type'],
                        'end_stock_value' => $_GET['end_stock_value'], 'end_stock_type' => $_GET['end_stock_type'],
                        'stock_method'=>$_GET['stock_method'],'end_stock_method'=>$_GET['end_stock_method']];
            //            echo"<pre>";die(print_r($options));
            $data = $this->_registry->report->statementOfIncome($options);
            $form = Forms::incomeStatementForm($data,$options);
            die(json_encode([$form,$data]));
        }
    }

    public function StmtFinancialPosAjax() {
        if (isset($_GET['From_Date'])) {
            $options = ['from_date' => $_GET['From_Date'], 'to_date' => $_GET['To_Date'],
                        'currency' => $_GET['Currency_ID'], 'is_actual' => $_GET['actual'],
                        'stock_value' => $_GET['stock_value'], 'stock_type' => $_GET['stock_type'],
                        'end_stock_value' => $_GET['end_stock_value'], 'end_stock_type' => $_GET['end_stock_type'],
                        'stock_method'=>$_GET['stock_method'],'end_stock_method'=>$_GET['end_stock_method']];
            $data = $this->_registry->report->StmtFinancialPosition($options);
            $form = Forms::financialPosition($data,$options);
            die(json_Encode([$form,$data]));
        }
    }

    public function BalanceSheetAjax() {
        if (isset($_GET['digits'])) {
            $ActualOnly = false;
            $digits = $_GET['digits'];
            $Grouping = $_GET['Grouping'];
            $datefrom = $_GET['From_Date'];
            $dateto = $_GET['To_Date'];
            $currency_id = $_GET['Currency_ID'];
            if ($_GET['actual'] == 1) {
                $ActualOnly = $_GET['Actual_BalanceSheet'] == 1 ? true : false;
            }
            $defCurrencySymbol = CurrencyFactory::getCurrencySymbol($currency_id);
            $list = $_GET['actual'] ? $this->_registry->report->viewBalanceSheet($digits, $Grouping, $datefrom, $dateto, true, $currency_id, $ActualOnly) : $this->_registry->report->viewBalanceSheet($digits, $Grouping, $datefrom, $dateto, false, $currency_id);
            die(json_encode([$list, $defCurrencySymbol]));
        }
    }

    public function BalanceSheetTotalsAjax() {
        if (isset($_GET['digits'])) {
            $digits = $_GET['digits'];
            $Grouping = $_GET['Grouping'];
            $datefrom = $_GET['From_Date'];
            $dateto = $_GET['To_Date'];
            $currency_id = $_GET['Currency_ID'];
            $defCurrencySymbol = CurrencyFactory::getCurrencySymbol($currency_id);
            $list = $_GET['actual'] ? $this->_registry->report->viewBalanceSheet($digits, $Grouping, $datefrom, $dateto, false, $currency_id) : $this->_registry->report->viewBalanceSheet($digits, $Grouping, $datefrom, $dateto, true, $currency_id);
            die(json_encode([$list, $defCurrencySymbol]));
        }
    }

    //                    public function DailyJournalsAjax() {
    //                        if (isset($_GET["From_Date"])) {
    //                            $DateFrom = ($_GET["From_Date"] == 0) ? null : $_GET["From_Date"];
    //                            $DateTo = ($_GET["To_Date"] == 0) ? null : $_GET['To_Date'];
    //                            $JVFrom = ($_GET["From_JV"] == 0) ? null : $_GET['From_JV'];
    //                            $JVTo = ($_GET["To_JV"] == 0) ? null : $_GET['To_JV'];
    //                            $DailyList = $_GET['actual'] ? $this->_registry->report->retrieveDailyJVsByRange($DateFrom, $DateTo, $JVFrom, $JVTo, true) : $this->_registry->report->retrieveDailyJVsByRange($DateFrom, $DateTo, $JVFrom, $JVTo);
    //                            die(json_encode($DailyList));
    //                        }
    //                    }
    public function topSuppliersAjax() {
        if (isset($_GET['From_Date'])) {
            $data = ["is_supplier" => 1, "date_from" => $_GET['From_Date'], "date_to" => $_GET['To_Date'], "limit" => $_GET['limit'], "currency" => smc_session()['local_currency'], "type" => "Credit", "is_leb" => $_GET['is_leb'], "accounts" => $_GET['accounts']];
            $result = $this->_registry->report->viewTopSuppCust($data);
            die(json_encode($result));
        }
    }

    public function topCustomersAjax() {
        if (isset($_GET['From_Date'])) {
            $data = ["is_supplier" => 0, "date_from" => $_GET['From_Date'], "date_to" => $_GET['To_Date'], "limit" => $_GET['limit'], "currency" => smc_session()['local_currency'], "type" => "Debit", "is_leb" => $_GET['is_leb'], "accounts" => ["4111"]];
            $result = $this->_registry->report->viewTopSuppCust($data);
            die(json_encode($result));
        }
    }

    public function dailyJVsRequest() {
        $cond = ' 1=1 ';
        $from_date = !empty($_GET['Transaction_Date_From']) ? $_GET['Transaction_Date_From'] : smc_session()['start_date'];
        $to_date = !empty($_GET['Transaction_Date_To']) ? $_GET['Transaction_Date_To'] : smc_session()['end_date'];
        $cond .= ' and  Transaction_Date >= "' . $from_date . '" AND Transaction_Date <= "' . $to_date . '"';
        if (!empty($_GET['due_date_from']) && !empty($_GET['due_date_to'])) {
            $cond .= ' and due_date >= "' . $_GET['due_date_from'] . '" AND due_date <= "' . $_GET['due_date_to'] . '"';
        }
        if ($_GET['Is_Actual'] == 0) {
            $cond .= ' and is_actual = "' . $_GET['Is_Actual'] . '" ';
        }
        if ($_GET['actual_only'] == 1 && $_GET['Is_Actual'] == 1) {
            $cond .= ' and is_actual = "' . $_GET['Is_Actual'] . '" ';
        }
        if (isset($_GET['trans_type']) && $_GET['trans_type'] != '') {
            $cond .= ' and main_type in ("' . implode('","', $_GET['trans_type']) . '") ';
        }
        if (!empty($_GET['from_jv'])) {
            $cond .= ' and JV_ID >= "' . $_GET['from_jv'] . '" ';
        }
        if (!empty($_GET['to_jv'])) {
            $cond .= ' and  JV_ID <= "' . $_GET['to_jv'] . '"';
        }
        if (!empty($_GET['from_account'])) {
            $cond .= ' and left(Transaction_Account,' . strlen($_GET['from_account']) . ') >= "' . $_GET['from_account'] . '" ';
        }
        if (!empty($_GET['to_account'])) {
            $cond .= ' and  left(Transaction_Account,' . strlen($_GET['from_account']) . ') <= "' . $_GET['to_account'] . '"';
        }
        if (!empty($_GET['from_amount'])) {
            $cond .= ' and Transaction_Amount >= "' . $_GET['from_amount'] . '" ';
        }
        if (!empty($_GET['to_amount'])) {
            $cond .= ' and  Transaction_Amount <= "' . $_GET['to_amount'] . '"';
        }
        if (!empty($_GET['job_ids'])) {
            $cond .= ' and job_id in (' . $_GET['job_ids'] . ')';
        }
        if (!empty($_GET['project_ids'])) {
            $cond .= ' and project_id in (' . $_GET['project_ids'] . ')';
        }
        if (!empty($_GET['multi_accounts'])) {
            $cond .= ' and Account_ID in (' . $_GET['multi_accounts'] . ')';
        }
        if (!empty($_GET['family_acc'])) {
            $family_accs = CommonACC::get_family_accs_by_id($_GET['family_acc']);
            $cond .= ' and Account_ID in (' . $family_accs . ')';
        }
        if (!empty($_GET['ref_type'])) {
            $cond .= ' and subtype in ("' . implode('","', explode(",", $_GET['ref_type'])) . '") and main_type="mjv" ';
        }
        if (!empty($_GET['trans_currency'])) {
            $cond .= ' and Currency_ID in(' . $_GET['trans_currency'] . ')';
        }
        if (!empty($_GET['jv_id'])) {
            $cond = ' JV_ID = "' . $_GET['jv_id'] . '" and is_actual = "' . $_GET['Is_Actual'] . '"';
        }
        if (!empty($_GET['salesman_id'])) {
            $cond .= ' and salesman_id = "' . $_GET['salesman_id'] . '" ';
        } 
        if (!empty($_GET['is_activity'])) {
            $cond .= ' and activity_id <> 0 and activity_id is not null ';
        }
        $_GET['inv_pur_ids'] = array('pur_ids'=>array(),'inv_ids'=>array());
        //                                                                if (smc_session()['default_setting']['activate_second_currency'] == 1) {
        $columns = array(
            array("db" => "jv_nb"),
            array("db" => "subtype"),
            array("db" => "trans_nb","formatter"=>function($d,$row){
                $abrv = CommonBusiness::get_trans_main_type($row['main_type'],true);
                return $abrv.' '.$d;
            }),
            array("db" => "user_ref"),
            array("db" => $_GET['is_activity'] == 0 ? "Transaction_Account" : "activity_code"),
            array("db" => $_GET['is_activity'] == 0 ? "Account_Name" : "activity_title"),
            array("db" => "Transaction_Description"),
            array("db" => "Transaction_Date"),
            array("db" => "due_date"),
            array("db" => "job_name"),
            array("db" => "Transaction_Amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Debit' ? CommonFunctions::formatNumber(round($d, 3)) . ' ' . $row['Currency_Symbol'] : '';
            }),
            array("db" => "Transaction_Amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Credit' ? CommonFunctions::formatNumber(round($d, 3)) . ' ' . $row['Currency_Symbol'] : '';
            }), array("db" => "local_amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Debit' ? CommonFunctions::formatNumber(round($d, 3)) : '';
            }),
            array("db" => "local_amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Credit' ? CommonFunctions::formatNumber(round($d, 3)) : '';
            }),);
        if (smc_session()['default_setting']['activate_second_currency'] == 1) {
            $columns = array_merge($columns, array(
                array("db" => "second_amount", "formatter" => function($d, $row) {
                    return $row['Transaction_Type'] == 'Debit' ? CommonFunctions::formatNumber(round($d, 3)) : '';
                }),
                array("db" => "second_amount", "formatter" => function($d, $row) {
                    return $row['Transaction_Type'] == 'Credit' ? CommonFunctions::formatNumber(round($d, 3)) : '';
                })));
        }
        //                                                                    array("db" => "User_Name", "dt" => 12),
        $columns = array_merge($columns,
                               array
                               (array('db' => 'JV_ID',
                                      'formatter' => function( $d, $row ) {
                                          //                                                    echo"<pre>";
                                          //                                                        print_r($row);
                                          $options = [["title" => CommonLanguage::getMessage('copy'),
                                                       "class" => "EditEntry",
                                                       "icon" => "fa-pencil",
                                                       "href" => "ACC/addJV/copy/" . (($row['is_actual'] == 1) ? "act/" : "") . $row['JV_ID']
                                                      ]
                                                     ];
                                          //                                                        echo"<pre>";
                                          //                                                        print_r($_GET['inv_pur_ids']['pur_ids']);
                                          $main_type = $row['main_type'];
                                          $main_id = $row['main_id'];
                                          if($row['main_type']=='pur' && !is_null($_GET['inv_pur_ids']['pur_ids'][$row['main_id']])){
                                              $main_type = 'spinv';
                                              $main_id = $_GET['inv_pur_ids']['pur_ids'][$row['main_id']];
                                          }
                                          else if($row['main_type']=='inv' && !is_null($_GET['inv_pur_ids']['inv_ids'][$row['main_id']])){
                                              $main_type = 'spinv';
                                              $main_id = $_GET['inv_pur_ids']['inv_ids'][$row['main_id']];
                                          }
                                          $edit_arr = CommonACC::get_edit_link_by_type($main_type, $main_id, $row['is_actual'], $row['JV_ID']);
                                          //                                                         if ($row['main_type'] == 'mjv') {
                                          
                                            $options[] = ["title" => CommonLanguage::getMessage('Edit'),
                                                        "class" => "EditEntry $main_type, $main_id, {$row['is_actual']}, {$row['JV_ID']}",
                                                        "icon" => "fa-pencil",
                                                        "permission" => $edit_arr['permission'],
                                                        "href" => $edit_arr['link']
                                                       ];
                                          //                                                         }
                                          $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $row['JV_ID'],
                                                                         "ActionOption" => $options]);

                                          return $html;
                                      }
                                     ),
                                array("db" => "Currency_Symbol"),
                                array("db" => "main_type"),
                                array("db" => "is_actual"),
                                array("db" => "Transaction_Type"), 'main_id', 'prefix','activity_code','activity_title'
                               ));
        // if(!empty($_GET['order'][0]['dir']))                                           
        //            $_GET['order'][0]['dir']='desc';
        $key = "Transaction_ID";
        $table = "transactions_info";
        $year_id = Session::getCurrentYearID($_GET['Is_Actual']);
        $cond .= ' AND current_year_id = "' . $year_id . '" ';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond, null, null, ['fetch_row_callback' => ['ft' => array($this, 'daily_jv_row_cb')],'fetch_all_callback' => ['ft' => array($this, 'daily_jv_fill_link')]]);
        echo json_encode($data);
    }

    public function daily_jv_row_cb($data,$row){
        if($row['main_type']=='pur')
            $_GET['inv_pur_ids']['pur_ids'][$row['main_id']] = null;
        else if($row['main_type']=='inv')
            $_GET['inv_pur_ids']['inv_ids'][$row['main_id']] = null;
    }

    public function daily_jv_fill_link(&$data){
        //        echo"<pre>";(print_r($_GET['inv_pur_ids']));
        //        echo"<pre>";die(print_r($data));
        if(!empty($_GET['inv_pur_ids']['pur_ids'])){
            $query = $this->db->query('select sales_purchase_id,Purchase_ID_Auto as auto_id
                from tbl_inventory_purchases where Purchase_ID_Auto in ('.implode(',',array_keys($_GET['inv_pur_ids']['pur_ids'])).') and ifnull(sales_purchase_id,0) <> 0');
            while($row = $this->db->assoc($query)){
                $_GET['inv_pur_ids']['pur_ids'][$row['auto_id']] = $row['sales_purchase_id'];
            }

        }
        if(!empty($_GET['inv_pur_ids']['inv_ids'])){
            $query = $this->db->query('select sales_purchase_id,Invoice_ID_Auto as auto_id
                from tbl_invoices where Invoice_ID_Auto in ('.implode(',',array_keys($_GET['inv_pur_ids']['inv_ids'])).') and ifnull(sales_purchase_id,0) <> 0');
            while($row = $this->db->assoc($query)){
                $_GET['inv_pur_ids']['inv_ids'][$row['auto_id']] = $row['sales_purchase_id'];
            }
        }
        //        $_GET['inv_pur_ids']

    }
    public function editJVAjax() {
        if (isset($_POST["Transaction_Date"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $ret = $this->_registry->jv->setData($_POST)->editJV();
            die(json_encode(!is_array($ret) ? ["OK", $ret] : ['error', $ret[0]] ));
            //            die(empty($ret) ? "OK" : "error" );
        }
    }

    public function printReport() {
        $options = ['from_date' => $_GET['data_from'], 'to_date' => $_GET['data_to'], 'currency' => $_GET['data_cur'], 'is_actual' => $_GET['data_actual']];
        if ($_GET['income'])
            $data = $this->_registry->report->statementOfIncome($options);
        else
            $data = $this->_registry->report->StmtFinancialPosition($options);
        $table = $_GET['income'] ? Forms::incomeStatementForm($data,$options) : Forms::financialPosition($data,$options);
        $current_time = date("Y-m-d h:i:s a");
        $time_lang = CommonLanguage::getMessage('print_time');
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, 'cm', array(21, 29.7), true, 'UTF-8', true);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetTitle('Balance Sheet');
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetMargins(1, 1, 1);
        if (@file_exists(dirname(__FILE__) . '/../TCPDF/examples/lang/ara.php')) {
            require(dirname(__FILE__) . '/../TCPDF/examples/lang/ara.php');
            $pdf->setLanguageArray($l);
        }
        $pdf->SetFont('aealarabiya', '', 14);
        $pdf->AddPage('', array(21, 29.7));
        $html = '<style>
  table {
        color: #000;
        font-family: aealarabiya;
        font-size: 15pt;
       text-align:center;
        border: 1px solid #000; 
    }
    table td{
    border: 1px solid #000; 
    }
    .title{
    background-color:#6dc0f9;
    color:white;
    text-align:center;
    }
    .toptitle{
    margin:0px !important;
    text-align:center}
</style>
<h4 class=" toptitle">' . $_GET['org'] . '<br>
    ' . $_GET['title'] . ' ' . $_GET['date'] . '<br>
    Amounts Expressed in ' . $_GET['currency'] . '<br>' . $_GET['actual'] . '</h4><br>
<table class="table table-hover demo-table-search" id="IncomeStatement">
                <tbody>';
        $html .= $table . '</tbody></table>';
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Output($_GET['title'] . '.pdf', 'D');
    }

    public function FixedAssetsRegisterList() {
        //        $condition=' 1=1 ';
        $condition = 'Is_Hidden = "' . $_GET['actual'] . '" and Is_Done = 1';
        if (isset($_GET['DateFrom']) and isset($_GET['DateTo']))
            $condition .= ' AND Expense_Date >= "' . $_GET['DateFrom'] . '" AND Expense_Date <= "' . $_GET['DateTo'] . '"';
        $columns = array(
            array("db" => "expense_nb", "dt" => 0),
            array("db" => "Account_Code", "dt" => 1),
            array("db" => "Account_Name", "dt" => 2),
            array("db" => "Depreciation_Rate_Description", "dt" => 3),
            array("db" => "Supplier_Name", "dt" => 4),
            array("db" => "Expense_Date", "dt" => 5),
            array("db" => "quantity", "dt" => 6),
            array("db" => "unit_price", "dt" => 7, "formatter" => function($d, $row) {
                return $row[13] . ' ' . Forms::DecimalNumber($d);
            }),
            array("db" => "net_total", "dt" => 8, "formatter" => function($d, $row) {
                return $row[13] . ' ' . Forms::DecimalNumber($d);
            }),
            array("db" => "Depreciation_Rate_Percent", "dt" => 9, "formatter" => function($d) {
                return '% ' . $d;
            }),
            array("db" => "sum(Depreciation_Amount)", "dt" => 10, "formatter" => function($d, $row) {
                return $row[13] . ' ' . Forms::DecimalNumber($d);
            }),
            array("db" => "Depreciation_Rate_ID", "dt" => 11, "formatter" => function($d, $row) {
                $sum = Report::get_uptodate_dep($d, $_GET['actual']);
                return $row[13] . ' ' . Forms::DecimalNumber($sum);
            }),
            array("db" => "Depreciation_Rate_ID", "dt" => 12,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("view"),
                                                                  "class" => "View",
                                                                  "icon" => "fa-eye",
                                                                  "permission" => $_GET['actual'] == 0 ? "viewDepreciation" : "viewDepreciationActual",
                                                                  "href" => "ACC/viewDepreciation/" . $d
                                                              )
                                                          )
                                                         ));
                      return $html;
                  }
                 ),
            array("db" => "Currency_Symbol", "dt" => 13),
        );
        $key = "Depreciation_Rate_ID";
        $table = "fixed_assets_register";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition, null, 'group by Depreciation_Rate_ID');
        echo json_encode($data);
    }

    public function editPayment() {
        if (isset($_POST["Account_Code"])) {
            $RET = $this->_registry->payment->setData($_POST)->editPayment(true);
            die(json_encode(is_numeric($RET[0]) ? ['OK', $RET[0], $RET[1], $RET[2]] : $RET));
        }
    }

    public function UserAccAccounts() {
        $cond = ' Status_ID = 1 ' . (smc_session()['user_logged_username'] == 'admin' ? '' : ' and User_Name !="admin" ');
        $columns = array(
            array('db' => 'User_Name', 'dt' => 0),
            array('db' => 'Cash_Name', 'dt' => 1),
            array("db" => "User_ID", "dt" => 2,
                  "formatter" => function($d) {
                    $actions = [
                         ["title" => CommonLanguage::getMessage("Edit"),
                         "class" => "Edit",
                         "permission" => "editUserAccounts",
                         "icon" => "fa-pencil"
                        ]
                    ];
                    $actions[] = ["title" => CommonLanguage::getMessage("copy"),
                    "class" => "copy",
                     "permission" => "editUserAccounts",
                     "icon" => "fa-copy"
                ];
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                          "ActionOption" =>  $actions
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'User_Account_ID';
        $table = 'user_accounting_accounts_name';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function CashDrawerAccounts() {
        $columns = array('cash_drawer_title', 'account_name',
                         array("db" => "cash_drawer_id", "dt" => 2,
                               "formatter" => function($d) {
                                   $html = Forms::action_snippet(array("color" => "complete",
                                                                       "isDropDown" => false,
                                                                       "data_id" => $d,
                                                                       "ActionOption" => array(
                                                                           array(
                                                                               "title" => CommonLanguage::getMessage("Edit"),
                                                                               "class" => "edit_cash_drawer",
                                                                               "permission" => "editcash_drawer_accounts",
                                                                               "data-target" => "#add-edit-cash-drawer-modal",
                                                                               "icon" => "fa-pencil"
                                                                           )
                                                                       )
                                                                      ));
                                   return $html;
                               }
                              )
                        );
        $key = 'cash_drawer_id';
        $table = 'view_cash_drawer_accounts';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function assignUserAccounts() {
        $insert = $this->_registry->user->setData($_POST)->setAccountsToUser();
        die(json_encode(empty($insert[0]) ? ['OK', CommonLanguage::getMessage('Submitted_Successfully') . ($insert[1] ? '<br>' . CommonLanguage::getMessage('used_prefix') : '')] : ['error', '']));
    }

    public function submitCashDrawerAccount() {
        $submit = $this->_registry->CommonACC->setData($_POST)->submitCashDrawerAccount();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage($_POST['cash_drawer_id'] == 0 ? 'cash_drawer_added' : 'cash_drawer_updated'), 'success'] : [$submit[0], 'danger']));
    }

    public function submitCashDrawerAmount() {
        $submit = $this->_registry->CommonACC->setData($_POST)->submitCashDrawerAmount();
        if (empty($submit)) {
            smc_session()['is_cash_drawer_active'] = 1;
            smc_session()['current_cash_drawer_id'] = $_POST['cash_drawer_id_ref'];
            die(json_encode([CommonLanguage::getMessage('amount_submitted'), 'success']));
        }
        die(json_encode([$submit[0], 'danger']));
    }

    public function continueWithCurrentCashDrawer() {
        $data = $this->_registry->CommonACC->getCashDrawerLogoutData();
        smc_session()['is_cash_drawer_active'] = 1;
        smc_session()['user_accounts']['cash_account_id'] = $data['cash_account_id'];
        smc_session()['current_cash_drawer_id'] = $data['cash_drawer_id'];
        die(!empty($data) ? "success" : "error");
    }

    public function submitCashDrawerAmountLogout() {
        $submit = $this->_registry->CommonACC->setData($_POST)->submitCashDrawerAmountLogout();
        if (empty($submit)) {
            die(json_encode([CommonLanguage::getMessage('amount_submitted'), 'success']));
        }
        die(json_encode([$submit[0], 'danger']));
    }

    public function getUserAccounts() {
        $data = $this->_registry->user->getUserAccounts($_GET['id']);
        die(json_encode($data));
    }

    public function getAccountBalance() {
        $today = Date::getToday();
        $from = smc_session()['start_date']; //date("Y", strtotime($today)) . '-01-01';
        //                                                                $code = JV::getAccountCodeByID($_GET['account']);
        //                                                                $data = $this->_registry->report->returnExactBalance($code, $_GET['currency'], $from, $today, true);
        $options = ["Account_ID" => $_GET['account'], "Currency_ID" => $_GET['currency'],
                    "From_Date" => $from, "To_Date" => $today, "Is_Actual" => $_GET['is_actual'],"pos_customer_id"=>$_GET['pos_customer']];
        $data = $this->_registry->report->returnExactBalanceByID($options);
        //                                                                                        $data = $this->_registry->report->returnExactBalanceByID($_GET['account'], $_GET['currency'], $from, $today, true, $_GET['is_actual']);
        die(json_encode($data));
    }

    public function getUnpaidInvoicesByCustomer() {
        $_GET['pos_customer'] = isset($_GET['pos_customer']) ? $_GET['pos_customer'] : 0;
        $_GET['record_id'] = isset($_GET['record_id']) ? $_GET['record_id'] : 0;
        $_GET['type'] = isset($_GET['type']) ? $_GET['type'] : ($_GET['is_receipt']==1 ? 'rec' : 'pay');
        if($_GET['is_receipt']==1)
            $data = $this->_registry->Invoice->getUnpaidInvoicesByCustomer($_GET['account'], $_GET['currency'], $_GET['record_id'], $_GET['is_actual'],$_GET['pos_customer'],$_GET['type']);
        else
            $data = $this->_registry->purchase->getUnpaidInvoicesBySupplier($_GET['account'], $_GET['currency'], $_GET['record_id'], $_GET['is_actual'],$_GET['type']);
        die(json_encode($data));
    }

    public function add_org_branch() {
        $insert = $this->_registry->Organization->setData($_POST)->add_org_branch();
        die(json_encode(empty($insert[0]) ? ['OK', CommonLanguage::getMessage('Submitted_Successfully') . ($insert[1] ? '<br>' . CommonLanguage::getMessage('used_prefix') : '')] : ['error', '']));
    }

    public function edit_org_branch() {
        $edit = $this->_registry->Organization->setData($_POST)->edit_org_branch();
        die(json_encode(empty($edit[0]) ? ['OK', CommonLanguage::getMessage('Submitted_Successfully') . ($edit[1] ? '<br>' . CommonLanguage::getMessage('used_prefix') : '')] : ['error', '']));
    }

    public function getOrgBranch() {
        $data = $this->_registry->Organization->getOrgBranch($_GET['id']);
        die(json_encode($data));
    }

    public function org_branches() {
        $columns = array(
            array('db' => 'branch_name', 'dt' => 0),
            array('db' => 'branch_prefix', 'dt' => 1),
            array("db" => "branch_id", "dt" => 2,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "permission" => "edit_org_branches",
                                                                  "icon" => "fa-pencil"
                                                              )
                                                          )
                                                         ));
                      return smc_session()['default_setting']['sync_type'] != 2 ? $html : '<span>' . CommonLanguage::getMessage('noauthactions') . '</span>';
                  }
                 )
        );
        $key = 'branch_id';
        $table = 'tbl_organization_branches';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function add_edit_group_accounts() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_group_accounts();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function group_account_list() {
        $columns = array(
            array('db' => 'group_name', 'dt' => 0),
            array("db" => "group_account_id", "dt" => 1,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "permission" => "edit_group_account_list",
                                                                  "icon" => "fa-pencil"
                                                              )
                                                          )
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'group_account_id';
        $table = 'tbl_group_accounts';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function get_group_accounts() {
        $data = $this->_registry->CommonACC->get_group_accounts($_GET['id']);
        die(json_encode($data));
    }

    public function coa_generate_code() {
        $data = $this->_registry->CommonACC->coa_generate_code($_GET['parent_id']);
        die(json_encode($data));
    }

    public function getdilyJVsTotals() {
        $totals = Report::getDebitCreditTotals($_GET['data']);
        die(json_encode($totals));
    }

    public function reorder_jv() {
        $reorder = $this->_registry->jv->reorderOffJVNum($_POST['from_date'], $_POST['is_actual']);
        die(empty($reorder) ? 'OK' : 'error');
    }

    public function check_if_fa_child() {
        $flag = CommonACC::account_is_child(smc_session()['account_setting']['fixed_asset_parent_acc_id'], $_GET['id']);
        die(json_encode($flag));
    }

    public function add_edit_jobs() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_jobs();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    //    public function jobs_list() {
    //        $columns = array(
    //            array('db' => 'job_name', 'dt' => 0),
    //            array("db" => "job_id", "dt" => 1,
    //                  "formatter" => function($d) {
    //                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false, "data_id" => $d,
    //                                                          "ActionOption" => array(
    //                                                              array(
    //                                                                  "title" => CommonLanguage::getMessage("Edit"),
    //                                                                  "class" => "Edit",
    //                                                                  "icon" => "fa-pencil",
    //                                                                  "permission" => "edit_job"
    //                                                              )
    //                                                          )
    //                                                         ));
    //                      return $html;
    //                  }
    //                 )
    //        );
    //        $key = 'job_id';
    //        $table = 'tbl_accounting_jobs';
    //        $data = DataTable::complex($_GET, $table, $key, $columns);
    //
    //        echo json_encode($data);
    //    }
    public function add_edit_trans_types() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_trans_types();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function trans_type_list() {
        $columns = array(
            array('db' => 'subtype_name', 'dt' => 0),
            array('db' => 'subtype_abbrv', 'dt' => 1),
            array("db" => "subtype_id", "dt" => 2,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "icon" => "fa-pencil",
                                                                  "permission" => "edit_trans_type"
                                                              )
                                                          )
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'subtype_id';
        $table = 'tbl_accounting_transaction_subtype';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function get_jobs_by_ids() {
        $data = $this->_registry->CommonACC->get_jobs_by_ids($_GET['job_ids']);
        die(json_encode($data));
    }

    public function JobSearch() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        if ((smc_session()['default_setting']['all_jobs_for_notlinked_accs'] == 1 && isset($_GET['job_ids']) && $_GET['job_ids'] == '') || !isset($_GET['job_ids'])) {
            $job_ids = null;
        } else {
            $job_ids = $_GET['job_ids'];
        }
        $ALL = $this->_registry->CommonACC->JobSearch($term, $page, $_GET['limit'], $job_ids);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }

    public function add_edit_family_accounts() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_family_accounts();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function family_accounts_list() {
        $columns = array(
            array('db' => 'family_name', 'dt' => 0),
            array("db" => "family_id", "dt" => 1,
                  "formatter" => function($d) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => false, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "icon" => "fa-pencil",
                                                                  "permission" => "edit_family_account"
                                                              )
                                                          )
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'family_id';
        $table = 'tbl_family_accounts';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function get_family_accounts() {
        $data = $this->_registry->CommonACC->get_family_accounts($_GET['id']);
        die(json_encode($data));
    }

    public function get_jv_exchange_rate() {
        $data = array();
        $data['local'] = $this->_registry->currency->returnExchangeRate($_GET['currency_id'], smc_session()['local_currency']);
        $data['second'] = $this->_registry->currency->returnExchangeRate($_GET['currency_id'], smc_session()['second_currency']['id']);
        die(json_encode($data));
    }

    public function get_job_tree() {
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        $this->status = isset($_GET["status"]) ? intval($_GET["status"]) : -1;
        if ($cmd == "fetch") {
            $RET = $id == 0 ? $this->_registry->CommonACC->get_job_tree() : $this->_registry->CommonACC->get_job_tree($id);
            for ($x = 0; $x < count($RET); $x++) {
                $RET2 = $this->_registry->CommonACC->get_job_tree(intval($RET[$x]["job_id"]));
                if (count($RET2) > 0)
                    $RET[$x]["isLazy"] = true;
                $RET[$x]["key"] = $RET[$x]["job_id"];
            }
            echo json_encode($RET);
        }
    }

    public function get_next_job_code() {
        $code = $this->_registry->CommonACC->get_next_job_code($_GET['parent_id']);
        die($code);
    }

    public function job_trial_balance_ajax() {
        $trialList = $this->_registry->report->job_trial_balance($_GET['data']);
        $actual = $_GET['data']['Is_Actual'] == 1 ? 1 : null;
        $form = Forms::gettrialBalance($trialList, $actual, 1);
        die($form);
    }

    public function project_trial_balance_ajax() {
        $trialList = $this->_registry->report->project_trial_balance($_GET['data']);
        $actual = $_GET['data']['Is_Actual'] == 1 ? 1 : null;
        $form = Forms::gettrialBalance($trialList, $actual, 2);
        die($form);
    }



    public function get_job_by_id() {
        $data = $this->_registry->CommonACC->get_job_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function add_edit_financial_year() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_financial_year();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function financial_year_list() {
        $columns = array(
            array('db' => 'current_year', 'dt' => 0),
            array('db' => 'start_date', 'dt' => 1),
            array('db' => 'end_date', 'dt' => 2),
            array("db" => "current_year_id", "dt" => 3,
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "icon" => "",
                                                                  "attr" => "data-is-closed='{$row[4]}' data-is-act-closed='{$row[5]}'",
                                                                  "permission" => "edit_financial_year"
                                                              ), array(
                                                                  "title" => CommonLanguage::getMessage("open_act_year"),
                                                                  "class" => "open_act_year",
                                                                  "icon" => "",
                                                                  "permission" => "open_actual_year"
                                                              ),
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("open_year"),
                                                                  "class" => "open_year",
                                                                  "icon" => "",
                                                                  "permission" => "open_year"
                                                              )
                                                          )
                                                         ));
                      return $html;
                  }
                 ),
            array('db' => 'is_closed', 'dt' => 4),
            array('db' => 'is_act_closed', 'dt' => 5),
        );
        $key = 'current_year_id';
        $table = 'tbl_common_current_year';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function customer_supplier_vat_report() {
        $data_result = $this->_registry->report->customer_supplier_vat_report($_GET['type'], $_GET['from_date'], $_GET['to_date'], $_GET['is_actual'], $_GET['search_branch_id']);
        $html = Forms::build_table_html($data_result['data']);
        die(json_encode(["html" => $html, "total" => $data_result['total']]));
    }

    public function check_due_dates_report() {
        $condition = ' 1=1 ';
        $year_id = $_GET['is_actual'] ? $this->year_id_actual : $this->year_id;
        if (isset($_GET['date_from']) && isset($_GET['date_to'])) {
            if ($_GET['date_type'] == 1)
                $condition .= ' and due_date >= "' . $_GET['date_from'] . '" AND due_date <= "' . $_GET['date_to'] . '"';
            else
                $condition .= ' and value_date >= "' . $_GET['date_from'] . '" AND value_date <= "' . $_GET['date_to'] . '"';
        }
        if (!empty($_GET['account'])) {
            $condition .= ' and Account_ID = "' . $_GET['account'] . '" ';
        }
        if (!empty($_GET['type'])) {
            $condition .= ' and main_type in ("' . implode('","', $_GET['type']) . '") ';
        }
        if (!empty($_GET['trans_type'])) {
            $condition .= ' and Transaction_Type ="' . $_GET['trans_type'] . '" ';
        }
        $condition .= ' AND is_actual= "' . $_GET['is_actual'] . '" AND current_year_id = "' . $year_id . '"';
        $condition .= ' AND check_nb <> 0';
        $columns = array(
            array("db" => "Account_Name", "dt" => 0, "formatter" => function($d, $row) {
                return $d . ' - ' . $row['Transaction_Account'];
            }), "check_nb", "due_date", "value_date", "Transaction_Description",
            array("db" => "Transaction_Amount", "dt" => 5, "formatter" => function($d, $row) {
                return '<span class="bold" style="color:' . ($row['Transaction_Type'] == 'Debit' ? 'green' : 'red') . ';">' . $row['Currency_Symbol'] . ' ' . CommonFunctions::public_round_number($d) . '</span>';
            }),
            array("db" => "main_type", "dt" => 6, "formatter" => function($d) {
                return CommonBusiness::get_trans_main_type($d);
            }), "trans_nb", "Currency_Symbol", "Transaction_Account", "Transaction_Type"
        );
        $key = "Transaction_ID";
        $table = "transactions_info";
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function manual_jv_list_ajax() {
        $cond = ' 1=1 ';
        $from_date = !empty($_GET['Transaction_Date_From']) ? $_GET['Transaction_Date_From'] : smc_session()['start_date'];
        $to_date = !empty($_GET['Transaction_Date_To']) ? $_GET['Transaction_Date_To'] : smc_session()['end_date'];
        $cond .= ' and  Transaction_Date >= "' . $from_date . '" AND Transaction_Date <= "' . $to_date . '"';
        if (!empty($_GET['due_date_from']) && !empty($_GET['due_date_to'])) {
            $cond .= ' and due_date >= "' . $_GET['due_date_from'] . '" AND due_date <= "' . $_GET['due_date_to'] . '"';
        }
        if ($_GET['Is_Actual'] == 0) {
            $cond .= ' and is_actual = "' . $_GET['Is_Actual'] . '" ';
        }
        if ($_GET['actual_only'] == 1 && $_GET['Is_Actual'] == 1) {
            $cond .= ' and is_actual = "' . $_GET['Is_Actual'] . '" ';
        }
        if (isset($_GET['trans_type']) && $_GET['trans_type'] != '') {
            $cond .= ' and main_type in ("' . implode('","', $_GET['trans_type']) . '") ';
        }
        if (!empty($_GET['from_jv'])) {
            $cond .= ' and JV_ID >= "' . $_GET['from_jv'] . '" ';
        }
        if (!empty($_GET['to_jv'])) {
            $cond .= ' and  JV_ID <= "' . $_GET['to_jv'] . '"';
        }
        if (!empty($_GET['from_account'])) {
            $cond .= ' and left(Transaction_Account,' . strlen($_GET['from_account']) . ') >= "' . $_GET['from_account'] . '" ';
        }
        if (!empty($_GET['to_account'])) {
            $cond .= ' and  left(Transaction_Account,' . strlen($_GET['from_account']) . ') <= "' . $_GET['to_account'] . '"';
        }
        if (!empty($_GET['from_amount'])) {
            $cond .= ' and Transaction_Amount >= "' . $_GET['from_amount'] . '" ';
        }
        if (!empty($_GET['to_amount'])) {
            $cond .= ' and  Transaction_Amount <= "' . $_GET['to_amount'] . '"';
        }
        if (!empty($_GET['job_ids'])) {
            $cond .= ' and job_id in (' . $_GET['job_ids'] . ')';
        }
        if (!empty($_GET['project_ids'])) {
            $cond .= ' and project_id in (' . $_GET['project_ids'] . ')';
        }
        if (!empty($_GET['multi_accounts'])) {
            $cond .= ' and Account_ID in (' . $_GET['multi_accounts'] . ')';
        }
        if (!empty($_GET['family_acc'])) {
            $family_accs = CommonACC::get_family_accs_by_id($_GET['family_acc']);
            $cond .= ' and Account_ID in (' . $family_accs . ')';
        }
        if (!empty($_GET['ref_type'])) {
            $cond .= ' and subtype in ("' . implode('","', explode(",", $_GET['ref_type'])) . '") and main_type="mjv" ';
        }
        if (!empty($_GET['trans_currency'])) {
            $cond .= ' and Currency_ID in(' . $_GET['trans_currency'] . ')';
        }
        if (!empty($_GET['jv_id'])) {
            $cond = ' JV_ID = "' . $_GET['jv_id'] . '" and is_actual = "' . $_GET['Is_Actual'] . '"';
        }
        if($this->_registry->permissions->hasPermission('Branches')){
            $cond .= !empty($_GET['search_branch_id']) ? ' and branch_id ="' . ($_GET['search_branch_id']) . '"' : '';
        }else{
            $cond .= ' and branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '"'  ;
        }
        
        //                                                                if (smc_session()['default_setting']['activate_second_currency'] == 1) {
        $columns = array(
            array("db"=>"trans_nb","formatter"=>function($d,$row){
                    return '<input type="checkbox" data-id="' . $row['JV_ID'] . '" data-nb="' . $d . '"  class="del_td pull-left multi_delete"/>' . $d;
               
        }),
            array("db" => "Transaction_Reference"),
            array("db" => "Transaction_Account"),
            array("db" => "Account_Name"),
            array("db" => "Transaction_Description"),
            array("db" => "Transaction_Date"),
            array("db" => "Transaction_Amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Debit' ? CommonFunctions::public_round_number($d) . ' ' . $row['Currency_Symbol'] : '';
            }),
            array("db" => "Transaction_Amount", "formatter" => function($d, $row) {
                return $row['Transaction_Type'] == 'Credit' ? CommonFunctions::public_round_number($d) . ' ' . $row['Currency_Symbol'] : '';
            }));
        //                                                                    array("db" => "User_Name", "dt" => 12),
        $columns = array_merge($columns, array(array('db' => 'JV_ID',
                                                     'formatter' => function( $d, $row ) {
                                                         $options = [["title" => CommonLanguage::getMessage('view'),
                                                                      "class" => "openFrame",
                                                                      "icon" => "fa-eye",
                                                                      "permission" => $row['is_actual'] ? 'view_actual_manual_jv' : 'view_manual_jv',
                                                                      "attr" => "data-src='ACC/ViewJV/" . (($row['is_actual'] == 1) ? "act/" : "") . "/{$d}?is_pop=1'"
                                                                     ], ["title" => CommonLanguage::getMessage('copy'),
                                                                         "class" => "EditEntry",
                                                                         "icon" => "fa-pencil",
                                                                         "href" => "ACC/addJV/copy/" . (($row['is_actual'] == 1) ? "act/" : "") . $d
                                                                        ], ["title" => CommonLanguage::getMessage('Delete'),
                                                                            "class" => "delete_jv",
                                                                            "icon" => "fa-trash"
                                                                           ]
                                                                    ];
                                                         if ($row['main_type'] == 'mjv') {
                                                             $options[] = ["title" => CommonLanguage::getMessage('Edit'),
                                                                           "class" => "EditEntry",
                                                                           "icon" => "fa-pencil",
                                                                           "href" => "ACC/addJV/" . (($row['is_actual'] == 1) ? "act/" : "") . $d
                                                                          ];
                                                           
                                                            $options[] = [
                                                                "title" => CommonLanguage::getMessage($row['is_actual'] == 1 ? "to_official" : "to_actual"),
                                                                "class" => "change_actual",
                                                                "permission" => ($row['is_actual'] == 1 ?  "convert_act_manual_jv_to_official":"convert_manual_jv_to_actual"),
                                                                "icon" => "fa-retweet"
                                                            ];
                                                         }
                                                         $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                                                        "ActionOption" => $options]);
                                                         return $html;
                                                     }
                                                    ),
                                               array("db" => "Currency_Symbol"),
                                               array("db" => "main_type"),
                                               array("db" => "is_actual"),
                                               array("db" => "Transaction_Type")
                                              ));
        $key = "Transaction_ID";
        $table = "transactions_info";
        //        $year_id = Session::getCurrentYearID($_GET['Is_Actual']);
        $cond .= ' AND current_year_id = "' . $this->year_id . '"';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);
        echo json_encode($data);
    }

    public function ex_rate_table_ajax() {
        $data_result = $this->_registry->currency->selectExchangeRateAccounts($_GET['actual'], $_GET['date']);
        die(json_encode($data_result));
    }

    public function delete_payment_receipt() {
        if(isset($_GET['from_pos']))
            $from_pos = $_GET['from_pos'];
        else 
            $from_pos = 0;
        $delete = $this->_registry->payment->delete_payment_receipt($_GET['ids'], $_GET['is_receipt'],$_GET['is_return'],$from_pos);
        die(empty($delete) ? 'ok' : $delete[0]);
    }


    public function delete_expense() {
        $delete = $this->_registry->expense->delete_expense($_GET['ids']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function delete_jv() {
        $delete = $this->_registry->jv->delete_jv($_GET['ids'], $_GET['is_actual']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function delete_deposit_withdrawal() {
        $delete = $this->_registry->jv->delete_deposit_withdrawal($_GET['ids']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }


    public function delete_debit_credit_note() {
        $delete = $this->_registry->debitnote->delete_debit_credit_note($_GET['id'], $_GET['is_debit']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function add_edit_dynamic_report() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_dynamic_report();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function get_dynamic_report_by_id() {
        $data = $this->_registry->CommonACC->get_dynamic_report_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function dynamic_report_ajax() {
        $columns = array(
            array('db' => 'report_name', 'dt' => 0),
            array("db" => "report_id", "dt" => 1,
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "icon" => "",
                                                                  "permission" => "edit_dynamic_report"
                                                              ), array(
                                                                  "title" => CommonLanguage::getMessage("Delete"),
                                                                  "class" => "delete",
                                                                  "icon" => "",
                                                                  "permission" => "delete_dynamic_report"
                                                              ),
                                                          )
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'report_id';
        $table = 'tbl_dynamic_report_template';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function delete_dynamic_report() {
        $delete = $this->_registry->CommonACC->delete_dynamic_report($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function build_dynamic_report() {
        $data_result = $this->_registry->report->build_dynamic_report($_GET);
        //        echo"<pre>";die(print_r($data_result));
        $html = Forms::build_table_html($data_result);
        die(json_encode(["html" => $html, "data" => $data_result]));
    }

    public function get_project_tree() {
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        $this->status = isset($_GET["status"]) ? intval($_GET["status"]) : -1;
        if ($cmd == "fetch") {
            $RET = $id == 0 ? $this->_registry->CommonACC->get_project_tree() : $this->_registry->CommonACC->get_project_tree($id);
            for ($x = 0; $x < count($RET); $x++) {
                $RET2 = $this->_registry->CommonACC->get_project_tree(intval($RET[$x]["project_id"]));
                if (count($RET2) > 0)
                    $RET[$x]["isLazy"] = true;
                $RET[$x]["key"] = $RET[$x]["project_id"];
            }
            echo json_encode($RET);
        }
    }

    public function get_next_project_code() {
        $code = $this->_registry->CommonACC->get_next_project_code($_GET['parent_id']);
        die($code);
    }

    public function get_project_by_id() {
        $data = $this->_registry->CommonACC->get_project_by_id($_GET['id']);
        die(json_encode($data));
    }


    public function add_edit_projects() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_projects();
        die(json_encode(empty($insert) ? 'OK' : $insert[0]));
    }

    public function projectSearch() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->CommonACC->projectSearch($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }

    public function checkProjectTransactions() {
        $ret = $this->_registry->jv->setData($_GET)->checkProjectTransactions();
        die(json_encode($ret));
    }

    public function submitScheduleBills() {
        $submit = $this->_registry->payment->setData($_POST)->submitScheduleBills();
        die(json_encode(is_numeric($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success', $submit] : [$submit[0], 'danger']));
    }

    public function deleteScheduleBills() {
        $delete = $this->_registry->payment->setData($_GET)->deleteScheduleBills();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function scheduleBillsPayments() {
        $condition = ' is_actual= "' . $_GET['is_actual'] . '" ';
        if (!empty($_GET['bill_due_date_from']) && !empty($_GET['bill_due_date_to'])) {
            $FromDate = $_GET['bill_due_date_from'];
            $ToDate = $_GET['bill_due_date_to'];
            $condition .= 'and  bill_detail_due_date  between "' . $FromDate . '" AND  "' . $ToDate . '"';
        }
        if (!empty($_GET['status_id'])) {
            $condition .= ' and is_paid = "' . $_GET['status_id'] . '"';
        }
        if (is_numeric($_GET['customer_id']))
            $condition .= ' and customer_id = "' . $_GET['customer_id'] . '"';
        $columns = array("bill_nb", "Customer_Name", "bill_detail_due_date",
                         array("db" => "bill_detail_amount", "dt" => 3,
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber($d) . ' ' . $row['Currency_Symbol'];
                               }
                              ),
                         array("db" => "Transaction_Amount", "dt" => 4,
                               "formatter" => function($d, $row) {
                                   return $d ? ('<span class="transac_amount" data-trans-amount="' . $d . '">' . CommonFunctions::formatNumber($d) . ' ' . $row['trans_currency_symbol'] . ($row['user_ref'] ? (' - ' . $row['user_ref'] . ' - ') : '') . ' ' . $row['Transaction_Date'] . ' <i class="fa fa-trash delete_bill_payment" data-bill-id="' . $row['bill_id'] . '" data-bill-detail-id="' . $row['bill_detail_id'] . '" data-transaction-nb="' . $row['JV_ID'] . '"></i></span>') : '';
                               }
                              ),
                         array("db" => "bill_detail_paid_amount", "dt" => 5,
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber($row['bill_detail_amount'] - $d) . ' ' . $row['Currency_Symbol'];
                               }
                              ),
                         array("db" => "bill_detail_id", "dt" => 6,
                               "formatter" => function($d, $row, $is_excel) {
                                   if ($is_excel)
                                       return '';
                                   return $row['is_paid'] == 3 ? CommonLanguage::getMessage('noauthactions') : '<button class="btn btn-complete add_payment_btn" data-toggle="modal" data-target="#add_payment_modal" data-currency-id="' . $row['currency_id'] . '"  data-currency-symbol="' . $row['Currency_Symbol'] . '" data-customer-id="' . $row['customer_id'] . '" data-bill-id="' . $row['bill_id'] . '" data-bill-detail-id="' . $d . '" data-amount="' . $row['bill_detail_amount'] . '"> ' . CommonLanguage::getMessage('add_payment') . '</button>';
                               }
                              ), 'Currency_Symbol', 'bill_id', 'currency_id', 'customer_id', 'JV_ID', 'Transaction_Date', 'is_paid', 'user_ref', 'trans_currency_symbol'
                        );
        $key = 'bill_detail_id';
        $table = 'schedule_bills_payment_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $condition);
        echo json_encode($data);
    }

    public function submitSchedulePaymentBill() {
        $submit = $this->_registry->payment->setData($_POST)->submitSchedulePaymentBill();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function deletePaymentScheduleBills() {
        $delete = $this->_registry->payment->setData($_GET)->deletePaymentScheduleBills();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function getTotalPaymentBill() {
        $data = $this->_registry->payment->setData($_GET)->getTotalPaymentBill();
        die(json_encode($data));
    }

    public function dynamic_report_blocks_ajax() {
        $columns = array(
            array('db' => 'sub_title', 'dt' => 0),
            array("db" => "sub_id", "dt" => 1,
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                          "ActionOption" => array(
                                                              array(
                                                                  "title" => CommonLanguage::getMessage("Edit"),
                                                                  "class" => "Edit",
                                                                  "icon" => "",
                                                                  "permission" => "edit_dynamic_report_blocks"
                                                              ), 
                                                              //                                                              array(
                                                              //                                                                  "title" => CommonLanguage::getMessage("Delete"),
                                                              //                                                                  "class" => "delete",
                                                              //                                                                  "icon" => "",
                                                              //                                                                  "permission" => "delete_dynamic_report_blocks"
                                                              //                                                              ),
                                                          )
                                                         ));
                      return $html;
                  }
                 )
        );
        $key = 'sub_id';
        $table = 'tbl_dynamic_report_template_sub';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' report_id = 0 ');
        echo json_encode($data);
    }


    public function add_edit_dynamic_report_blocks() {
        $insert = $this->_registry->CommonACC->setData($_POST)->add_edit_dynamic_report_blocks();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function get_dynamic_report_block_by_id() {
        $data = $this->_registry->CommonACC->get_dynamic_report_block_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function settle_payment_ajax() {
        $update = $this->_registry->payment->settle_payment($_POST['payments']);
        die(empty($update) ? 'OK' : 'error');
    }


    public function aging_report_ajax(){

        $data_result = $this->_registry->report->setData($_GET)->aging_report();
        //                                                                                                                                                                        echo"<pre>";
        $html = Forms::build_table_html($data_result['data']);
        die(json_encode(["html" => $html,'totals'=>$data_result['totals']]));
    }
    public function checksalesman_ajax(){
        $data = $this->_registry->customer->get_customer_salesman($_GET['customer_id']);
        die(json_encode($data));
    }
    public function statement_pos_customer_ajax() {
        $list = $this->_registry->report->general_ledger_report($_GET['data']);
        die(json_encode($list));
    }
    public function pos_customer_trial_balance_ajax() {
        $trialList = $this->_registry->report->pos_customer_trial_balance($_GET['data']);
        $actual = $_GET['data']['Is_Actual'] == 1 ? 1 : null;
        $form = Forms::gettrialBalance($trialList, $actual, 3);
        die($form);
    }
    public function delete_prepaid() {
        $delete = $this->_registry->jv->delete_prepaid($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function get_payment_detail(){
        $data = $this->_registry->payment->get_payment_detail($_GET['id']);
        die(json_encode($data));
    }
    public function get_collection_by_id(){
        $data = $this->_registry->payment->get_collection_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function submit_collection(){
        $submit = $this->_registry->payment->setData($_POST)->submit_collection();
        die(json_encode(empty($submit) ? 'ok' : 'error'));
    }
    public function collection_list_ajax() {
        $columns = array('collection_nb','Account_Code','Account_Name','pay_amount',
                         'Currency_Symbol','note','collection_date',
                         array("db" => "collection_id", 
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(array("color" => "complete", "isDropDown" => true, "data_id" => $d,
                                                                       "ActionOption" => array(
                                                                           array(
                                                                               "title" => CommonLanguage::getMessage("Edit"),
                                                                               "class" => "Edit",
                                                                               "icon" => "",
                                                                               "permission" => ($_GET['is_actual']==1 ? "act_edit_collection": "edit_collection")
                                                                           ), 
                                                                           array(
                                                                               "title" => CommonLanguage::getMessage("Delete"),
                                                                               "class" => "delete",
                                                                               "icon" => "",
                                                                               "permission" => ($_GET['is_actual']==1 ? "act_delete_collection": "delete_collection")
                                                                           ),
                                                                       )
                                                                      ));
                                   return $html;
                               }
                              )
                        );
        $key = 'collection_id';
        $table = '(select c.*,a.Account_Code,a.Account_Name,cu.Currency_Symbol from tbl_pay_rec_collection c 
            join tbl_chart_of_accounts a on a.Account_ID = c.account_id
            join tbl_common_currency  cu on cu.Currency_ID = c.currency_id) as collection';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }

    public function delete_collection(){
        $delete = $this->_registry->payment->delete_collection($_GET['id']);
        die(empty($delete) ? 'ok' : $delete[0]);
    }

    public function get_activity_tree() {
        $cmd = isset($_GET["cmd"]) ? $_GET["cmd"] : "";
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        if ($cmd == "fetch") {
            $RET = $id == 0 ? $this->_registry->project->get_activity_tree() : $this->_registry->project->get_activity_tree($id);
            for ($x = 0; $x < count($RET); $x++) {
                $RET2 = $this->_registry->project->get_activity_tree(intval($RET[$x]["activity_id"]));
                if (count($RET2) > 0)
                    $RET[$x]["isLazy"] = true;
                $RET[$x]["key"] = $RET[$x]["activity_id"];
            }
            echo json_encode($RET);
        }
    }
    public function submit_activity_tree() {
        $submit = $this->_registry->project->setData($_POST)->submit_activity_tree();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function delete_activity_tree() {
        $submit = $this->_registry->project->setData($_GET)->delete_activity_tree();
        die(empty($submit) ? "ok" : $submit);
    }
    public function searchMainActivity() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->project->setData($_GET)->searchMainActivity($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    } 
    public function searchProjectPeriod() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->project->setData($_GET)->searchProjectPeriod($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    } 
    public function searchProjectPeriodDetails() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->project->setData($_GET)->searchProjectPeriodDetails($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }
    public function searchProjectPeriodActivity() {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->project->setData($_GET)->searchProjectPeriodActivity($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }
    public function project_period_list() {
        $columns = array('period_nb','period_title','project_name','nb_period','start_date',
                         'Currency_Symbol',
                         array("db" => "period_id", 
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(
                                       array("color" => "complete",
                                             "isDropDown" => true,
                                             "data_id" => $d,
                                             "ActionOption" => array(
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Edit"),
                                                     "class" => "edit_project_period",
                                                     "data-target"=>"#project_period_modal",
                                                     "icon" => "",
                                                     "permission" =>"edit_project_period"),
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Delete"),
                                                     "class" => "delete_project_period",
                                                     "icon" => "",
                                                     "permission" =>"delete_project_period")
                                             )
                                            )
                                   );
                                   return $html;

                               })
                        );
        $key = 'period_id';
        $table = 'project_period_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function submit_project_period() {
        $submit = $this->_registry->project->setData($_POST)->submit_project_period();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_activity_budget() {
        $submit = $this->_registry->project->setData($_POST)->submit_activity_budget();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function delete_project_period() {
        $submit = $this->_registry->project->setData($_GET)->delete_project_period();
        die(empty($submit) ? "ok" : $submit);
    }
    public function get_project_period(){
        $is_used = $this->_registry->project->check_project_period_used($_GET['period_id']);
        $data['main'] = CommonFunctions::CommonView('project_period_list',['period_id'],[$_GET['period_id']])[0];
        $data['activities'] =  $this->_registry->project->get_period_activities($data['main']['activity_ids']);
        $data['details'] = CommonFunctions::CommonView('tbl_project_period_details',['period_id'],[$_GET['period_id']]);
        $data['is_used'] = empty($is_used) ? 0 : 1;
        die(json_encode($data));
    }
    public function activity_budget(){
        $data = $this->_registry->project->setData($_GET)->activity_budget();
        $body = Forms::build_table_html($data['body']);
        $header = $data['header'];
        die(json_encode(['body'=>$body,'header'=>$header,'budget_id'=>$data['budget_id']]));
    }


    public function project_funding_list() {
        $columns = array('project_funding_nb','project_name','period_title','detail_period_title',
                         'date_created',
                         array("db" => "project_funding_id", 
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(
                                       array("color" => "complete",
                                             "isDropDown" => true,
                                             "data_id" => $d,
                                             "ActionOption" => array(
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Edit"),
                                                     "class" => "edit_project_funding",
                                                     "href"=>"ACC/project_funding/{$d}",
                                                     "icon" => "fa-pencil",
                                                     "permission" =>"edit_project_funding"),
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Delete"),
                                                     "class" => "delete",
                                                     "icon" => "fa-trash",
                                                     "permission" =>"delete_project_funding")
                                             )
                                            )
                                   );
                                   return $html;

                               })
                        );
        $key = 'project_funding_id';
        $table = 'project_funding_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function submit_project_funding() {
        $submit = $this->_registry->project->setData($_POST)->submit_project_funding();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function delete_project_funding() {
        $submit = $this->_registry->project->setData($_GET)->delete_project_funding();
        die(empty($submit) ? "ok" : $submit);
    }
    public function get_project_budget(){
        $data = $this->_registry->project->setData($_GET)->get_project_budget();
        $body = Forms::build_table_html($data);
        die(json_encode(['body'=>$body]));
    } 


    public function project_expense_list() {
        $cond = '';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
            $cond .= ' and project_expense_date between "' . $_GET['from_date'] . '" AND  "' . $_GET['to_date'] . '"';
        }
        $columns = array('project_expense_nb','project_expense_date','project_name','Supplier_Name',
                         array("db" => "project_expense_total", 
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber($d).' '.$row['Currency_Symbol']; 

                               }),
                         array("db" => "project_expense_id", 
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(
                                       array("color" => "complete",
                                             "isDropDown" => true,
                                             "data_id" => $d,
                                             "ActionOption" => array(
                                                 array(
                                                     "title" => CommonLanguage::getMessage("view"),
                                                     "class" => "View openFrame",
                                                     "permission" => 'view_project_expense',
                                                     "icon" => "fa-eye",
                                                     "attr" => "data-src='ACC/view_project_expense/{$d}?is_pop=1'"
                                                 ),
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Edit"),
                                                     "class" => "edit_project_expense",
                                                     "href"=>"ACC/project_expense/{$d}",
                                                     "icon" => "fa-pencil",
                                                     "permission" =>"edit_project_expense"),
                                                 array(
                                                     "title" => CommonLanguage::getMessage("Delete"),
                                                     "class" => "delete",
                                                     "icon" => "fa-trash",
                                                     "permission" =>"delete_project_expense")
                                             )
                                            )
                                   );
                                   return $html;

                               }),'Currency_Symbol'
                        );
        $key = 'project_expense_id';
        $table = 'project_expense_list';
        $data = DataTable::complex($_GET, $table, $key, $columns,' 1=1 '.$cond);
        echo json_encode($data);
    }
    public function submit_project_expense() {
        $submit = $this->_registry->project->setData($_POST)->submit_project_expense();
        die(json_encode(is_numeric($submit[0]) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success',$submit[0]] : [$submit[0], 'danger']));
    }
    public function delete_project_expense() {
        $submit = $this->_registry->project->setData($_GET)->delete_project_expense();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function get_project_expense(){
        $data = $this->_registry->project->setData($_GET)->get_project_expense();
        die(json_encode($data));
    }

    public function settle_expense_ajax() {
        $update = $this->_registry->expense->settle_expense($_POST['exp_id']);
        die(is_numeric($update[0]) ? 'OK' : 'error');
    }
    public function get_project_period_report(){
        $data = $this->_registry->project->setData($_GET)->get_project_period_report();
        $body = Forms::build_table_html($data);
        die(json_encode(['body'=>$body]));
    }

    public function get_activity_by_id() {
        $data = CommonFunctions::CommonView('tbl_activity_tree', ['activity_id'], ['activity_title'])[0];
        die(json_encode($data));
    }
    public function statement_of_activity_ajax() {
        $list = $this->_registry->report->general_ledger_report($_GET['data']);
        die(json_encode($list));
    }

    public function activity_trial_balance_ajax() {
        $trialList = $this->_registry->report->activity_trial_balance($_GET['data']);
        $actual = $_GET['data']['Is_Actual'] == 1 ? 1 : null;
        $form = Forms::gettrialBalance($trialList, $actual, 4);
        die($form);
    }
    public function project_activities_report(){
        $data = $this->_registry->project->setData($_GET)->activity_balances_report();
        $body = Forms::build_table_html($data['data']);
        die(json_encode(['total_exp'=>$data['total_exp'],'total_fund'=>$data['total_fund'],'total_balance'=>$data['total_balance'],'body'=>$body]));
    }

    public function update_activity_node(){
        $update = $this->_registry->project->setData($_POST)->update_activity_parent();
        die(empty($update) ? 'OK' : $update[0]);

    }
    public function aging_report_bydate_ajax(){

        $data_result = $this->_registry->report->setData($_GET)->aging_report_bydate();
        //                                                                                                                                                                        echo"<pre>";
        $html = Forms::build_table_html($data_result['data']);
        die(json_encode(["html" => $html,'totals'=>$data_result['totals']]));
    }
    public function change_expense_actual() {
        $change = $this->_registry->expense->change_expense_actual($_POST['id'], $_POST['is_actual'],$_POST['is_pending']);
        die(empty($change) ? 'OK' : 'error');
    }
    public function change_deposit_actual() {
        $change = $this->_registry->jv->change_deposit_actual($_POST['id'], $_POST['is_actual']);
        die(empty($change) ? 'OK' : 'error');
    }
    public function change_pay_rec_actual() {
        $change = $this->_registry->payment->change_pay_rec_actual($_POST['id'],$_POST['is_receipt'],$_POST['is_return'], $_POST['is_actual']);
        die(empty($change) ? 'OK' : 'error');
    }
    public function change_jv_actual() {
        $change = $this->_registry->jv->change_jv_actual($_POST['id'], $_POST['is_actual']);
        die(empty($change) ? 'OK' : 'error');
    }
    public function getBankInfo() {
        
        $data = $this->_registry->bank->setData($_GET)->getBankInfo();
        die(json_encode($data));
    }
    public function getAccountName() {
        $get_ids = $_GET['data'];
        $accounts_name = "";
        
        if (strpos($get_ids, ",") !== false) {
            $ids = explode(",",$get_ids);
            foreach($ids as $id){
                $accounts_name .= $this->_registry->jv->getAccountNameByID($id).' - ';
            }
        }else{
            $accounts_name = $this->_registry->jv->getAccountNameByID($get_ids);
        }

        
        die(json_encode([$accounts_name]));
    }

}
