<?php

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

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

class Loan_payment_journal extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 391;
    public $menu_model = '';
    public $name = 'Loan Payment Journal';
    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_journal');
        $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_journal/v_loan_payment_journal', $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('am_branch', 'at_loanpayment_journal.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee as created_by', 'at_loanpayment_journal.CreatedBy=created_by.EmployeeCode', 'LEFT');

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

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


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


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

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

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

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

        /* ========================end======================================= */
        $result = $this->m_loan_payment_journal->get_all(1);

        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]->LJNumber,
                'LJDate' => $result[$i]->LJDate,
                'LJAmount' => $result[$i]->LJAmount,
                'LJDesc' => $result[$i]->LJDesc,
                'TransStatus' => $TransStatus,
                '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_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_loan_payment_journal->get_all_to_print($this->session->userdata('branch'));

        $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_journal->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment_journal/v_preview_loan_payment_journal', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_loan_payment_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_loan_payment_journal->get_all_to_print($this->session->userdata('branch'));

        $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_journal/v_preview_loan_payment_journal', $data);
        $this->load->view('v_footer');
    }

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

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/loan_payment_journal/v_preview_loan_payment_journal', $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_journal'] = $this->m_loan_payment_journal->create_loan_payment_number(date('d-m-Y'), 1);
                    $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_journal/v_new_loan_payment_journal', $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_journal->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_journal->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_journal->m_get_expense_account($branch);

        echo $expense_account;
    }

    public function get_all_account() {
        $branch = $this->session->userdata('branch');
        $all_account = $this->m_loan_payment_journal->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_journal->get_akun_bank_edit($branch_explode);
        echo $list_akun;
    }

    public function get_piutang() {
        $BranchCode = $this->session->userdata('branch');
        $list_piutang = $this->m_loan_payment_journal->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;

            $outstanding = $this->m_loan_payment_journal->get_sisa_piutang($LFNumber);

            $total_payment = $outstanding->total_payment;
            $total_expense = $outstanding->TotalExpense;



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

            if (empty($outstanding)) {
                $outstanding = $outstanding;
            } else {
                $outstanding = $row->LFAmount;
            }


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

            $hasil[] = array(
                'LFAmount' => $row->LFAmount,
                'BranchName' => $row->BranchName,
                'BranchCode' => $row->BranchCode,
                'AccountName' => $row->AccountName,
                'LFAccount' => $row->LFAccount,
                'LFNumber' => $row->LFNumber,
                'LFIsLock' => $IsLock,
                'LFDesc' => $row->LFDesc,
                'CurrencyCode' => $row->CurrencyCode,
                'CurrencyRate' => $row->CurrencyRate,
                'outstanding' => $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_journal->get_company_edit($branch_explode);
        echo "$list_company";
    }

    public function get_company() {
        $branch = $this->session->userdata('branch');
        $list_company = $this->m_loan_payment_journal->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);
        $LFNumber = $uri4 . "/" . $uri5 . "/" . $uri6;
        $payment_period = $this->uri->segment(7);
        $currency_payment = $this->uri->segment(8);

        $list_payment = $this->m_loan_payment_journal->get_payment_periode($LFNumber, $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_journal->get_payment_periode_cancel($payment_before);

        echo"$list_payment";
    }

    public function get_history_payment($LJNumber) {

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

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


        $result = $this->m_loan_payment_journal->get_history_payment($LJNumber);

        echo json_encode($result);
    }

    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, $LJNumber, $LFNumber, $txt_desc, $txt_amount, $txt_rate, $currency_payment) {

        $data_payment = array(
            'BranchCode' => $BranchCode,
            'LJDate' => $txt_date,
            'LJNumber' => $LJNumber,
            'LFNumber' => $LFNumber,
            'LJDesc' => $txt_desc,
            'TransStatus' => 5,
            'LJAmount' => $txt_amount,
            'CurrencyCode' => $currency_payment,
            'CurrencyRate' => $txt_rate,
            'Payment_Type' => 1,
            '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;
    }

    public function insert_detail($detail, $LJNumber) {

        foreach ($detail as $row) {

            /* =============================== get account number ============================== */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $currency_code->CurrencyCode, '1');

            $detail_data = array(
                'LJNumber' => $LJNumber,
                'LJAccountNumber' => $acc_number->AccountNumber,
                'LJAmount' => $row->PaymentAmount,
                'LJMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

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

    public function insert_journal($detail, $txt_date, $LFNumber, $LJNumber, $LFAccount, $txt_amount, $txt_desc, $txt_rate, $rate_funding, $currency_payment) {

        $outstanding_db_new = $this->m_loan_payment_journal->get_sisa_piutang_new($LFNumber);
        $outstanding_balance = $outstanding_db_new->PaymentBalance;

        $journal_credit = array(
            'LJDate' => $txt_date,
            'LJNumber' => $LJNumber,
            'LJAccountNumber' => $LFAccount,
            'LJSaldoDebet' => (doubleval($outstanding_balance) * doubleval($rate_funding)),
            'LJSaldoCredit' => 0,
            'AmountCurrency' => $outstanding_balance,
            'LJDesc' => $txt_desc,
            'LJSignStatus' => 1,
            'LastUser' => $this->session->userdata('username')
        );

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

        foreach ($detail as $row) {

            /* =============================== get account number ============================== */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $currency_code->CurrencyCode, '1');

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

            /* =============================== 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_debet = array(
                'LJDate' => $txt_date,
                'LJNumber' => $LJNumber,
                'LJAccountNumber' => $acc_number->AccountNumber,
                'LJSaldoDebet' => 0,
                'LJSaldoCredit' => (doubleval($row->PaymentAmount) * doubleval($txt_rate)),
                'AmountCurrency' => $row->PaymentAmount,
                'LJDesc' => $txt_desc,
                'LJSignStatus' => $debet_credit == 'Debet' ? 1 : 0,
                'LastUser' => $this->session->userdata('username')
            );

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

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

            /* =============== get account selisih kurs ============================ */
            $rate_account = $this->m_loan_payment_journal->get_rate_account($currency_payment);

            $gap_amount = (doubleval($rate_funding) - doubleval($txt_rate)) * doubleval($outstanding_balance);

            /* ====================== insert journal selisih kurs account =============== */
            $journal_bank = array(
                'LJDate' => $txt_date,
                'LJNumber' => $LJNumber,
                'LJAccountNumber' => $rate_account,
                'LJSaldoDebet' => $gap_amount < 0 ? abs($gap_amount) : 0,
                'LJSaldoCredit' => $gap_amount > 0 ? abs($gap_amount) : 0,
                'AmountCurrency' => abs($gap_amount),
                'LJDesc' => $txt_desc,
                'LJSignStatus' => $gap_amount < 0 ? 0 : 1,
                'LastUser' => $this->session->userdata('username')
            );

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

    function insert_journal_lama($txt_date, $LPNumber, $LFAccount, $cmb_bank, $txt_amount, $exp_account, $exp_amount, $txt_desc, $currency_funding, $currency_payment, $txt_rate, $rate_piutang, $total_piutang) {

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

            $this->m_loan_payment_journal->insert_journal($journal_funding);

            /* ====================== insert journal bank account =============== */
            $account_journal = $this->m_account_journal->m_get_account_type($cmb_bank);

            $debet_credit = $this->m_account_journal->debet_kredit($account_journal->Type_Name, $account_journal->Sub_Type_Name);

            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => $debet_credit == 'Debet' ? 0 : $txt_amount,
                'LPSaldoCredit' => $debet_credit == 'Credit' ? 0 : $txt_amount,
                'AmountCurrency' => $txt_amount,
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_loan_payment_journal->insert_journal($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' => $txt_amount,
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (doubleval($txt_amount) / doubleval($txt_rate)),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_loan_payment_journal->insert_journal($journal_funding);

            /* ====================== insert journal bank account =============== */
            $account_journal = $this->m_account_journal->m_get_account_type($cmb_bank);

            $debet_credit = $this->m_account_journal->debet_kredit($account_journal->Type_Name, $account_journal->Sub_Type_Name);

            $journal_bank = array(
                'LPDate' => $txt_date,
                'LPNumber' => $LPNumber,
                'LPAccountNumber' => $cmb_bank,
                'LPSaldoDebet' => $debet_credit == 'Debet' ? 0 : (doubleval($txt_amount) + doubleval($exp_amount)),
                'LPSaldoCredit' => $debet_credit == 'Credit' ? 0 : (doubleval($txt_amount) + doubleval($exp_amount)),
                'AmountCurrency' => (doubleval($txt_amount) / doubleval($txt_rate)) + (doubleval($exp_amount) / doubleval($txt_rate)),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_loan_payment_journal->insert_journal($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' => (doubleval($txt_amount) * doubleval($txt_rate)),
                'LPSaldoCredit' => 0,
                'AmountCurrency' => (doubleval($txt_amount) * doubleval($txt_rate)),
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_loan_payment_journal->insert_journal($journal_funding);

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

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

                $gap_amount = (doubleval($rate_piutang) - doubleval($txt_rate)) * doubleval($total_piutang);

                /* ====================== 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->m_loan_payment_journal->insert_journal($journal_bank);
            }

            /* ====================== insert journal bank account =============== */

            $account_journal = $this->m_account_journal->m_get_account_type($cmb_bank);

            $debet_credit = $this->m_account_journal->debet_kredit($account_journal->Type_Name, $account_journal->Sub_Type_Name);

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

            $this->m_loan_payment_journal->insert_journal($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' => (doubleval($txt_amount) * doubleval($txt_rate)),
                'LPSaldoCredit' => 0,
                'AmountCurrency' => $txt_amount,
                'LPDesc' => $txt_desc,
                'LPSignStatus' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_loan_payment_journal->insert_journal($journal_funding);

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

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

                $gap_amount = (doubleval($rate_piutang) - doubleval($txt_rate)) * doubleval($total_piutang);

                /* ====================== 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->m_loan_payment_journal->insert_journal($journal_bank);
            }

            /* ====================== insert journal bank account =============== */

            $account_journal = $this->m_account_journal->m_get_account_type($cmb_bank);

            $debet_credit = $this->m_account_journal->debet_kredit($account_journal->Type_Name, $account_journal->Sub_Type_Name);

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

            $this->m_loan_payment_journal->insert_journal($journal_bank);
        }
    }

    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 ====================== */
        $LJNumber = $this->m_loan_payment_journal->create_loan_payment_number($txt_date, 1);

        $LFAccount = trim($this->input->post('hutang_code'));
        $txt_desc = $this->input->post('txa_memo');
        $txt_amount = $this->input->post('txt_amount');
        $txt_rate = $this->input->post('txt_rate');
        $rate_funding = $this->input->post('rate_funding');
        $currency_funding = $this->input->post('currency_funding');
        $currency_payment = 'IDR';
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

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

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

        /* =================================== set insert group ============================== */
        $this->insert_group($BranchCode, $txt_date, $LJNumber, $LFNumber, $txt_desc, $txt_amount, $txt_rate, $currency_funding);

        /* =================================== set insert detail ============================= */
        $this->insert_detail($detail, $LJNumber);

        /* =================================== set insert journal ============================ */
        $this->insert_journal($detail, $txt_date, $LFNumber, $LJNumber, $LFAccount, $txt_amount, $txt_desc, $txt_rate, $rate_funding, $currency_funding);

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    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_journal->get_detail($id);
                    //echo $this->db->last_query();

                    $data['piutang_no'] = $this->m_loan_payment_journal->get_piutang_no_detail($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_journal/v_edit_loan_payment_journal', $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, $LJNumber, $LFNumber, $txt_desc, $txt_amount, $txt_rate, $currency_payment) {

        $data_group = array(
            'LJDesc' => $txt_desc,
            'LJAmount' => $txt_amount,
            'CurrencyCode' => $currency_payment,
            'CurrencyRate' => $txt_rate,
            'LastUser' => $this->session->userdata('username')
        );

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

    function update_detail($detail, $LJNumber) {
        foreach ($detail as $row) {
            /* =============================== get account number ============================== */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $currency_code->CurrencyCode, '1');

            $detail_data = array(
                'LJNumber' => $LJNumber,
                'LJAccountNumber' => $acc_number->AccountNumber,
                'LJAmount' => $row->PaymentAmount,
                'LJMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['update_detail']['data'][] = $detail_data;
            $this->trans_data['update_detail']['LJDetailID'][] = $row->LJDetailID;
        }
    }

    public function update() {

        $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 ====================== */
        $LJNumber = trim($this->input->post('payment_loan_no'));

        $LFAccount = trim($this->input->post('hutang_code'));
        $txt_desc = $this->input->post('txa_memo');
        $txt_amount = $this->input->post('txt_amount');
        $txt_rate = $this->input->post('txt_rate');
        $rate_funding = $this->input->post('rate_funding');
        $currency_funding = $this->input->post('currency_funding');
        $currency_payment = $currency_funding;
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);

        /* =================================== update group ================================= */
        $this->update_group($BranchCode, $txt_date, $LJNumber, $LFNumber, $txt_desc, $txt_amount, $txt_rate, $currency_payment);

        /* =================================== set delete detail ================================================ */
        $this->trans_data['delete_detail']['total'] = count($detail_id);

        if (count($detail_id) > 0) {
            foreach ($detail_id as $LJDetailID) {
                $this->trans_data['delete_detail']['LJDetailID'][] = $LJDetailID;
            }
        }

        /* =================================== set update detail ================================ */
        $this->update_detail($detail, $LJNumber);

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

        /* =================================== set insert journal ================================ */
        $this->insert_journal($detail, $txt_date, $LFNumber, $LJNumber, $LFAccount, $txt_amount, $txt_desc, $txt_rate, $rate_funding, $currency_payment);

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    function approved_dir() {
        $txt_payment_no = $this->input->post('payment_loan_no');
        $LFNumber = $this->input->post('txt_payment_for');
        $txt_amount = $this->input->post('txt_amount');

        $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);

        $cek_status_piutang = $this->m_loan_payment_journal->m_cek_status_piutang($LFNumber);

        /* ================================= piutang ============================================= */
        $piutang = $this->m_loan_payment_journal->m_get_total_piutang($LFNumber);

        /* ================================= get total payment ========================================== */
        $total_payment = $this->m_loan_payment_journal->m_get_total_payment($LFNumber);

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

        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 {

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

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

            $this->trans_data['update_piutang']['data'] = $data_piutang_finished;
            $this->trans_data['update_piutang']['TransNumber'] = $LFNumber;

            $result_return = $this->m_loan_payment_journal->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_journal->get_piutang_number($txt_payment_no);

        $no_piutang = $data_payment['LFNumber'];

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

        if ($check_period == 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_journal->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 {

            $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_journal->get_date_journal_payment($payment_number);
        $data['list_jurnal'] = $this->m_loan_payment_journal->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_journal/v_print_journal_loan_payment_journal', $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_journal->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 ===================== */
        $this->trans_data['islock_status']['TransNumber'] = $piutang_no;
        $this->trans_data['islock_status']['data'] = $data_islock_status;

        /* ========================== 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_journal->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['detail'] = $this->m_loan_payment_journal->get_detail_item_print($payment_no);
            $data['list'] = $this->m_loan_payment_journal->get_detail_item_print_journal($payment_no, $BranchCode);

            $this->load->view('v_header');
            $this->load->view('cash_and_bank/loan_payment_journal/v_print_detail_loan_payment_journal', $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);
    }

    function get_gl_account($CurrencyCode='') {
        $branch = $this->session->userdata('branch');
        $result = $this->m_loan_payment_journal->m_get_gl_account($branch,$CurrencyCode);
        echo json_encode($result);
    }

}
