<?php

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

/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 20-07-2014	
 * 	Revisi 	: Fachri
 */

class purchases_expense_real extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 245;
    // 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 $name = "Expense Payment";
    public $trans_data = array();

    public function __construct() {
        parent::__construct();

        $this->load->model('m_menu');
        $this->load->model('m_expensecashbon_payment');
        $this->load->model('m_account_journal');
        $this->load->helper('message');
        $this->load->helper('custom_string_helper');
        $this->load->model('m_expense_cashbon');
        $this->load->model('custom/m_custom');
        $this->load->helper('convert_date');
        $this->load->helper('status');
        $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() {
        //untuk cek login dan menu apakah bisa diakses oleh user yang login
        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 {
                    //untuk ambil data dari session dan hak akses
                    $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('expense_cashbon/v_purchases_expense_real', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function add($no_piutang = null) {
        //untuk cek login dan menu apakah bisa diakses oleh user yang login
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group_add($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 {
                    //untuk ambil data dari session dan hak akses
                    $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);

                    if ($no_piutang != null) {
                        $no_piutang = str_replace($data['menu_link'] . '/add/', "", $this->uri->uri_string());
                        $data['no_piutang'] = $no_piutang;
                        $data_cashbon = $this->m_expensecashbon_payment->get_data_cashbon($no_piutang);
                        $data['employee'] = $data_cashbon->EmployeeCode;
                        $data['TransStatus'] = $data_cashbon->TransStatus;
                        $data['IsLock'] = $data_cashbon->EBonLockStatus;
                    } else {
                        $data['no_piutang'] = '';
                        $data['TransStatus'] = '';
                        $data['employee'] = '';
                        $data['IsLock'] = '';
                    }



                    $data['exp_payment_number'] = $this->m_expensecashbon_payment->create_epay_number(date('d-m-Y'));
                    $department = $this->m_custom->get_department_by_name('EXIM');
                    $data['department_code'] = $department[0]->DepartmentCode;
                    $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('expense_cashbon/v_new_purchase_expense_real', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax_list_payment() {
        $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================= */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

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


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_expensepayment.EPayDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_expensepayment.EPayDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

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

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_expensecashbon_payment->get_all();
        //echo $this->db->last_query();

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

            $hasil[] = array(
                'BranchName' => $result[$i]->BranchName,
                'EmployeeName' => $result[$i]->EmployeeName,
                'TransNumber' => $result[$i]->EPayNumber,
                'EPayDate' => $result[$i]->EPayDate,
                'amountPayment' => $result[$i]->amountPayment,
                'EPayAmount' => $result[$i]->amountPayment,
                'cashbonPayment' => $result[$i]->EBonAmount,
                'EPayDesc' => $result[$i]->EPayDesc,
                'TransStatus' => $TransStatus,
                'DepartmentName' => $result[$i]->DepartmentName,
                'CreatedBy' => $result[$i]->nm_createdby
            );
        }

        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_list() {
        // set data
        $CompanyCode = $this->session->userdata('company');
        $lists = $this->m_expensecashbon_payment->get_all($CompanyCode);
        $data['list'] = json_encode($lists);
        $this->load->view('v_header');
        $this->load->view('expense_cashbon/v_print_expense_payment', $data);
        $this->load->view('v_footer');
    }

    public function ajax_list_cashbon($EmpCode) {
        $replace_emp_code = str_replace('_', '-', $EmpCode);
        $result = $this->m_expensecashbon_payment->get_list_cashbon($replace_emp_code);

        //echo $this->db->last_query();
        $hasil = '';
        foreach ($result as $row) {
            $EBonDate = convert_to_dmy($row->EBonDate);

            if ($row->EBonLockStatus == 1) {
                $Lock = "Lock";
            } else {
                $Lock = "Un Lock";
            }

            $hasil[] = array(
                'EBonNumber' => $row->EBonNumber,
                'EBonDate' => $EBonDate,
                'EBonAmount' => $row->EBonAmount,
                'CurrencyCode' => $row->CurrencyCode,
                'CurrencyRate' => $row->CurrencyRate,
                'BankPayment' => $row->BankPayment,
                'BankName' => $row->AccountName,
                'EBonAccountNumber' => $row->EBonAccountNumber,
                'EBonLockStatus' => $Lock,
                'EBonDesc' => $row->EBonDesc,
                'ExpCategoryID' => $row->ExpCategoryID
            );
        }

        echo json_encode($hasil);
    }

    public function get_expense_group($ExpCategoryID) {
        // $replace_akun = str_replace('_','-',$ebon_akun);

        $expense_group = $this->m_expensecashbon_payment->get_list_expense_group($ExpCategoryID);
        echo "$expense_group";
    }

    public function ajax_list_item_group_expense($Groupid) {
        $list_item_expense_group = $this->m_expensecashbon_payment->get_list_item_expense_group($Groupid);
        echo"$list_item_expense_group";
    }

    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status'] = false;
        $result['message'] = get_notification_transaksi($this->name, $modus, 0);

        echo json_encode($result);
        die();
    }

    public function insert_group($BranchCode, $DepartmentCode, $EmployeeCode, $EPayDate, $EPayNumber, $EBonNumber, $EPayDesc, $curren_code_casbon, $total_payment, $txt_rate) {
        $data_payment = array(
            'BranchCode' => $BranchCode,
            'DepartmentCode' => $DepartmentCode,
            'EmployeeCode' => $EmployeeCode,
            'EPayDate' => $EPayDate,
            'EPayNumber' => $EPayNumber,
            'EBonNumber' => $EBonNumber,
            'EPayDesc' => $EPayDesc,
            'CurrencyCode' => $curren_code_casbon,
            'EPayAmount' => $total_payment,
            'EPayRate' => $txt_rate,
            'TransStatus' => 4,
            'CreatedBy' => $this->session->userdata('username'),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expensecashbon_payment->insert_payment_cashbon($data_payment);
        $this->trans_data['insert_group']['data'] = $data_payment;
    }

    public function insert_detail($detail_pay, $EPayNumber, $ExpGroupId, $curren_code_casbon, $txt_rate) {
        foreach ($detail_pay as $details) {

            $ExpDetailID = $details->ExpDetailID;
            $ExpDetailName = $details->ExpDetailName;
            $ExpDetailDesc = $details->ExpDetailDesc;
            $ItemAmount = $details->ItemAmount;
            if ($curren_code_casbon == "IDR") {
                $TotalAmount = $ItemAmount * 1;
            } else {
                $TotalAmount = $ItemAmount * $txt_rate;
            }

            $detail_payment = array(
                'EPayNumber' => $EPayNumber,
                'ExpCategoryID' => $ExpGroupId,
                'ExpCategoryName' => $ExpDetailName,
                'ExpenseDesc' => $ExpDetailDesc,
                'ExpenseAmount' => $ItemAmount,
                'ExpenseTotalAmount' => $TotalAmount,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_detail_payment_cashbon($detail_payment);
            $this->trans_data['insert_detail']['data'][] = $detail_payment;
        }
    }

    public function insert_detail_cpvr($cek_selisih, $detail_cpvr, $EPayDate, $EPayNumber, $curren_code, $curren_code_casbon, $total_payment, $update) {

        $BranchCode = $this->session->userdata('branch');
        $bulan = date('m');
        $tahun = date('y');
        $cek_tahun = date('Y');
        $kode = "ER";

        if ($cek_selisih > 0) {

            foreach ($detail_cpvr as $row) {

                $AccountNumber = $row->BankCode;

                $PaymentAmount = $row->AmountDiff;

                $bank_id = $this->m_expensecashbon_payment->get_bank_id($AccountNumber);
                $bank_code_masuk = $this->m_expensecashbon_payment->get_bank_code_keluar($bank_id);

                $crv_no = $this->m_expensecashbon_payment->count_crv_number($bulan, $cek_tahun);

                $crv_number = $this->m_expensecashbon_payment->create_crv_number($EPayDate, $bank_code_masuk);

                $EPRealNumber = $crv_number;
                $BankReceipt = $AccountNumber;
                $EPRealAmount = $PaymentAmount;
                $EPRealExpense = $total_payment;
                $CurrencyCode = $curren_code_casbon;
                $EPRealTransType = 1;
            }
        } elseif ($cek_selisih < 0) {

            foreach ($detail_cpvr as $row) {

                $AccountNumber = $row->BankCode;

                $PaymentAmount = $row->AmountDiff;


                $bank_id = $this->m_expensecashbon_payment->get_bank_id($AccountNumber);
                $bank_code_keluar = $this->m_expensecashbon_payment->get_bank_code_keluar($bank_id);

                $cpv_no = $this->m_expensecashbon_payment->count_cpv_number($bulan, $cek_tahun);

                $cpv_number = $this->m_expensecashbon_payment->create_crv_number($EPayDate, $bank_code_keluar);

                $EPRealNumber = $cpv_number;
                $BankReceipt = $AccountNumber;
                $EPRealAmount = $PaymentAmount;
                $EPRealExpense = $total_payment;
                $CurrencyCode = $curren_code_casbon;
                $EPRealTransType = 2;
            }
        } else {

            $bank_code_masuk = "";
            $cpv_number = $this->m_expensecashbon_payment->create_crv_number($EPayDate, $bank_code_masuk);


            $EPRealNumber = $cpv_number;
            $BankReceipt = 0;
            $EPRealAmount = 0;
            $EPRealExpense = 0;
            $CurrencyCode = $curren_code_casbon;
            $EPRealTransType = 2;
        }

        $detail_data = array(
            'EPRealDate' => $EPayDate,
            'EPRealNumber' => $EPRealNumber, //beda
            'EPayDate' => $EPayDate,
            'EPayNumber' => $EPayNumber,
            'BankReceipt' => $BankReceipt, //beda
            'EPRealAmount' => $EPRealAmount, //beda
            'EPRealExpense' => $EPRealExpense, //beda
            'CurrencyCode' => $CurrencyCode, //beda
            'EPRealTransType' => $EPRealTransType, //beda
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expensecashbon_payment->insert_detail_cpvr($detail_data);
        $this->trans_data['insert_detail_cpvr']['data'] = $detail_data;

        if ($update == false) {
            $return['EPRealNumber'] = $EPRealNumber;
            $return['AccountNumber'] = ($cek_selisih > 0) || ($cek_selisih < 0) ? $AccountNumber : 0;
        } else {
            $return['EPRealNumber'] = $EPRealNumber;
            $return['AccountNumber'] = ($cek_selisih > 0) || ($cek_selisih < 0) ? $AccountNumber : 0;
            $return['total_exceed'] = ($cek_selisih > 0) || ($cek_selisih < 0) ? $PaymentAmount : 0;
        }

        return $return;
    }

    public function insert_journal($cek_selisih, $EPayDate, $EPayNumber, $EPayDesc, $EPRealNumber, $AccountNumber, $account_exp_payable, $total_convert, $total_exceed_convert, $total_exceed, $account_adv_cashbon, $total_cashbon, $txt_cashbon_amount, $account_exp_relize, $rate_casbon, $txt_rate) {

        /* ================================ selisih > 0 ========================================= */
        if ($cek_selisih > 0) {

            /* ================================ debet =========================================== */
            $data_journal_exp_crv_debit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_exp_payable,
                'EPRealSaldoDebet' => $total_convert,
                'AmountCurrency' => ($total_convert / $txt_rate),
                'EPRealSignStatus' => 0,
                'EPRealDesc' => $EPayDesc,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_crv_debit($data_journal_exp_crv_debit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_exp_crv_debit;


            $data_journal_bank_crv_debit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $AccountNumber,
                'EPRealSaldoDebet' => $total_exceed_convert,
                'AmountCurrency' => $total_exceed,
                'EPRealDesc' => $EPayDesc,
                'EPRealSignStatus' => 0,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_bank_crv_debit($data_journal_bank_crv_debit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_bank_crv_debit;


            /* =========================================== credit ================================================== */
            $data_journal_crv_credit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_adv_cashbon,
                'EPRealSaldoCredit' => $total_cashbon,
                'AmountCurrency' => $txt_cashbon_amount,
                'EPRealSignStatus' => 1,
                'EPRealDesc' => $EPayDesc,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_crv_credit($data_journal_crv_credit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_crv_credit;

            if ($rate_casbon > $txt_rate) {

                $total_amount_relize = ($total_exceed_convert + $total_convert);
                $relize_amount = $total_cashbon - $total_amount_relize;

                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPRealNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoDebet' => abs($relize_amount),
                    'AmountCurrency' => abs($relize_amount),
                    'EPRealSignStatus' => 0,
                    'EPRealDesc' => $EPayDesc,
                    'LastUser' => $this->session->userdata('username')
                );
            } else {

                $total_amount_relize = ($total_exceed_convert + $total_convert);
                $relize_amount = $total_amount_relize - $total_cashbon;


                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPRealNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoCredit' => abs($relize_amount),
                    'AmountCurrency' => abs($relize_amount),
                    'EPRealSignStatus' => 1,
                    'EPRealDesc' => $EPayDesc,
                    'LastUser' => $this->session->userdata('username')
                );
            }

            if ($relize_amount != 0) {

                //$this->m_expensecashbon_payment->insert_journal_expense_relize_credit($data_journal_relize_credit);
                $this->trans_data['insert_journal']['data'][] = $data_journal_relize_credit;
            }


            /* ================================ selisih < 0 ========================================= */
        } elseif ($cek_selisih < 0) {

            $data_journal_exp_cpv_debit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_exp_payable,
                'EPRealSaldoDebet' => $total_convert,
                'AmountCurrency' => ($total_convert / $txt_rate),
                'EPRealSignStatus' => 0,
                'EPRealDesc' => $EPayDesc,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_cpv_debit($data_journal_exp_cpv_debit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_exp_cpv_debit;

            $data_journal_bank_cpv_credit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $AccountNumber,
                'EPRealSaldoCredit' => $total_exceed_convert,
                'AmountCurrency' => $total_exceed,
                'EPRealSignStatus' => 1,
                'EPRealDesc' => $EPayDesc,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_bank_cpv_credit($data_journal_bank_cpv_credit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_bank_cpv_credit;

            $data_journal_cpv_credit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPRealNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_adv_cashbon,
                'EPRealSaldoCredit' => $total_cashbon,
                'EPRealSignStatus' => 1,
                'AmountCurrency' => $txt_cashbon_amount,
                'EPRealDesc' => $EPayDesc,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_cpv_credit($data_journal_cpv_credit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_cpv_credit;

            if ($rate_casbon > $txt_rate) {
                $total_amount_relize = ($total_cashbon + $total_exceed_convert);
                $relize_amount = $total_amount_relize - $total_convert;

                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPRealNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoDebet' => abs($relize_amount),
                    'AmountCurrency' => abs($relize_amount),
                    'EPRealSignStatus' => 0,
                    'EPRealDesc' => $EPayDesc,
                    'LastUser' => $this->session->userdata('username')
                );
            } else {
                $total_amount_relize = ($total_cashbon + $total_exceed_convert);
                $relize_amount = $total_convert - $total_amount_relize;

                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPRealNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoCredit' => abs($relize_amount),
                    'AmountCurrency' => abs($relize_amount),
                    'EPRealSignStatus' => 1,
                    'EPRealDesc' => $EPayDesc,
                    'LastUser' => $this->session->userdata('username')
                );
            }

            if ($relize_amount != 0) {

                //$this->m_expensecashbon_payment->insert_journal_expense_crv_credit($data_journal_relize_credit);
                $this->trans_data['insert_journal']['data'][] = $data_journal_relize_credit;
            }


            /* ================================ selisih == 0 ========================================= */
        } else {

            $data_journal_exp_debit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPayNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_exp_payable,
                'EPRealSaldoDebet' => $total_convert,
                'AmountCurrency' => ($total_convert / $txt_rate),
                'EPRealSignStatus' => 0,
                'EPRealDesc' => $this->input->post('txa_memo'),
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_payment_debit($data_journal_exp_debit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_exp_debit;

            $data_journal_exp_credit = array(
                'EPRealDate' => $EPayDate,
                'EPRealNumber' => $EPayNumber,
                'EPRealNumber_BOut' => $EPayNumber,
                'EPRealAccountNumber' => $account_adv_cashbon,
                'EPRealSaldoCredit' => $total_cashbon,
                'EPRealSignStatus' => 1,
                'AmountCurrency' => $txt_cashbon_amount,
                'EPRealDesc' => $this->input->post('txa_memo'),
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->insert_journal_expense_payment_credit($data_journal_exp_credit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_exp_credit;

            if ($rate_casbon > $txt_rate) {

                $relize_kosong = $total_cashbon - $total_convert;

                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPayNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoDebet' => abs($relize_kosong),
                    'AmountCurrency' => abs($relize_kosong),
                    'EPRealSignStatus' => 0,
                    'EPRealDesc' => $this->input->post('txa_memo'),
                    'LastUser' => $this->session->userdata('username')
                );
            } else {

                $relize_kosong = $total_convert - $total_cashbon;

                $data_journal_relize_credit = array(
                    'EPRealDate' => $EPayDate,
                    'EPRealNumber' => $EPayNumber,
                    'EPRealNumber_BOut' => $EPayNumber,
                    'EPRealAccountNumber' => $account_exp_relize,
                    'EPRealSaldoCredit' => abs($relize_kosong),
                    'AmountCurrency' => abs($relize_kosong),
                    'EPRealSignStatus' => 1,
                    'EPRealDesc' => $this->input->post('txa_memo'),
                    'LastUser' => $this->session->userdata('username')
                );
            }

            if ($relize_kosong != 0) {
                //$this->m_expensecashbon_payment->insert_journal_expense_crv_credit($data_journal_relize_credit);
                $this->trans_data['insert_journal']['data'][] = $data_journal_relize_credit;
            }
        }
    }

    public function insert() {
        //set post data
        $BranchCode = $this->session->userdata('branch');
        $currency_cashbon = $this->input->post('curren_code_casbon');

        /* ======================================== category expense group ========================================= */
        $expCategoryID = $this->input->post('ExpGroupId');

        /* ======================================== get payable account/ selisih kurs ============================================ */
        $account_exp_payable = $this->m_expensecashbon_payment->get_account_exp_payable($expCategoryID);

        /* ======================================== get expense account/advance expense  =================================== */
        $account_adv_cashbon = $this->m_expensecashbon_payment->get_account_advance_cashbon($expCategoryID);

        /* ======================================== get realize account / selisih kurs transaksi ==================================== */
        $account_exp_relize = $this->m_account_journal->get_sys_cashbon_account('Realized',$expCategoryID,$currency_cashbon);

        if (!empty($account_exp_payable) || !empty($account_adv_cashbon) || !empty($account_exp_relize->AccountNumber)) {

            $DepartmentCode = $this->input->post('cmb_departement');
            $EmployeeCode = $this->input->post('cmb_employee');

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

            /* ======================================== create payment number ============================================ */
            $EPayNumber = $this->m_expensecashbon_payment->create_epay_number($EPayDate);

            /* ======================================== set cashbon number =============================================== */
            $EBonNumber = $this->input->post('txt_ebon_number');

            $EPayDesc = $this->input->post('txa_memo');

            $total_payment = $this->input->post('total_payment');

            $txt_cashbon_amount = $this->input->post('txt_cashbon_amount');
            $txt_rate = $this->input->post('txt_rate');
            $total_exceed = $this->input->post('total_exceed');
            $curren_code_casbon = $this->input->post('curren_code_casbon');
            $curren_code = $this->input->post('curren_code');
            $rate_casbon = $this->input->post('rate_casbon');
            $ExpGroupId = $this->input->post('ExpGroupId');

            /* ============================ payment convert to rupiah ============================== */
            $total_convert = $total_payment * $txt_rate;

            /* =========================== cashbon convert to rupiah =============================== */
            $total_cashbon = $txt_cashbon_amount * $rate_casbon;

            /* =========================== total exceed convert to rupiah ========================== */
            $total_exceed_convert = $total_exceed * $txt_rate;

            $data_payment = $this->input->post('detail_payment');
            $detail_pay = json_decode($data_payment);

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

            $cek_selisih = $txt_cashbon_amount - $total_payment;

            /* ================================== insert group =========================================== */
            $this->insert_group($BranchCode, $DepartmentCode, $EmployeeCode, $EPayDate, $EPayNumber, $EBonNumber, $EPayDesc, $curren_code_casbon, $total_payment, $txt_rate);

            /* ================================== insert detail payment ================================== */
            $this->insert_detail($detail_pay, $EPayNumber, $ExpGroupId, $curren_code_casbon, $txt_rate);

            /* ================================== insert detail cpvr and get EPRealNumber and AccountNumber ===================================== */
            $EPRealNumber = $this->insert_detail_cpvr($cek_selisih, $detail_cpvr, $EPayDate, $EPayNumber, $curren_code, $curren_code_casbon, $total_payment, false);

            /* ================================================= insert journal ========================================================================== */
            $this->insert_journal($cek_selisih, $EPayDate, $EPayNumber, $EPayDesc, $EPRealNumber['EPRealNumber'], $EPRealNumber['AccountNumber'], $account_exp_payable, $total_convert, $total_exceed_convert, $total_exceed, $account_adv_cashbon, $total_cashbon, $txt_cashbon_amount,$account_exp_relize->AccountNumber, $rate_casbon, $txt_rate);

            /* ================================================= update EBonLockStatus to lock =================================== */
            $status_cashbon = array('EBonLockStatus' => 1);

            //$this->m_expensecashbon_payment->update_status_cashbon($EBonNumber, $status_cashbon);
            $this->trans_data['update_status_cashbon']['data'] = $status_cashbon;
            $this->trans_data['update_status_cashbon']['TransNumber'] = $EBonNumber;

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

            $this->trans_data = [];

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

            echo json_encode($result);
        } else {

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

    public function edit() {
        //untuk cek login dan menu apakah bisa diakses oleh user yang login
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($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 {
                    //untuk ambil data dari session dan hak akses
                    $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_expensecashbon_payment->get_detail($id);
                    $ebonNumber = $this->m_expensecashbon_payment->get_cashbon_number($id);
                    $data['amount_cashbon'] = $this->m_expensecashbon_payment->get_amount_cashbon($ebonNumber);
                    $data['ebon_date'] = $this->m_expensecashbon_payment->get_date_cashbon($ebonNumber);
                    $data['bank_paymanet'] = $this->m_expensecashbon_payment->get_bank_cashbon($ebonNumber);
                    $data['amount_expensepay'] = $this->m_expensecashbon_payment->get_amount_expense_payment($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('expense_cashbon/v_edit_purchase_expense_real', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax_detail_payment($id) {
        $no_epay = str_replace(".", "/", $id);
        $number = str_replace("_", "-", $no_epay);
        $list_detail = $this->m_expensecashbon_payment->get_detail_item($number);

        echo"$list_detail";
    }

    public function ajax_detail_actual($id) {
        $no_epay = str_replace(".", "/", $id);
        $number = str_replace("_", "-", $no_epay);
        $list_actual = $this->m_expensecashbon_payment->get_detail_actual($number);

        foreach ($list_actual as $row) {

            $acc_no = $row->AccountNumber;
            $acc_name = $this->m_expensecashbon_payment->get_acc_name($acc_no);

            if ($row->EPRealTransType == 1) {
                $total_exceed = floatval($row->EBonAmount) - floatval($row->EPayAmount);
            } else {
                $total_exceed = floatval($row->EPayAmount) - floatval($row->EBonAmount);
            }

            $CrCvDate = convert_to_dmy($row->CrCvDate);
            $hasil[] = array(
                'CrCvDate' => $CrCvDate,
                'AmountCRV' => $row->EPayAmount,
                'PaymentAmount' => $row->EBonAmount,
                'AmountDiff' => $row->AmountCRV,
                'BankName' => $acc_name,
                'BankCode' => $acc_no
            );
        }

        echo json_encode($hasil);
    }

    public function update_group($BranchCode, $DepartmentCode, $EmployeeCode, $EPayNumber, $EPayDate, $EBonNumber, $total_payment, $txt_rate, $EPayDesc) {

        $data_payment = array(
            'BranchCode' => $BranchCode,
            'DepartmentCode' => $DepartmentCode,
            'EmployeeCode' => $EmployeeCode,
            'EPayDate' => $EPayDate,
            'EBonNumber' => $EBonNumber,
            'EPayAmount' => $total_payment,
            'EPayRate' => $txt_rate,
            'EPayDesc' => $EPayDesc,
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expensecashbon_payment->update_payment_cashbon($data_payment, $EPayNumber);
        $this->trans_data['update_group']['data'] = $data_payment;
        $this->trans_data['update_group']['TransNumber'] = $EPayNumber;
    }

    public function update_detail($detail_pay, $txt_rate, $EPayNumber, $curren_code) {

        foreach ($detail_pay as $details) {
            $ExpDetailName = $details->ExpDetailName;
            $ExpDetailDesc = $details->ExpDetailDesc;
            $ItemAmount = $details->ItemAmount;
            $EPayDetailID = $details->EPayDetailID;
            $ExpDetailID = $details->ExpDetailID;

            if ($curren_code == "IDR") {
                $TotalAmount = $ItemAmount * 1;
            } else {
                $TotalAmount = $ItemAmount * $txt_rate;
            }

            $detail_payment = array(
                'EPayNumber' => $EPayNumber,
                'ExpCategoryID' => $ExpDetailID,
                'ExpCategoryName' => $ExpDetailName,
                'ExpenseDesc' => $ExpDetailDesc,
                'ExpenseAmount' => $ItemAmount,
                'ExpenseTotalAmount' => $TotalAmount,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expensecashbon_payment->update_detail_payment_cashbon($detail_payment, $EPayDetailID);
            $this->trans_data['update_detail']['data'][] = $detail_payment;
            $this->trans_data['update_detail']['EPayDetailID'][] = $EPayDetailID;

            @$CategoryAmount[$details->ExpDetailID] += $ItemAmount;
        }
    }

    public function update() {

        $BranchCode = $this->session->userdata('branch');
        $DepartmentCode = $this->input->post('cmb_departement');
        $EmployeeCode = $this->input->post('cmb_employee');
        $EPayDate = date("Y-m-d", strtotime($this->input->post('txt_payment_date')));
        $EPayNumber = $this->input->post('txt_payment_no');
        $EBonNumber = $this->input->post('txt_ebon_number');
        $EPayDesc = $this->input->post('txa_memo');
        $total_payment = $this->input->post('total_payment');
        $txt_cashbon_amount = $this->input->post('txt_cashbon_amount');
        $rate_casbon = $this->input->post('rate_casbon');
        $txt_rate = $this->input->post('txt_rate');
        $curren_code = $this->input->post('curren_code');
        $txt_total_convert = $this->input->post('txt_total_convert');

        $get_casbon = $this->m_expensecashbon_payment->get_rate_cashbon($EBonNumber);
        $total_casbon_amount = $txt_cashbon_amount * $get_casbon;
        $total_paymen_amount = $total_payment * $txt_rate;

        $total_convert = $total_payment * $txt_rate;
        $total_exceed_convert = $this->input->post('total_exceed_convert');

        /* =========================== cashbon convert to rupiah =============================== */
        $total_cashbon = $txt_cashbon_amount * $rate_casbon;

        /* ============================= detail payment ======================================== */
        $data_payment = $this->input->post('detail_payment');
        $detail_pay = json_decode($data_payment);

        /* ============================= detail cpvr =========================================== */
        $data_detail = $this->input->post('detail_crcv');
        $detail_cpvr = json_decode($data_detail);

        /* ============================= amountdiff cashbon n payment ========================== */
        $cek_selisih = $txt_cashbon_amount - $total_payment;

        $expCategoryID = $this->input->post('ExpGroupId');

        $account_exp_payable = $this->m_expensecashbon_payment->get_account_exp_payable($expCategoryID);
        $account_adv_cashbon = $this->m_expensecashbon_payment->get_account_advance_cashbon($expCategoryID);

        $account_exp_relize = $this->m_account_journal->get_sys_cashbon_account('Realized',$expCategoryID,$curren_code);

        if (!empty($account_exp_payable) || !empty($account_adv_cashbon) || !empty($account_exp_relize->AccountNumber)) {

            /* ====================================== update group ================================================ */
            $this->update_group($BranchCode, $DepartmentCode, $EmployeeCode, $EPayNumber, $EPayDate, $EBonNumber, $total_payment, $txt_rate, $EPayDesc);

            /* ========================================== update detail ============================================== */
            $this->update_detail($detail_pay, $txt_rate, $EPayNumber, $curren_code);

            /* ========================================== delete journal ============================================= */
            //$this->m_expensecashbon_payment->delete_journal_expense_crv($EPayNumber);
            $this->trans_data['delete_journal']['TransNumber'] = $EPayNumber;

            /* ========================================== delete cpvr ================================================ */
            //$this->m_expensecashbon_payment->delete_detail_cpv($EPayNumber);
            $this->trans_data['delete_detail_cpv']['TransNumber'] = $EPayNumber;

            /* ========================================== insert cpvr ================================================ */
            $EPRealNumber = $this->insert_detail_cpvr($cek_selisih, $detail_cpvr, $EPayDate, $EPayNumber, $curren_code, $curren_code, $total_payment, true);

            $total_exceed = $EPRealNumber['total_exceed'];
            $total_exceed_convert = $EPRealNumber['total_exceed'] * $txt_rate;

            /* ================================================= insert journal ========================================================================== */
            $this->insert_journal($cek_selisih, $EPayDate, $EPayNumber, $EPayDesc, $EPRealNumber['EPRealNumber'], $EPRealNumber['AccountNumber'], $account_exp_payable, $total_convert, $total_exceed_convert, $total_exceed, $account_adv_cashbon, $total_cashbon, $txt_cashbon_amount, $account_exp_relize->AccountNumber, $rate_casbon, $txt_rate);


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

            $this->trans_data = [];

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

    function approved_mgr() {
        $txt_cashbon_no = $this->input->post('txt_exp_paymentno_other');
        $txt_payment_no = $this->input->post('txt_payment_no');

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

        /* ================================= data update to lock cashbon =========================== */
        $data_cashbon = array('TransStatus' => 2, 'EBonLockStatus' => 1);

        /* =========================================== chcek status transaction cashbon ================================ */
        $cek_status_piutang = $this->m_expensecashbon_payment->m_cek_status_cashbon($txt_cashbon_no);

        if ($cek_status_piutang == false) {

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

            die;
        } else {

            /* ============================= Transac begin =================================== */
            $this->db->trans_begin();

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

            /* ============================= fungsi update islock =================================== */
            //$this->m_expensecashbon_payment->update_is_lock($data_cashbon, $txt_cashbon_no);
            $this->trans_data['update_is_lock']['data'] = $data_cashbon;
            $this->trans_data['update_is_lock']['TransNumber'] = $txt_cashbon_no;

            $result_return = $this->m_expensecashbon_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' => 4,
            'AppFinished' => 0,
        );

        $data_reversed_cashbon = array(
            'TransStatus' => 1,
            'EBonLockStatus' => 1
        );

        /* ============================= get ABONNumber / no cashbon ============ */
        $no_cashbon = $this->m_expensecashbon_payment->get_cashbon_number($txt_payment_no);

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

        if ($check_period == false) {

            /* ============================= reverse payment =================================== */
            //$this->m_expensecashbon_payment->update_to_reverse_payment($txt_payment_no,$data_reversed_payment);
            $this->trans_data['reverse_data']['data'] = $data_reversed_payment;
            $this->trans_data['reverse_data']['TransNumber'] = $txt_payment_no;

            /* =============================update edebt/ reverse =================================== */
            //$this->m_expensecashbon_payment->update_to_reverse_cashbon($no_cashbon,$data_reversed_cashbon);
            $this->trans_data['update_to_reverse_cashbon']['data'] = $data_reversed_cashbon;
            $this->trans_data['update_to_reverse_cashbon']['TransNumber'] = $no_cashbon;

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

            $result_return = $this->m_expensecashbon_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);

            /* ============================= End Transac =================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('reverse_in_period', 0);
            echo json_encode($result);
        }
    }

    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_expensecashbon_payment->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_expensecashbon_payment->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('expense_cashbon/v_print_expense_payment_real', $data);
        $this->load->view('v_footer');
    }
    
    public function to_preview($obj_string = null){
        
        //$data['list'] 		= $this->m_expensecashbon_payment->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);
        
        $str_branch             = "";
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data_filter['cmb_branch']==""||$data_filter['cmb_branch']==null?$str_branch = $this->session->userdata('branch'):$str_branch = $data_filter['cmb_branch'];
        $data['company'] = $this->m_expensecashbon_payment->get_company_by_branch($str_branch);
        $data['list']           = $this->m_expensecashbon_payment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('expense_cashbon/v_print_expense_payment_real', $data);
        $this->load->view('v_footer');
    }
    
    public function to_journal($EPayNumber) {
        $CompanyCode = $this->session->userdata('company');
        $str_replace_no = str_replace(".", "/", $EPayNumber);
        $payment_number = str_replace("_", "-", $str_replace_no);
        $EPRealNumber = $this->m_expensecashbon_payment->get_actual_number($payment_number);
        $BranchCode = $this->m_expensecashbon_payment->get_branch_code($payment_number);
        if (!empty($EPRealNumber)) {
            $EPRealNumber = $EPRealNumber;
        } else {
            $EPRealNumber = $payment_number;
        }

        $data['cek_status_trans'] = $this->m_expensecashbon_payment->get_status_journal($payment_number);
        $data['list_jurnal_payment'] = $this->m_expensecashbon_payment->get_journal_payment($payment_number, $BranchCode);

        $data['date_journal'] = $this->m_expensecashbon_payment->get_date_journal_payment($payment_number);
        $data['detail_payment'] = $this->m_expensecashbon_payment->get_detail_payment_description($payment_number);
        $data['detail_list'] = $this->m_expensecashbon_payment->get_detail_pembiayaan($payment_number);

        $this->load->view('v_header');
        $this->load->view('expense_cashbon/v_print_journal_payment_cashbon', $data);
        $this->load->view('v_footer');
    }

    public function suspend_data() {

        $EPayNumber = $this->input->post('id');

        $get_at_payment = $this->m_expensecashbon_payment->get_at_expensepayment($EPayNumber);

        $EBonNumber = $get_at_payment->EBonNumber;

        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );

        $status_cashbon = array('TransStatus' => 1, 'EBonLockStatus' => 0);

        //$this->m_expensecashbon_payment->update_trans_status($id, $data);
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $EPayNumber;

        //$this->m_expensecashbon_payment->update_status_cashbon($EBonNumber, $status_cashbon);
        $this->trans_data['update_status_cashbon']['data'] = $status_cashbon;
        $this->trans_data['update_status_cashbon']['TransNumber'] = $EBonNumber;

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    public function approval1() {
        if ($this->session->userdata("jobtitle_status") == 0) {
            $payment_number = $this->input->post('txt_payment_no');

            $cek_app_status_mgr = $this->m_expensecashbon_payment->cek_status_app_mgr($payment_number);
            if (!empty($cek_app_status_mgr)) {
                $TransStatus = 2;
                $app_finis = 1;
            } else {
                $TransStatus = 4;
                $app_finis = 0;
            }

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

            // transaction begin
            $this->db->trans_begin();
            $this->m_expensecashbon_payment->approval_status($data, $payment_number);

            $app_finished = array('AppFinished' => $app_finis);
            $cek_app = $this->m_expensecashbon_payment->cek_app($payment_number);

            if (!empty($cek_app)) {
                $this->m_expensecashbon_payment->status_finished($app_finished, $payment_number);
            }

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = false;
                $result['message'] = 'Approval Gaggal';
            } else {
                $this->db->trans_commit();
                $result['status'] = true;
                $result['message'] = 'Approval Berhasil';
            }

            echo json_encode($result);
        }
    }

    public function approval2() {
        if ($this->session->userdata("jobtitle_status") == 1) {
            $payment_number = $this->input->post('txt_payment_no');
            $EBonNumber = $this->input->post('txt_ebon_number');
            $app_finis = 1;
            /* $cek_app_status_dir = $this->m_expensecashbon_payment->cek_status_app_dir($payment_number);
              if(!empty($cek_app_status_dir)){
              $TransStatus = 2;
              $app_finis = 1;
              } else {
              $TransStatus = 5;
              $app_finis = 0;
              } */

            $data = array(
                'AppLevel1Status' => 1,
                'TransStatus' => 2,
                'AppLevel1Code' => $this->session->userdata("username"),
                'AppLevel1Date' => date("Y-m-d"),
                'LastUser' => $this->session->userdata("username")
            );

            // transaction begin
            $this->db->trans_begin();
            $this->m_expensecashbon_payment->approval_status($data, $payment_number);

            $status_cashbon = array('TransStatus' => 2, 'EBonLockStatus' => 0);
            $this->m_expensecashbon_payment->update_status_cashbon($EBonNumber, $status_cashbon);

            $app_finished = array('AppFinished' => $app_finis);
            $cek_app = $this->m_expensecashbon_payment->cek_app($payment_number);

            //if(!empty($cek_app)){
            $this->m_expensecashbon_payment->status_finished($app_finished, $payment_number);
            //}

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = false;
                $result['message'] = 'Approval Gaggal';
            } else {
                $this->db->trans_commit();
                $result['status'] = true;
                $result['message'] = 'Approval Berhasil';
            }

            echo json_encode($result);
        }
    }

    public function get_epay_number() {
        $epay_date = $this->input->post('EPay_Date') == '' ? date('d-m-Y') : $this->input->post('EPay_Date');
        /* $bankout_code	= $this->input->post('BankOut_Code'); */

        if (!empty($epay_date)) {
            $result['status'] = true;
            $result['number'] = $this->m_expensecashbon_payment->create_epay_number($epay_date/* , $bankout_code */);
        } else {
            $result['status'] = false;
            $result['number'] = '';
        }

        echo json_encode($result);
    }

    public function get_akun($cpv, $bank_payment) {
        $replace_akun = str_replace('_', '-', $bank_payment);
        $branch = $this->session->userdata('branch');

        $get_akun_gl = $this->m_expensecashbon_payment->get_am_akun_gl($replace_akun, $branch);

        $CompanyCode = $this->session->userdata('company');
        $cpv_payment = "CPV";
        $crv_payment = "CRV";

        if ($cpv == "CPV") {
            $result = $this->m_expensecashbon_payment->get_akun($CompanyCode, $get_akun_gl->AccountSubTypeID, $get_akun_gl->CurrencyCode, $cpv_payment);
        } else {
            $result = $this->m_expensecashbon_payment->get_akun($CompanyCode, $replace_akun, $get_akun_gl->CurrencyCode, $crv_payment);
        }
        foreach ($result as $row) {
            $hasil[] = array(
                'ExpBankNumber' => $row->AccountNumber,
                'ExpBankName' => $row->AccountName,
                'ExpCurrency' => $row->CurrencyCode,
                'BranchCode' => $row->BranchCode
            );
        }

        echo json_encode($hasil);
    }

    public function ajax_item() {
        $ExpDetailID = $this->input->post('ExpDetailID');

        if (!empty($ExpDetailID)) {
            echo json_encode($this->m_expensecashbon_payment->get_detail_item_for_payment($ExpDetailID));
        } else {
            echo '[]';
        }
    }

    public function get_employee($DepCode) {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $depCode = str_replace($data['menu_link'] . '/get_employee/', "", $this->uri->uri_string());
        $employee = $this->m_expensecashbon_payment->get_employee($depCode);
        echo"$employee";
    }

    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_expensecashbon_payment->get_detail_to_print($payment_no);
            //echo $this->db->last_query();
            $data['list'] = $this->m_expensecashbon_payment->get_to_print_detail($payment_no);

            $this->load->view('v_header');
            $this->load->view('expense_cashbon/v_print_detail_expense_payment_real', $data);
            $this->load->view('v_footer');
        }
    }

}
