<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 01-09-2014	
 * 	Revisi 	: 
 */

class Loan_payment extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 389;
    public $menu_model = '';
    public $name = 'Loan Payment';
    public $trans_data = array();
    // inisialisasi otomatis
    public $add = "add";
    public $edit = "edit";
    public $delete = "delete";
    public $to_preview = "to_preview";
    public $to_pdf = "to_pdf";
    public $to_excel = "to_excel";

    public function __construct() {
        parent::__construct();
        $this->load->model('m_menu');
        $this->load->model('m_loan_payment');
        $this->load->model('m_account_journal');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
        $this->load->model('login/m_login');
        $is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
        if($is_login){

        }else{
            $username       = $this->session->userdata('username');
            $session_id     = $this->session->userdata('session_id');
            $this->m_login->delete_session($username,$session_id);
            $this->session->sess_destroy();

            $uri_func = $this->uri->segment(3);
            if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
                redirect(base_url() . 'login', 'refresh');
            }else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
                $result['status']   = 'session';
                $result['message']  = get_notification('session_destroy',0);
                echo json_encode($result);
                die();
            }
        }
    }

    // Function Index	
    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    $group_menu = $this->session->userdata('group_menu');
                    // get link from tbl_menu 
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    // set data
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    // set for view
                    $this->load->view('v_header');
                    $this->load->view('cash_and_bank/loan_payment/v_loan_payment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $Number = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc = isset($param['txt_Description']) ? $param['txt_Description'] : '';

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        /* ============================================end============================================================ */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        $this->db->join('at_lpdetail', 'at_lpdetail.LPNumber=at_loanpayment.LPNumber', 'INNER');
        $this->db->join('am_branch', 'at_loanpayment.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee as created_by', 'at_loanpayment.CreatedBy=created_by.EmployeeCode', 'LEFT');

        if ($BranchCode != "") {
            $this->db->where('at_loanpayment.BranchCode', $BranchCode);
        } else {
            $this->db->where('at_loanpayment.BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('at_loanpayment.LPNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('at_loanpayment.LPDesc', $Desc);
        } //change
        if ($TransStatus != '') {
            $this->db->where_in('at_loanpayment.TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('at_loanpayment.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_loanpayment.LPDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_loanpayment.LPDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }


        $this->db->where('Payment_Type', 0);

        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_loanpayment');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }

        /* ========================end======================================= */
        $result = $this->m_loan_payment->get_all(0);
        //echo $this->db->last_query();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
                'TransNumber' => $result[$i]->LPNumber,
                'LPDate' => $result[$i]->LPDate,
                'LPAmount' => $result[$i]->LPAmount,
                'LPDesc' => $result[$i]->LPDesc,
                'PaymentPeriod' => $result[$i]->PaymentPeriod,
                'TransStatus' => $TransStatus,
                'BankAccount' => $result[$i]->Bank_Account,
                'CreatedBy' => $result[$i]->Created
            );
        }

        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
    }

    public function to_preview($obj_string = null) {
        $data['company'] = $this->m_loan_payment->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_loan_payment->get_all_to_print($this->session->userdata('branch'),0);

        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['list']           = $this->m_loan_payment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment/v_preview_loan_payment', $data);
        $this->load->view('v_footer');
    }

    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_loan_payment->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_loan_payment->get_all_to_print($this->session->userdata('branch'),0);

        $data_grid = str_replace('__', '/', $data_grid);
        $data_grid = str_replace('_', '-', $data_grid);
        $data_grid = str_replace('%20', ' ', $data_grid);
        $arr_grid_lv1 = explode('linebaru', $data_grid);

        $obj_string = '[';

        for ($x = 0; $x < count($arr_grid_lv1) - 1; $x++) {
            $arr_data_lv1 = $arr_grid_lv1[$x];
            $arr_grid_lv2 = explode('spasi', $arr_data_lv1);

            $obj_string .= '{';
            for ($i = 0; $i < count($arr_grid_lv2); $i++) {
                $arr_grid_lv3 = explode(':', $arr_grid_lv2[$i]);
                if ($i < count($arr_grid_lv2) - 1) {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '",';
                } else {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '"';
                }
            }

            if ($x < count($arr_grid_lv1) - 2) {
                $obj_string .= '},';
            } else {
                $obj_string .= '}';
            }
        }

        $obj_string .= ']';

        $data['list'] = json_decode($obj_string);

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment/v_preview_loan_payment', $data);
        $this->load->view('v_footer');
    }

    public function to_print_list() {
        // set data
        $data['list'] = $this->m_loan_payment->get_all();

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment/v_preview_loan_payment', $data);
        $this->load->view('v_footer');
    }

    // Function Index	
    public function add($no_piutang = null) {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    $group_menu = $this->session->userdata('group_menu');
                    // get link from tbl_menu 
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    // set data
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    $CompanyCode = $this->session->userdata('company');
                    $BranchCode = $this->session->userdata('branch');

                    if ($no_piutang != null) {
                        $no_piutang = str_replace($data['menu_link'] . '/add/', "", $this->uri->uri_string());
                        $data['no_piutang'] = $no_piutang;
                    } else {
                        $data['no_piutang'] = '';
                    }

                    $data['loan_payment'] = $this->m_loan_payment->create_loan_payment_number(date('d-m-Y'));
                    $data['date_now'] = date('d-m-Y');

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    // set for view
                    $this->load->view('v_header');
                    $this->load->view('cash_and_bank/loan_payment/v_new_loan_payment', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function get_loan_payment_number() {
        $preg_date = $this->input->post('loan_payment_date') == '' ? date('d-m-Y') : $this->input->post('loan_payment_date');

        $pay_karyawan_number = $this->m_loan_payment->create_loan_payment_number($preg_date);

//        print_r($data['sq_number1']);

        $result['status'] = true;
        $result['number'] = $pay_karyawan_number;
        echo json_encode($result);
    }

    public function get_bank_account($CurrencyCode = '') {

        $branch = $this->session->userdata('branch');

        $bank_account = $this->m_loan_payment->m_get_bank_account($branch, $CurrencyCode);

        echo $bank_account;
    }

    public function get_expense_account() {

        $branch = $this->session->userdata('branch');
        //$CurrencyCode 		= ($this->input->post('CurrencyCode')) ? $this->input->post('CurrencyCode'):'';

        $expense_account = $this->m_loan_payment->m_get_expense_account($branch);

        echo $expense_account;
    }

    public function get_all_account() {
        $branch = $this->session->userdata('branch');
        $all_account = $this->m_loan_payment->m_get_all_account($branch);
        echo $all_account;
    }

    public function get_akun_bank_edit($BranchCode) {
        $branch_explode = str_replace('_', '-', $BranchCode);
        $list_akun = $this->m_loan_payment->get_akun_bank_edit($branch_explode);
        echo $list_akun;
    }

    public function get_piutang() {
        $BranchCode = $this->session->userdata('branch');
        $list_piutang = $this->m_loan_payment->get_piutang($BranchCode);
        //echo $this->db->last_query();

        foreach ($list_piutang as $row) {
            $LFNumber = $row->LFNumber;
            $total_piutang = $row->LFAmount;
            $rate_piutang = $row->CurrencyRate;
            $currency_piutang = $row->CurrencyCode;
            $JVB = $row->JVoucherBalance;
            $BalanceAmount = 0;

            $outstanding = $this->m_loan_payment->get_sisa_piutang($LFNumber);
            $total_payment = $outstanding->total_payment;

            if (!empty($outstanding)) {
;
                //$BalanceAmount 		+= $total_payment + $JVB;
                $BalanceAmount = $total_piutang - (($total_payment + $JVB));
            } else {
                $BalanceAmount = $total_piutang;
            }

            if ($row->LFIsLock == 1) {
                $IsLock = "Locked";
            } else {
                $IsLock = "Un Locked";
            }

            $hasil[] = array(
                'LFAmount' => $row->LFAmount,
                'LFAmountview' => $row->LFAmount,
                'BranchName' => $row->BranchName,
                'BranchCode' => $row->BranchCode,
                'AccountName' => $row->AccountName,
                'LFAccount' => $row->LFAccount,
                'ReceiptAccount' => $row->ReceiptAccount,
                'LFNumber' => $row->LFNumber,
                'LFIsLock' => $IsLock,
                'LFDesc' => $row->LFDesc,
                'CurrencyCode' => $row->CurrencyCode,
                'CurrencyRate' => $row->CurrencyRate,
                'outstanding' => $BalanceAmount,
                'outstandingview' => $BalanceAmount
            );
        }

        if (!empty($hasil)) {
            echo json_encode($hasil);
        } else {
            $notFound = array();
            echo json_encode($notFound);
        }
    }

    public function get_company_edit($branch) {
        $branch_explode = str_replace('_', '-', $branch);
        $list_company = $this->m_loan_payment->get_company_edit($branch_explode);
        echo "$list_company";
    }

    public function get_company() {
        $branch = $this->session->userdata('branch');
        $list_company = $this->m_loan_payment->get_company_edit($branch);
        echo "$list_company";
    }

    public function get_payment_periode($payment_num) {

        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $LPNumber = $uri4 . "/" . $uri5 . "/" . $uri6;
        $payment_period = $this->uri->segment(7);
        $currency_payment = $this->uri->segment(8);

        $list_payment = $this->m_loan_payment->get_payment_periode($LPNumber, $payment_period, $currency_payment);
        //echo $this->db->last_query();

        echo $list_payment;
    }

    public function get_payment_periode_cancel($payment_num) {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $payment_before = str_replace($data['menu_link'] . '/get_payment_periode_cancel/', "", $this->uri->uri_string());

        $list_payment = $this->m_loan_payment->get_payment_periode_cancel($payment_before);

        echo"$list_payment";
    }

    public function get_history_payment($LPNumber, $payment_currency = '', $act_edit = '') {

        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        $LPNumber = str_replace('__', '/', $LPNumber);
        $LPNumber = str_replace('_', '-', $LPNumber);


        $result = $this->m_loan_payment->get_history_payment($LPNumber, $payment_currency, $act_edit);
        //echo $this->db->last_query();

        foreach ($result as $row) {
            $hasil[] = array(
                'LoanPayment' => $row->LoanPayment,
                'PaymentPeriod' => $row->PaymentPeriod,
                'PaymentPerPeriod1' => $row->PaymentPerPeriod1,
                'PaymentPerPeriod2' => $row->PaymentPerPeriod2,
                'PaymentBalance' => $row->PaymentBalance,
                'ExpenseAccount' => $row->ExpenseAccount,
                'ExpenseAmount1' => $row->ExpenseAmount1,
                'ExpenseAmount2' => $row->ExpenseAmount2,
                'LPNumber' => $row->LPNumber,
                'LPDetailID' => $row->LPDetailID
            );
        }

        if (!empty($hasil)) {
            echo json_encode($hasil);
        } else {
            $notFound = array();
            echo json_encode($notFound);
        }
    }

    public function proses_tutup() {
        $this->db->trans_rollback();
        $hasil = 0;
        $result['status'] = false;
        $result['message'] = get_notification('proses_tutup', $hasil);
        echo json_encode($result);
        die();
    }

    public function insert_group($BranchCode, $txt_date, $LPNumber, $LFNumber, $cmb_bank, $txt_desc, $total_payment, $total_expense, $txt_rate, $currency_payment,$cheque_number) {

        $data_payment = array(
            'BranchCode' => $BranchCode,
            'LPDate' => $txt_date,
            'LPNumber' => $LPNumber,
            'LFNumber' => $LFNumber,
            'BankAccount' => $cmb_bank,
            'LPDesc' => $txt_desc,
            'TransStatus' => 5,
            'LPAmount' => $total_payment,
            'ExpAmount' => $total_expense,
            'CurrencyCode' => $currency_payment,
            'CurrencyRate' => $txt_rate,
            'Payment_Type' => 0,
            'ChequeNumber' => $cheque_number,
            'CreatedBy' => $this->session->userdata('username'),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata('username')
        );

        $this->trans_data['insert_group']['data'] = $data_payment;
    }

    function insert_detail($LPNumber, $LFNumber, $detail, $currency_funding, $currency_payment, $txt_rate, $outstanding_amount) {

        foreach ($detail as $row) {
            if ($currency_payment == $currency_funding) {
                $LoanPayment = doubleval($row->LoanPayment);
                $PaymentPeriod = $row->PaymentPeriod;
                $PaymentPerPeriod = doubleval($row->PaymentPerPeriod1);
                $PaymentBalance = $outstanding_amount - doubleval($PaymentPerPeriod);
                $ExpenseAmount = $row->ExpenseAmount1;

                /* ================= get expense account ======================= */
                $currency_code = $this->m_account_journal->get_currency_code('', $row->ExpenseAccount, '');
                $data_account = $this->m_account_journal->get_account_name($row->ExpenseAccount, $currency_code->CurrencyCode);
                $ExpenseAccount = $data_account->AccountNumber;
                /* ================ end end end end end  ======================= */

                $detail_payment = array(
                    'LPNumber' => $LPNumber,
                    'LFNumber' => $LFNumber,
                    'LoanPayment' => $LoanPayment,
                    'PaymentPeriod' => $PaymentPeriod,
                    'PaymentPerPeriod' => $PaymentPerPeriod,
                    'PaymentBalance' => $PaymentBalance,
                    'ExpenseAccount' => $ExpenseAccount,
                    'ExpenseAmount' => $ExpenseAmount,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_detail']['data'] = $detail_payment;
            } else {

                $LoanPayment = $row->LoanPayment;
                $PaymentPeriod = $row->PaymentPeriod;

                /* ================= get expense account ======================= */
                $currency_code = $this->m_account_journal->get_currency_code('', $row->ExpenseAccount, '');
                $data_account = $this->m_account_journal->get_account_name($row->ExpenseAccount, $currency_code->CurrencyCode);
                $ExpenseAccount = $data_account->AccountNumber;
                /* ================ end end end end end  ======================= */

                if (($currency_payment == 'IDR') and ( $currency_funding != 'IDR')) {
                    $PaymentPerPeriod = doubleval($row->PaymentPerPeriod2) / $txt_rate;
                    $PaymentBalance = $outstanding_amount - $PaymentPerPeriod;
                    $ExpenseAmount = doubleval($row->ExpenseAmount2) / $txt_rate;
                } elseif (($currency_payment != 'IDR') and ( $currency_funding == 'IDR')) {
                    $PaymentPerPeriod = doubleval($row->PaymentPerPeriod2) * $txt_rate;
                    $PaymentBalance = $outstanding_amount - $PaymentPerPeriod;
                    $ExpenseAmount = doubleval($row->ExpenseAmount2) * $txt_rate;
                }

                $detail_payment = array(
                    'LPNumber' => $LPNumber,
                    'LFNumber' => $LFNumber,
                    'LoanPayment' => $LoanPayment,
                    'PaymentPeriod' => $PaymentPeriod,
                    'PaymentPerPeriod' => $PaymentPerPeriod,
                    'PaymentBalance' => $PaymentBalance,
                    'ExpenseAccount' => $ExpenseAccount,
                    'ExpenseAmount' => $ExpenseAmount,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_detail']['data'] = $detail_payment;
            }
        }
    }

    function insert_journal($txt_date, $LPNumber, $LFNumber, $LFAccount, $cmb_bank, $total_payment, $exp_account, $total_expense, $txt_desc, $currency_funding, $currency_payment, $txt_rate, $rate_piutang, $outstanding, $txt_amount, $outstanding_db) {

        $outstanding_db_new = $this->m_loan_payment->get_sisa_piutang_new($LFNumber);
        // echo $outstanding_db_new->PaymentBalance;
        // die();

        if ($currency_funding == 'IDR' and $currency_payment == 'IDR') {
            /* ============ insert journal loan Account ================== */
            $journal_funding = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $LFAccount,
                'LPSaldoDebet' => (strcmp($outstanding, $txt_amount) !== 0) ? $total_payment : $outstanding_db_new->PaymentBalance,
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? $total_payment : $outstanding_db_new->PaymentBalance,
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_funding;

            if (($total_expense != '') and ( $total_expense > 0)) {
                /* ============ insert journal expense Account ================== */

                /* ================================ get type n sub type account ========================== */
                $type_acc = $this->m_account_journal->m_get_account_type($exp_account);

                /* =============================== find plus in coa, credit or debet ======================== */
                $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                $journal_funding = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $exp_account,
                    'LPSaldoDebet' => $total_expense,
                    'AmountCurrency' => $total_expense,
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_funding;
            }

            /* ====================== insert journal bank account =============== */
            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => 0,
                'LPSaldoCredit' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : ($outstanding_db_new->PaymentBalance + $total_expense),
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : ($outstanding_db_new->PaymentBalance + $total_expense),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_bank;
        } elseif (($currency_funding == 'IDR') and ( $currency_payment != 'IDR')) {

            /* ============ insert journal loan Account ================== */
            $journal_loan = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $LFAccount,
                'LPSaldoDebet' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment * $txt_rate) : ($outstanding_db_new->PaymentBalance * $txt_rate),
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? $total_payment : $outstanding_db_new->PaymentBalance,
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_loan;

            if (($total_expense != '') and ( $total_expense > 0)) {
                /* ============ insert journal expense Account ================== */
                /* ================================ get type n sub type account ========================== */
                $type_acc = $this->m_account_journal->m_get_account_type($exp_account);

                /* =============================== find plus in coa, credit or debet ======================== */
                $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                $journal_funding = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $exp_account,
                    'LPSaldoDebet' => $total_expense * $txt_rate,
                    'LPSaldoCredit' => 0,
                    'AmountCurrency' => $total_expense,
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_funding;
            }

            /* ====================== insert journal bank account =============== */
            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => 0,
                'LPSaldoCredit' => (strcmp($outstanding, $txt_amount) !== 0) ? (($total_payment * $txt_rate) + ($total_expense * $txt_rate)) : (($outstanding_db * $txt_rate) + ($total_expense * $txt_rate)),
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : ($outstanding_db + $total_expense),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_bank;
        } elseif ($currency_funding != 'IDR' and $currency_payment == 'IDR') {
            /* ============ insert journal loan Account ================== */
            $journal_funding = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $LFAccount,
                'LPSaldoDebet' => (strcmp($outstanding, $txt_amount) !== 0) ? (($total_payment / $txt_rate) * $rate_piutang) : ($outstanding_db * $rate_piutang),
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? (($total_payment / $txt_rate) * $rate_piutang) : ($outstanding_db * $rate_piutang),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_funding;

            if (($total_expense != '') and ( $total_expense > 0)) {
                /* ============ insert journal expense Account ================== */
                /* ================================ get type n sub type account ========================== */
                $type_acc = $this->m_account_journal->m_get_account_type($exp_account);

                /* =============================== find plus in coa, credit or debet ======================== */
                $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                $journal_funding = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $exp_account,
                    'LPSaldoDebet' => $total_expense,
                    'AmountCurrency' => ($total_expense / $txt_rate),
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_funding;
            }

            if (doubleval($rate_piutang) != doubleval($txt_rate)) {

                /* =============== get account selisih kurs ============================ */
                $rate_account = $this->m_loan_payment->get_rate_account($currency_funding);
                //echo $this->db->last_query();

                $gap_amount = (strcmp($outstanding, $txt_amount) !== 0) ? (($rate_piutang - $txt_rate) * ($total_payment / $txt_rate)) : (($rate_piutang - $txt_rate) * ($outstanding_db));

                /* ====================== insert journal selisih kurs account =============== */
                $journal_bank = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $rate_account,
                    'LPSaldoDebet' => $gap_amount < 0 ? abs($gap_amount) : 0,
                    'LPSaldoCredit' => $gap_amount > 0 ? abs($gap_amount) : 0,
                    'AmountCurrency' => abs($gap_amount),
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $gap_amount < 0 ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_bank;
            }

            /* ====================== insert journal bank account =============== */
            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => 0,
                'LPSaldoCredit' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : (($outstanding_db * $txt_rate) + $total_expense),
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : (($outstanding_db * $txt_rate) + $total_expense),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_bank;
        } elseif ($currency_payment != 'IDR' and $currency_funding != 'IDR') {
            /* ============ insert journal loan Account ================== */
            $journal_funding = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $LFAccount,
                'LPSaldoDebet' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment * $rate_piutang) : ($outstanding_db * $rate_piutang),
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? $total_payment : $outstanding_db,
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_funding;

            if (($total_expense != '') and ( $total_expense > 0)) {
                /* ============ insert journal expense Account ================== */
                /* ================================ get type n sub type account ========================== */
                $type_acc = $this->m_account_journal->m_get_account_type($exp_account);

                /* =============================== find plus in coa, credit or debet ======================== */
                $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                $journal_funding = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $exp_account,
                    'LPSaldoDebet' => ($total_expense * $txt_rate),
                    'AmountCurrency' => $total_expense,
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_funding;
            }

            if (doubleval($rate_piutang) != doubleval($txt_rate)) {

                /* =============== get account selisih kurs ============================ */
                $rate_account = $this->m_loan_payment->get_rate_account($currency_funding);
                //echo $this->db->last_query();

                $gap_amount = (strcmp($outstanding, $txt_amount) !== 0) ? ($rate_piutang - $txt_rate) * $total_payment : ($rate_piutang - $txt_rate) * $outstanding_db;

                /* ====================== insert journal selisih kurs account =============== */
                $journal_bank = array(
                    'LPDate' => $txt_date,
                    'LPNumber' => $LPNumber,
                    'LPAccountNumber' => $rate_account,
                    'LPSaldoDebet' => $gap_amount < 0 ? abs($gap_amount) : 0,
                    'LPSaldoCredit' => $gap_amount > 0 ? abs($gap_amount) : 0,
                    'AmountCurrency' => abs($gap_amount),
                    'LPDesc' => $txt_desc,
                    'LPSignStatus' => $gap_amount < 0 ? 0 : 1,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['insert_journal']['data'][] = $journal_bank;
            }

            /* ====================== insert journal bank account =============== */
            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => 0,
                'LPSaldoCredit' => (strcmp($outstanding, $txt_amount) !== 0) ? (($total_payment + $total_expense) * $txt_rate) : (($outstanding_db + $total_expense) * $txt_rate),
                'AmountCurrency' => (strcmp($outstanding, $txt_amount) !== 0) ? ($total_payment + $total_expense) : ($outstanding_db + $total_expense),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_journal']['data'][] = $journal_bank;
        }

        // echo json_encode($this->trans_data['insert_journal']['data']);
        // die();
    }

    public function insert() {

        $BranchCode = $this->session->userdata('branch');

        $LFNumber = $this->input->post('txt_payment_for');
        $txt_date = date("Y-m-d", strtotime($this->input->post('txt_payment_date')));

        /* =============================== create number payment karyawan ====================== */
        $LPNumber = $this->m_loan_payment->create_loan_payment_number($txt_date);
        /* =============== LPNumber old get from post view ===================== */
        $LPNumber_old = $this->input->post('txt_payment_no');

        $AmountFunding = doubleval($this->input->post('txt_loan_amount'));
        $LFNumber = $this->input->post('txt_payment_for');

        $outstanding_round = doubleval($this->input->post('txt_outstanding_amount'));
        //$outstanding_amount 	= $this->m_loan_payment->get_total_outstanding($LFNumber);
        $outstanding_amount = doubleval($this->input->post('txt_outstanding_amount_hidden'));
        $cmb_bank = $this->input->post('cmb_bank');
        $txt_desc = $this->input->post('txa_description');
        $cheque_number = $this->input->post('cheque_number');
        $txt_rate = doubleval($this->input->post('txt_rate'));
        $total_payment = doubleval($this->input->post('txt_amount_total'));
        $txt_amount = doubleval($this->input->post('txt_amount'));
        $LFAccount = trim($this->input->post('lf_account'));
        $total_expense = doubleval($this->input->post('total_expense'));
        $currency_funding = trim($this->input->post('currency_funding'));
        $currency_payment = trim($this->input->post('currency_payment'));
        $rate_funding = doubleval($this->input->post('rate_funding'));
        $exp_account = trim($this->input->post('exp_account'));
        $exp_amount = doubleval($this->input->post('exp_amount'));

        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

        /* ================== total payment ============================== */
        $total_payment -= $total_expense;
        /* ====================== get expense account numbeer ======================== */
        $currency_code = $this->m_account_journal->get_currency_code('', $exp_account, '');
        $data_account = $this->m_account_journal->get_account_name($exp_account, $currency_code->CurrencyCode);
        $ExpenseAccount = $data_account->AccountNumber;
        /* ============================= end end end end end ========================= */

        $calculate_payment = $this->calculate_loan_payment($LFNumber, $LPNumber, $detail, $total_payment, $outstanding_round, $currency_payment, $currency_funding, $txt_rate, $rate_funding);

        if ($calculate_payment == false) {
            /* ===================== data update lock piutang karyawan =========================== */
            $data_islock_status = array(
                'LFIsLock' => 1
            );

            /* =================================== lock piutang karyawan ===================== */
            $this->trans_data['islock_status']['data'] = $data_islock_status;
            $this->trans_data['islock_status']['TransNumber'] = $LFNumber;

            /* =================================== insert group ============================== */
            $this->insert_group($BranchCode, $txt_date, $LPNumber, $LFNumber, $cmb_bank, $txt_desc, $total_payment, $total_expense, $txt_rate, $currency_payment,$cheque_number);

            /* =================================== insert detail ============================= */
            $this->insert_detail($LPNumber, $LFNumber, $detail, $currency_funding, $currency_payment, $txt_rate, $outstanding_amount);

            /* =================================== insert journal ============================ */
            $this->insert_journal($txt_date, $LPNumber, $LFNumber, $LFAccount, $cmb_bank, $total_payment, $ExpenseAccount, $total_expense, $txt_desc, $currency_funding, $currency_payment, $txt_rate, $rate_funding, $outstanding_round, $txt_amount, $outstanding_amount);

            $result_return = $this->m_loan_payment->insert_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $LFNumber);
            } else {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $LFNumber);
            }

            echo json_encode($result);
        } else {

            $result['status'] = FALSE;
            $result['message'] = get_notification('payment_more', 0);
            echo json_encode($result);
        }
    }

    function calculate_loan_payment($LFNumber, $LPNumber, $detail, $total_payment, $outstanding_amount, $currency_payment, $currency_funding, $txt_rate, $rate_funding) {
        if (($currency_funding == 'IDR') and ( $currency_payment == 'IDR')) {
            $total_payment = $total_payment;
        } elseif (($currency_funding == 'IDR') and ( $currency_payment != 'IDR')) {
            $total_payment = $total_payment * $txt_rate;
        } elseif (($currency_funding != 'IDR') and ( $currency_payment == 'IDR')) {
            $total_payment = $total_payment / $txt_rate;
        } elseif (($currency_funding != 'IDR') and ( $currency_payment != 'IDR')) {
            $total_payment = $total_payment;
        }

        // $result['status'] 	= FALSE;
        // $result['message']	= $total_payment.'  '.$outstanding_amount;
        // echo json_encode($result);
        // die();

        $selisih = ($outstanding_amount - $total_payment);

        if ($selisih >= 0) {
            return false;
        } else {
            return true;
        }
    }

    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    $group_menu = $this->session->userdata('group_menu');
                    // get link from tbl_menu 
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    // set data
                    $CompanyCode = $this->session->userdata('company');
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    // inisialisasi additional parameter
                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());

                    $data['detail'] = $this->m_loan_payment->get_detail($id);
                    //echo $this->db->last_query();

                    $data['piutang_no'] = $this->m_loan_payment->get_piutang_no_detail($id);
                    $data['total_piutang'] = $this->m_loan_payment->get_total_piutang_terakhir($id);
                    $data['balance'] = $this->m_loan_payment->get_payment_balance($id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    // set for view
                    $this->load->view('v_header');
                    $this->load->view('cash_and_bank/loan_payment/v_edit_loan_payment', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    function update_group($BranchCode, $txt_date, $LPNumber, $LFNumber, $cmb_bank, $txa_description, $total_payment, $total_expense, $txt_rate, $currency_code,$cheque_number) {

        $data_group = array(
            'BankAccount' => $cmb_bank,
            'LPDesc' => $txa_description,
            'LPAmount' => $total_payment,
            'ExpAmount' => $total_expense,
            'CurrencyCode' => $currency_code,
            'CurrencyRate' => $txt_rate,
            'ChequeNumber' => $cheque_number,
            'LastUser' => $this->session->userdata('username')
        );

        $this->trans_data['update_group']['data'] = $data_group;
        $this->trans_data['update_group']['TransNumber'] = $LPNumber;
    }

    function update_detail($LPNumber, $LFNumber, $detail, $currency_funding, $currency_payment, $txt_rate, $outstanding_amount) {

        foreach ($detail as $row) {
            if ($currency_payment == $currency_funding) {
                $LoanPayment = doubleval($row->LoanPayment);
                $PaymentPeriod = $row->PaymentPeriod;
                $PaymentPerPeriod = doubleval($row->PaymentPerPeriod1);
                $PaymentBalance = doubleval($outstanding_amount) - doubleval($PaymentPerPeriod);
                $ExpenseAmount = $row->ExpenseAmount1;

                /* ================= get expense account ======================= */
                $currency_code = $this->m_account_journal->get_currency_code('', $row->ExpenseAccount, '');
                $data_account = $this->m_account_journal->get_account_name($row->ExpenseAccount, $currency_code->CurrencyCode);
                $ExpenseAccount = $data_account->AccountNumber;
                /* ================ end end end end end  ======================= */

                $detail_payment = array(
                    'LPNumber' => $LPNumber,
                    'LFNumber' => $LFNumber,
                    'LoanPayment' => $LoanPayment,
                    'PaymentPeriod' => $PaymentPeriod,
                    'PaymentPerPeriod' => $PaymentPerPeriod,
                    'PaymentBalance' => $PaymentBalance,
                    'ExpenseAccount' => $ExpenseAccount,
                    'ExpenseAmount' => $ExpenseAmount,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['update_detail']['data'] = $detail_payment;
                $this->trans_data['update_detail']['TransNumber'] = $LPNumber;
            } else {

                $LoanPayment = $row->LoanPayment;
                $PaymentPeriod = $row->PaymentPeriod;

                /* ================= get expense account ======================= */
                $currency_code = $this->m_account_journal->get_currency_code('', $row->ExpenseAccount, '');
                $data_account = $this->m_account_journal->get_account_name($row->ExpenseAccount, $currency_code->CurrencyCode);
                $ExpenseAccount = $data_account->AccountNumber;
                /* ================ end end end end end  ======================= */

                if (($currency_payment == 'IDR') and ( $currency_funding != 'IDR')) {
                    $PaymentPerPeriod = doubleval($row->PaymentPerPeriod2) / $txt_rate;
                    $PaymentBalance = $outstanding_amount - $PaymentPerPeriod;
                    $ExpenseAmount = doubleval($row->ExpenseAmount2) / $txt_rate;
                } elseif (($currency_payment != 'IDR') and ( $currency_funding == 'IDR')) {
                    $PaymentPerPeriod = doubleval($row->PaymentPerPeriod2) * $txt_rate;
                    $PaymentBalance = $outstanding_amount - $PaymentPerPeriod;
                    $ExpenseAmount = doubleval($row->ExpenseAmount2) * $txt_rate;
                }

                $detail_payment = array(
                    'LPNumber' => $LPNumber,
                    'LFNumber' => $LFNumber,
                    'LoanPayment' => $LoanPayment,
                    'PaymentPeriod' => $PaymentPeriod,
                    'PaymentPerPeriod' => $PaymentPerPeriod,
                    'PaymentBalance' => $PaymentBalance,
                    'ExpenseAccount' => $ExpenseAccount,
                    'ExpenseAmount' => $ExpenseAmount,
                    'LastUser' => $this->session->userdata('username')
                );

                $this->trans_data['update_detail']['data'] = $detail_payment;
                $this->trans_data['update_detail']['TransNumber'] = $LPNumber;
            }
        }
    }

    public function update() {
        $LFNumber = trim($this->input->post('txt_payment_for'));
        $LPNumber = trim($this->input->post('txt_payment_no'));
        $cmb_bank = trim($this->input->post('cmb_bank'));
        $txt_date = date('Y-m-d', strtotime($this->input->post('txt_payment_date')));
        $txa_description = trim($this->input->post('txa_description'));
        $txt_amount = doubleval($this->input->post('txt_amount'));
        $txt_amount_total = doubleval($this->input->post('txt_amount_total'));
        $cheque_number = $this->input->post('cheque_number');
        $LFAccount = trim($this->input->post('lf_account'));
        $txt_rate = doubleval($this->input->post('txt_rate'));
        $exp_account = trim($this->input->post('exp_account'));
        $exp_amount = doubleval($this->input->post('exp_amount'));
        $currency_funding = trim($this->input->post('currency_funding'));
        $currency_payment = trim($this->input->post('currency_payment'));
        $rate_piutang = doubleval($this->input->post('rate_funding'));
        $loan_amount = doubleval($this->input->post('txt_loan_amount'));
        $total_expense = doubleval($this->input->post('total_expense'));
        $outstanding_round = doubleval($this->input->post('txt_outstanding_amount'));
        $outstanding_amount = doubleval($this->input->post('txt_outstanding_amount_hidden'));

        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $BranchCode = $this->session->userdata('branch');

        $currency_code = $this->m_account_journal->get_currency_code('', $exp_account, '');
        $data_account = $this->m_account_journal->get_account_name($exp_account, $currency_code->CurrencyCode);
        $ExpenseAccount = $data_account->AccountNumber;

        /* ================== penting perhitungan txt_amount di ganti variabel ini =============================== */
        $total_payment = $txt_amount_total - $total_expense;
        /* ======================================================================================================== */

        $calculate_payment = $this->calculate_loan_payment($LFNumber, $LPNumber, $detail, $total_payment, $outstanding_round, $currency_payment, $currency_funding, $txt_rate, $rate_piutang);

        if ($calculate_payment == FALSE) {

            /* =================================== set update group ================================= */
            $this->update_group($BranchCode, $txt_date, $LPNumber, $LFNumber, $cmb_bank, $txa_description, $total_payment, $total_expense, $txt_rate, $currency_payment,$cheque_number);

            /* =================================== set update detail ================================ */
            $this->update_detail($LPNumber, $LFNumber, $detail, $currency_funding, $currency_payment, $txt_rate, $outstanding_amount);

            /* =================================== set delete journal ================================ */
            $this->trans_data['delete_journal']['TransNumber'] = $LPNumber;

            /* =================================== set insert journal ================================ */
            $this->insert_journal($txt_date, $LPNumber, $LFNumber, $LFAccount, $cmb_bank, $total_payment, $ExpenseAccount, $total_expense, $txa_description, $currency_funding, $currency_payment, $txt_rate, $rate_piutang, $outstanding_round, $txt_amount, $outstanding_amount);

            $result_return = $this->m_loan_payment->update_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, $LPNumber);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $LPNumber);
            }
            echo json_encode($result);
        } else {
            $result['status'] = FALSE;
            $result['message'] = get_notification('payment_more', 0);
            echo json_encode($result);
        }
    }

    function approved_dir() {
        $txt_payment_no = $this->input->post('txt_payment_no');
        $period = $this->input->post('pay_period');
        $pay_balance = $this->input->post('pay_balance');

        $data_approval = array(
            "TransStatus" => 2,
            "AppFinished" => 1,
            "AppLevel2Status" => 1,
            "AppLevel2Code" => $this->session->userdata('username'),
            "AppLevel2Date" => date('Y-m-d'),
            "LastUser" => $this->session->userdata('username')
        );

        /* =============== data update islock =========================================== */
        $data_islock = array('LFIsLock' => 0);

        /* ==============  data update piutang menjadi finish =========================== */
        $data_piutang_finished = array('TransStatus' => 2);

        /* ============================= get LFNumber / no piutang karyawan ============ */
        $data_payment = $this->m_loan_payment->get_piutang_number($txt_payment_no);

        $no_piutang = $data_payment['LFNumber'];

        $cek_status_piutang = $this->m_loan_payment->m_cek_status_piutang($no_piutang);

        /* ================================= piutang ============================================= */
        $piutang = $this->m_loan_payment->m_get_total_piutang($no_piutang);

        /* ================================= get total payment ========================================== */
        $total_payment = $this->m_loan_payment->m_get_total_payment($no_piutang);

        $cek_payment = $piutang['LFAmount'] - ($total_payment + $piutang['JVoucherBalance']);

        if ($cek_status_piutang == false) {

            $result['status'] = false;
            $result['message'] = get_notification('approved_transaksi', 0);
            echo json_encode($result);
        } elseif ($cek_payment < 0) {

            $result['status'] = false;
            $result['message'] = get_notification('JVB', 0);
            echo json_encode($result);
        } else {

            /* =============================set Update payment =================================== */
            $this->trans_data['approve_data']['data'] = $data_approval;
            $this->trans_data['approve_data']['TransNumber'] = $txt_payment_no;

            /* ============================= set update islock =================================== */
            $this->trans_data['islock_status']['data'] = $data_islock;
            $this->trans_data['islock_status']['TransNumber'] = $no_piutang;

            $this->trans_data['update_piutang']['total'] = 0;
            $pay_balance = round($pay_balance, 2, PHP_ROUND_HALF_UP);

            if ($pay_balance <= 0) {
                $this->trans_data['update_piutang']['total'] = 1;
                $this->trans_data['update_piutang']['data'] = $data_piutang_finished;
                $this->trans_data['update_piutang']['TransNumber'] = $no_piutang;
            }

            $result_return = $this->m_loan_payment->approve_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'approve', 1, $txt_payment_no);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'approve', 0, $txt_payment_no);
            }

            echo json_encode($result);
        }
    }

    public function reversed_data() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $txt_payment_no = $this->input->post('id');

        $arr_no = explode("/", $txt_payment_no);
        $no_transaction = substr($arr_no[1], 0, 4);
        $month_transaction = (int) substr($no_transaction, 0, 2);
        $year_transaction = ((int) substr($no_transaction, 2, 2)) + 2000;

        $date_transaction = $year_transaction . $month_transaction;

        $data_reversed_payment = array(
            'AppLevel1Status' => 0,
            'AppLevel1Code' => null,
            'AppLevel1Date' => 0,
            'TransStatus' => 5,
            'AppFinished' => 0,
        );

        $data_reversed_piutang = array(
            'TransStatus' => 1,
            'LFIsLock' => 1
        );

        /* ============================= get LFNumber / no piutang karyawan ============ */
        $data_payment = $this->m_loan_payment->get_piutang_number($txt_payment_no);

        $no_piutang = $data_payment['LFNumber'];
        $payment_period = $data_payment['PaymentPeriod'];

        /* =============================== get max period ========================================= */
        $max_period = $this->m_loan_payment->get_max_period_finished($no_piutang);

        /* ============================== check period end ======================================== */
        $check_period = $this->m_loan_payment->check_period_end($date_transaction);

        $cek_loan_payment_journal = $this->m_loan_payment->m_cek_loan_payment_journal($no_piutang);

        if ($check_period == false) {

            if ($payment_period == $max_period) {

                if ($cek_loan_payment_journal == FALSE) {

                    /* ============================= set reverse payment =================================== */
                    $this->trans_data['reverse_payment']['data'] = $data_reversed_payment;
                    $this->trans_data['reverse_payment']['TransNumber'] = $txt_payment_no;

                    /* =============================set update edebt/ reverse =================================== */
                    $this->trans_data['reverse_piutang']['data'] = $data_reversed_piutang;
                    $this->trans_data['reverse_piutang']['TransNumber'] = $no_piutang;

                    /* ============================= set delete reconcile =============================================== */
                    $this->trans_data['delete_reconcile']['TransNumber'] = $txt_payment_no;

                    $result_return = $this->m_loan_payment->reverse_transsaction($this->trans_data);

                    $this->trans_data = [];

                    if ($result_return) {
                        $result['status'] = true;
                        $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_payment_no);
                    } else {
                        $result['status'] = false;
                        $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_payment_no);
                    }

                    echo json_encode($result);
                } else {

                    $no_loan_payment_journal = $this->m_loan_payment->get_no_loan_payment_journal($no_piutang);
                    $result['status'] = false;
                    $result['message'] = get_notification('reverse_transaksi', 0) . ' ' . $no_loan_payment_journal;
                    echo json_encode($result);
                }
            } else {

                $result['status'] = false;
                $result['message'] = get_notification('max_period', 0);
                echo json_encode($result);
            }
        } else {

            $result['status'] = false;
            $result['message'] = get_notification('reverse_in_period', 0);
            echo json_encode($result);
        }
    }

    public function to_journal($id) {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');
        $payment_number = str_replace($data['menu_link'] . '/to_journal/', "", $this->uri->uri_string());
        $explode_branch = explode('/', $payment_number);
        $branch_explode = $explode_branch[0];

        $data['date_journal'] = $this->m_loan_payment->get_date_journal_payment($payment_number);
        $data['list_jurnal'] = $this->m_loan_payment->get_all_journal_payment($payment_number, $branch_explode);
        //echo $this->db->last_query();

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment/v_print_journal_loan_payment', $data);
        $this->load->view('v_footer');
    }

    public function suspend_data() {
        $id = $this->input->post('id');

        $payment_no = str_replace(".", "/", $id);

        /* ========================== get piutang no ============================ */
        $piutang_no = $this->m_loan_payment->get_adebt_number($payment_no);

        /* ============================= set data update payment ================= */
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );

        /* ============================= set data update piutang ================== */
        $data_islock_status = array(
            'LFIsLock' => 0
        );

        /* ========================== set update is lock piutang ===================== */
        /* =================================== lock piutang karyawan ===================== */
        $this->trans_data['islock_status']['data'] = $data_islock_status;
        $this->trans_data['islock_status']['TransNumber'] = $piutang_no;

        /* ========================== set update trans status ======================== */
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $payment_no;

        $result_return = $this->m_loan_payment->suspend_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'suspend', 1, $payment_no);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'suspend', 0, $payment_no);
        }

        echo json_encode($result);
    }

    public function to_print_detail() {

        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $BranchCode = $this->session->userdata('branch');

        $payment_no = str_replace($data['menu_link'] . '/to_print_detail/', "", $this->uri->uri_string());

        if ($payment_no != "") {

            $data['list_transaksi'] = $this->m_loan_payment->get_detail_item_print($payment_no);
            //$data['list_receipt'] 		= $this->m_loan_payment->get_detail_item_print($id,$BranchCode,'!='); 
            // echo $this->db->last_query();

            $this->load->view('v_header');
            $this->load->view('cash_and_bank/loan_payment/v_print_detail_loan_payment', $data);
            $this->load->view('v_footer');
        }
    }

    function get_bank_balance() {
        $AccountNumber = $this->input->post('AccountNumber');
        $branch = $this->session->userdata('branch');

        $bank_balance = $this->m_account_journal->m_get_bank_balance($branch, $AccountNumber);

        if ($bank_balance == false) {
            $return = array('message' => false, 'value' => 0);
        } else {
            $return = array('message' => true, 'value' => $bank_balance);
        }

        echo json_encode($return);
    }

}
