<?php

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

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

class Payment_karyawan_journal extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 365;
    public $menu_model = '';
    public $name = 'Payment Karyawan 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_payment_karyawan_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/payment_karyawan_journal/v_paymentkaryawan_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_employee', 'at_employeeinstallment_journal.EmplTransCode=am_employee.EmployeeCode', 'INNER');
        $this->db->join('am_company', 'at_employeeinstallment_journal.CompRecpCode=am_company.CompanyCode', 'INNER');
        $this->db->join('am_branch', 'at_employeeinstallment_journal.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee as created_by', 'at_employeeinstallment_journal.CreatedBy=created_by.EmployeeCode', 'LEFT');

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

        if ($Number != "") {
            $this->db->like('at_employeeinstallment_journal.EInjNumber', $Number);
        }

        if ($Desc != "") {
            $this->db->like('at_employeeinstallment_journal.EInjDesc', $Desc);
        }

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


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

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

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

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

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

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

        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]->EInjNumber,
                'EInjDate' => $result[$i]->EInjDate,
                'CompRecpCode' => $result[$i]->CompanyName,
                'EmployeeName' => $result[$i]->EmployeeName,
                'EInjAmount' => $result[$i]->EInjAmount,
                'EInjDesc' => $result[$i]->EInjDesc,
                'TransStatus' => $TransStatus,
                'CompanyName' => $result[$i]->CompanyName,
                '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_payment_karyawan_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_payment_karyawan_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['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_payment_karyawan_journal->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('cash_and_bank/payment_karyawan_journal/v_preview_payment_karyawan_journal', $data);
        $this->load->view('v_footer');
    }

    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_payment_karyawan_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_payment_karyawan_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/payment_karyawan_journal/v_preview_payment_karyawan_journal', $data);
        $this->load->view('v_footer');
    }

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

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

    // Function Index	
    public function add() {
        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');

                    $data['payment_karyawan_no'] = $this->m_payment_karyawan_journal->create_payment_karyawan_journal_number(date('d-m-Y'));
                    $data['date_now'] = date('d-m-Y');

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

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

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

        $pay_karyawan_number = $this->m_payment_karyawan_journal->create_payment_karyawan_journal_number($preg_date);

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

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

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

    public function get_piutang() {
        $BranchCode = $this->session->userdata('branch');
        $list_piutang = $this->m_payment_karyawan_journal->get_piutang($BranchCode);

        foreach ($list_piutang as $row) {
            $EDebtNumber = $row->EDebtNumber;
            $total_piutang = $row->EDebtAmount;
            $outstanding = $this->m_payment_karyawan_journal->get_sisa_piutang($EDebtNumber);
            $JVB = $row->JVoucherBalance;


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

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


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

            $hasil[] = array(
                'EDebtAmount' => $row->EDebtAmount,
                'BranchName' => $row->BranchName,
                'BranchCode' => $row->BranchCode,
                //'CompTransCode' => $row->CompTransCode,
                'AccountName' => $row->AccountName,
                'EDebtNumber' => $row->EDebtNumber,
                'EmployeeName' => $row->EmployeeName,
                'EmplRecpCode' => $row->EmplRecpCode,
                'EdebtIsLock' => $IsLock,
                'EDebtDesc' => $row->EDebtDesc,
                'outstanding' => $BalanceAmount
            );
        }

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

    /* public function no_payment(){
      $piutang_no = $this->input->post('piutang_no');
      $no_payment_before = $this->m_payment_karyawan_journal->get_no_payment_before($piutang_no);
      echo"$no_payment_before";
      } */

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

    public function get_company() {
        $branch = $this->session->userdata('branch');
        $list_company = $this->m_payment_karyawan_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);
        $id = $uri4 . "/" . $uri5 . "/" . $uri6;
        $uri7 = $this->uri->segment(7);

        $list_payment = $this->m_payment_karyawan_journal->get_payment_periode($id, $uri7);
        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_payment_karyawan_journal->get_payment_periode_cancel($payment_before);

        echo"$list_payment";
    }

    public function get_history_payment($EInjNumber) {

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

        $result = $this->m_payment_karyawan_journal->get_history_payment($EInjNumber);
        echo json_encode($result);
    }

    public function insert_group($BranchCode, $txt_date, $EInjNumber, $EDebtNumber, $txt_karyawan, $coa_piutang_karyawan, $company, $txa_memo, $total_payment) {

        $data_payment = array(
            'BranchCode' => $BranchCode,
            'EInjDate' => $txt_date,
            'EInjNumber' => $EInjNumber,
            'EDebtNumber' => $EDebtNumber,
            'EmplTransCode' => $txt_karyawan,
            'BankTransfer' => $coa_piutang_karyawan,
            'CompRecpCode' => $company,
            'CqTermStatus' => 1,
            'EInjDesc' => $txa_memo,
            'TransStatus' => 4,
            'EInjAmount' => $total_payment,
            '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($EInjNumber, $detail) {

        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(
                'EInjNumber' => $EInjNumber,
                'EInjAccountNumber' => $acc_number->AccountNumber,
                'EInjAmount' => $row->PaymentAmount,
                'EInjMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

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

    public function insert_journal($detail, $txt_date, $EInjNumber, $coa_piutang_karyawan, $total_payment, $txa_memo) {

        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(
                'EInjDate' => $txt_date,
                'EInjNumber' => $EInjNumber,
                'EInjAccountNumber' => $acc_number->AccountNumber,
                'EInjSaldoDebet' => $row->PaymentAmount,
                'EInjSaldoCredit' => 0,
                'AmountCurrency' => $row->PaymentAmount,
                'EInjDesc' => $txa_memo,
                'EInjSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                'LastUser' => $this->session->userdata('username')
            );

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

        $journal_credit = array(
            'EInjDate' => $txt_date,
            'EInjNumber' => $EInjNumber,
            'EInjAccountNumber' => $coa_piutang_karyawan,
            'EInjSaldoDebet' => 0,
            'EInjSaldoCredit' => $total_payment,
            'AmountCurrency' => $total_payment,
            'EInjDesc' => $txa_memo,
            'EInjSignStatus' => 1,
            'LastUser' => $this->session->userdata('username')
        );

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

    public function insert() {

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

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

        /* =============================== create number payment karyawan ====================== */
        $EInjNumber = $this->m_payment_karyawan_journal->create_payment_karyawan_journal_number($txt_date);

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

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

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

        /* ================================= get totatl payment ================================ */
        //$total_payment_period = $this->m_payment_karyawan_journal->get_total_payment_period($EDebtNumber);

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

        //$ExpCategoryID = $this->m_payment_karyawan_journal->get_expt_payment();
        //$PaymentAccount = '1-3-04-004-00';

        /* ================================== Checking Coa piutang Karyawan =================================== */
        $coa_piutang_karyawan = $this->m_payment_karyawan_journal->get_coa_piutang_karyawan($company, $BranchCode);

        if ($coa_piutang_karyawan == "") {

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

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

            /* =================================== set data group ============================== */
            $this->insert_group($BranchCode, $txt_date, $EInjNumber, $EDebtNumber, $txt_karyawan, $coa_piutang_karyawan, $company, $txa_memo, $total_payment);

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

            /* =================================== insert journal ============================ */
            $this->insert_journal($detail, $txt_date, $EInjNumber, $coa_piutang_karyawan, $total_payment, $txa_memo);

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

            $this->trans_data = [];

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

            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_payment_karyawan_journal->get_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/payment_karyawan_journal/v_edit_paymentkaryawan_journal', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update_group($txt_payment_no, $total_payment, $txa_memo) {

        $data_group = array(
            'EInjDesc' => $txa_memo,
            'EInjAmount' => $total_payment
        );

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

    public function update_detail($detail, $txt_payment_no) {
        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(
                'EInjNumber' => $txt_payment_no,
                'EInjAccountNumber' => $acc_number->AccountNumber,
                'EInjAmount' => $row->PaymentAmount,
                'EInjMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

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

    public function update() {

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

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

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

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

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

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

        /* ================================== Checking Coa piutang Karyawan =================================== */
        $coa_piutang_karyawan = $this->m_payment_karyawan_journal->get_coa_piutang_karyawan($company, $BranchCode);

        if ($coa_piutang_karyawan == "") {

            $result['status'] = false;
            $result['message'] = get_notification('coa', 0);

            echo json_encode($result);
        } else {

            /* =================================== update group ================================= */
            $this->update_group($EInjNumber, $total_payment, $txa_memo);

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

            $this->trans_data['delete_detail']['total'] = count($detail_id);

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

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

            /* =================================== insert journal ================================ */
            $this->insert_journal($detail, $txt_date, $EInjNumber, $coa_piutang_karyawan, $total_payment, $txa_memo);


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

            $this->trans_data = [];

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

            echo json_encode($result);
        }
    }

    function approved_mgr() {
        $txt_payment_no = $this->input->post('payment_karyawan_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 islock =========================================== */
        $data_islock = array('EdebtIsLock' => 0);

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

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

        $no_piutang_karyawan = $data_payment['EDebtNumber'];

        $cek_status_piutang = $this->m_payment_karyawan_journal->m_cek_status_piutang($no_piutang_karyawan);


        if ($cek_status_piutang == false) {

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

            /* =============================Set Data Update payment =================================== */
            $this->m_payment_karyawan_journal->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;

            /* ============================= Set Data update islock =================================== */
            $this->trans_data['islock_status']['data'] = $data_islock;
            $this->trans_data['islock_status']['TransNumber'] = $no_piutang_karyawan;

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


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

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

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

        $no_piutang_karyawan = $data_payment['EDebtNumber'];

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

        if ($check_period == false) {

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

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

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

            $result_return = $this->m_payment_karyawan_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_payment_karyawan_journal->get_date_journal_payment($payment_number);
        $data['list_jurnal'] = $this->m_payment_karyawan_journal->get_all_journal_payment($payment_number, $branch_explode);

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/payment_karyawan_journal/v_print_journal_payment_karyawan_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_payment_karyawan_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(
            'EdebtIsLock' => 0
        );

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

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

        $result_return = $this->m_payment_karyawan_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 approval1() {
        if ($this->session->userdata("jobtitle_status") == 1) {
            $pay_number = $this->input->post('txt_payment_no');
            $EDebtNumber = $this->input->post('txt_payment_for');
            $pay_balance = $this->input->post('pay_balance');

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

            if ($pay_balance == 0) {
                $status_piutang = array('TransStatus' => 2);
                $result_insert = $this->m_payment_karyawan_journal->update_status_piutang($EDebtNumber, $status_piutang);
                if ($result_insert == 0) {
                    $this->proses_tutup();
                }
            }

            $data_islock_status = array(
                'EdebtIsLock' => 0
            );
            // transaction begin
            $this->db->trans_begin();

            $result_insert = $this->m_payment_karyawan_journal->update_is_lock($data_islock_status, $EDebtNumber);
            if ($result_insert == 0) {
                $this->proses_tutup();
            }

            $result_insert = $this->m_payment_karyawan_journal->approval_status($data, $pay_number);
            if ($result_insert == 0) {
                $this->proses_tutup();
            }

            if ($result_insert == 0) {
                $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 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_payment_karyawan_journal->get_detail_item_print($payment_no);
            $data['list'] = $this->m_payment_karyawan_journal->get_detail_item_print_journal($payment_no, $BranchCode);


            // echo $this->db->last_query();

            $this->load->view('v_header');
            $this->load->view('cash_and_bank/payment_karyawan_journal/v_print_detail_payment_karyawan_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_other_expense() {
        $branch = $this->session->userdata('branch');
        $result = $this->m_payment_karyawan_journal->m_get_other_expense($branch);
        echo json_encode($result);
    }

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

}
