<?php

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

/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 07-10-2014	
 * 	Revisi 	: 
 */

class Purchases_expense_cashbon extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 244;
    // 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 Cashbon";
    public $trans_data = array();

    public function __construct() {
        parent::__construct();
        $this->load->model('m_menu');
        $this->load->model('m_expense_cashbon');
        $this->load->model('m_account_journal');
        $this->load->helper('status');
        $this->load->helper('message');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
        $this->load->model('custom/m_custom');
        $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_cashbon', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

                    $department = $this->m_custom->get_department_by_name('EXIM');
                    $data['department_code'] = $department[0]->DepartmentCode;

                    $data['cachbon_number'] = $this->m_expense_cashbon->create_ebon_number(date('d-m-Y'));
                    $data['pr_date'] = 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_cashbon', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax_list_cashbon() {
        $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('EBonNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('EBonDesc', $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_expensecashbon.EBonDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_expensecashbon.EBonDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

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

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_expense_cashbon->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]->EBonNumber,
                'EBonDate' => $result[$i]->EBonDate,
                'EBonAmount' => $result[$i]->EBonAmount,
                'EBonDesc' => $result[$i]->EBonDesc,
                'TransStatus' => $TransStatus,
                'DepartmentName' => $result[$i]->DepartmentName,
                'EBonMemo' => $result[$i]->EBonDesc,
                '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_LAMA($data_grid = null) {
        $data['company'] = $this->m_expense_cashbon->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_expense_cashbon->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_cashbon', $data);
        $this->load->view('v_footer');
    }
    
    public function to_preview($obj_string = null) {
        $data['company'] = $this->m_expense_cashbon->get_company_by_branch($this->session->userdata('branch'));
        
        //$data['list'] 		= $this->m_expense_cashbon->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_expense_cashbon->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('expense_cashbon/v_print_expense_cashbon', $data);
        $this->load->view('v_footer');
    }
    
    public function get_department() {
        $CompanyCode = $this->session->userdata('company');
        $list_department = $this->m_expense_cashbon->get_department($CompanyCode);

        echo $list_department;
    }

    public function get_department_edit($departmen_code) {
        $replace_code = str_replace("_", "-", $departmen_code);
        $explode_dep_code = explode("-", $replace_code);
        $var_Company_code = $explode_dep_code[0];

        $list_department = $this->m_expense_cashbon->get_department_edit($var_Company_code, $replace_code);
        //echo $this->db->last_query();

        echo"$list_department";
    }

    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_expense_cashbon->get_employee($depCode);
        echo"$employee";
    }

    public function get_employee_edit($DepCode, $branchCode) {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $depCode = str_replace('_', '-', $DepCode);
        $branch_replace = str_replace('_', '-', $branchCode);
        $employee = $this->m_expense_cashbon->get_employee_edit($depCode, $branch_replace);
        echo"$employee";
    }

    public function get_akun() {
        $CompanyCode = $this->session->userdata('company');
        $list_akun = $this->m_expense_cashbon->get_akun($CompanyCode);
        echo"$list_akun";
    }

    public function akun_cashbon() {
        $CompanyCode = $this->session->userdata('company');
        $list_akun_cashbon = $this->m_expense_cashbon->get_akun_cashbon($CompanyCode);
        //echo $this->db->last_query();
        echo"$list_akun_cashbon";
    }

    /* Added by Hasan on 2015/03/23 */

    public function cashbon_account($CurrencyCode = null) {
        $Arr_post = $this->input->post();
        $AccountNo = isset($Arr_post['AccountNo']) ? $Arr_post['AccountNo'] : '';
        $AccountName = isset($Arr_post['AccountName']) ? $Arr_post['AccountName'] : '';
        $company = $this->session->userdata('company');

        $list_akun_cashbon = $this->m_expense_cashbon->get_akun_cashbon($company, $AccountNo, $AccountName, $CurrencyCode);
        //echo $this->db->last_query();
        echo $list_akun_cashbon;
    }

    /* End of Added */

    public function get_rate_currency() {
        $AccountNumber = $this->input->post('AccountNumber');
        $currency_rate = $this->m_expense_cashbon->get_currency_code($AccountNumber);
        echo"$currency_rate";
    }

    public function insert_group($BranchCode, $DepartmentCode, $EmployeeCode, $EBonDate, $EBonNumber, $EBonDesc, $txt_amount, $BankPayment, $CurrencyCode, $CurrencyRate, $ChequeNumber, $ChequeDate, $ChequeAmount) {
        $data_cashbon = array(
            'BranchCode' => $BranchCode,
            'DepartmentCode' => $DepartmentCode,
            'EmployeeCode' => $EmployeeCode,
            'EBonDate' => $EBonDate,
            'EBonNumber' => $EBonNumber,
            'EBonDesc' => $EBonDesc,
            'EBonAmount' => $txt_amount,
            'BankPayment' => $BankPayment,
            'CurrencyCode' => $CurrencyCode,
            'CurrencyRate' => $CurrencyRate,
            'ChequeNumber' => $ChequeNumber,
            'ChequeDate' => $ChequeDate,
            'ChequeAmount' => $ChequeAmount,
            'EBonLockStatus' => 1,
            'TransStatus' => 4,
            'CreatedBy' => $this->session->userdata('username'),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expense_cashbon->insert_expense_cashbon($data_cashbon);
        $this->trans_data['insert_group']['data'] = $data_cashbon;
    }

    public function insert_detail($detail, $kategoriid, $EBonNumber, $akun_number, $txt_amount) {
        foreach ($detail as $row) {
            $ebon_amount = $row->Amount;
            $ebon_Memo = $row->Memo;
            $detail_cashbon = array(
                'EBonNumber' => $EBonNumber,
                'ExpCategoryID' => $kategoriid,
                'EBonAccountNumber' => $akun_number,
                'EBonAmount' => $ebon_amount,
                'EbonAmountConvert' => $txt_amount,
                'EBonMemo' => $ebon_Memo,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expense_cashbon->insert_detail_cashbon($detail_cashbon);
            $this->trans_data['insert_detail']['data'][] = $detail_cashbon;
        }
    }

    public function insert_journal($EBonDate, $EBonNumber, $akun_number, $BankPayment, $total_amount, $EBonDesc, $txt_amount) {
        $data_journal_debit = array(
            'EBonDate' => $EBonDate,
            'EBonNumber' => $EBonNumber,
            'EBonAccountNumber' => $akun_number,
            'EBonSaldoDebet' => $total_amount,
            'EBonDesc' => $EBonDesc,
            'EBonSignStatus' => 0,
            'AmountCurrency' => $txt_amount,
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expense_cashbon->insert_journal_expense_cashbon_debit($data_journal_debit);
        $this->trans_data['insert_journal']['data'][] = $data_journal_debit;

        $data_journal_credit = array(
            'EBonDate' => $EBonDate,
            'EBonNumber' => $EBonNumber,
            'EBonAccountNumber' => $BankPayment,
            'EBonSaldoCredit' => $total_amount,
            'EBonDesc' => $EBonDesc,
            'EBonSignStatus' => 1,
            'AmountCurrency' => $txt_amount,
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_expense_cashbon->insert_journal_expense_cashbon_credit($data_journal_credit);
        $this->trans_data['insert_journal']['data'][] = $data_journal_credit;
    }

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

        $DepartmentCode = $this->input->post('cmb_departement');
        $EmployeeCode = $this->input->post('cmb_employee');
        $EBonDate = date("Y-m-d", strtotime($this->input->post('txt_cashbon_date')));

        /* =============================== create ebon number ================================= */
        $EBonNumber = $this->m_expense_cashbon->create_ebon_number($EBonDate);

        $EBonDesc = $this->input->post('txa_description');
        $BankPayment = $this->input->post('cmb_bank');
        $CurrencyCode = $this->input->post('currency_code');
        ;
        $CurrencyRate = $this->input->post('txt_rate');
        $ChequeNumber = $this->input->post('txtcheque_no');
        $ChequeDate = date("Y-m-d", strtotime($this->input->post('txt_cheque_date')));
        $ChequeAmount = $this->input->post('txt_cheque_amount');
        $txt_amount = $this->input->post('txt_amount');
        $kategoriid = $this->input->post('kategoriid');
        $detail = json_decode($this->input->post('detail'));
        $total_amount = $txt_amount * $CurrencyRate;

        /* ========================================== cek preferences other kategori ======================= */
        $account_advance = $this->m_expense_cashbon->get_account_advance_cashbon($kategoriid);

        if ($account_advance == false) {
            $hasil = 0;
            $this->trans_rollback('journal');
        } else {

            /* ====================== set account no cash bon================================================ */
            $akun_number = $account_advance;

            /* =========================================== insert group ================================================================================================================================ */
            $this->insert_group($BranchCode, $DepartmentCode, $EmployeeCode, $EBonDate, $EBonNumber, $EBonDesc, $txt_amount, $BankPayment, $CurrencyCode, $CurrencyRate, $ChequeNumber, $ChequeDate, $ChequeAmount);

            /* ===================================================== insert detail ================================================== */
            $this->insert_detail($detail, $kategoriid, $EBonNumber, $akun_number, $txt_amount);

            /* ==================================================== insert journal ================================================== */
            $this->insert_journal($EBonDate, $EBonNumber, $akun_number, $BankPayment, $total_amount, $EBonDesc, $txt_amount);

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

            $this->trans_data = [];

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

            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 {
                    $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_expense_cashbon->get_detail($id);
                    //echo $this->db->last_query();
                    $data['amount_cashbon'] = $this->m_expense_cashbon->get_amount_cashbon($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_expense_cashbon', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax_detail_item($id) {
        $number = str_replace(".", "/", $id);
        $replace_no = str_replace("_", "-", $number);

        //$arr_no 			= explode('/',$replace_no);
        //$year_transaction 	= 2000 + (int)substr($arr_no[1],2,2);

        $list_detail = $this->m_expense_cashbon->get_detail_item($replace_no);
        //echo $this->db->last_query();
        echo"$list_detail";
    }

    public function update_group($EBonNumber, $BranchCode, $DepartmentCode, $EmployeeCode, $EBonDate, $EBonDesc, $txt_amount, $BankPayment, $CurrencyCode, $CurrencyRate, $ChequeNumber, $ChequeDate, $ChequeAmount) {

        $data_cashbon = array(
            'BranchCode' => $BranchCode,
            'DepartmentCode' => $DepartmentCode,
            'EmployeeCode' => $EmployeeCode,
            'EBonDate' => $EBonDate,
            'EBonDesc' => $EBonDesc,
            'EBonAmount' => $txt_amount,
            'BankPayment' => $BankPayment,
            'CurrencyCode' => $CurrencyCode,
            'CurrencyRate' => $CurrencyRate,
            'ChequeNumber' => $ChequeNumber,
            'ChequeDate' => $ChequeDate,
            'ChequeAmount' => $ChequeAmount
        );

        //$this->m_expense_cashbon->update_expense_cashbon($data_cashbon, $EBonNumber);
        $this->trans_data['update_group']['data'] = $data_cashbon;
        $this->trans_data['update_group']['TransNumber'] = $EBonNumber;
    }

    public function update_detail($detail, $kategoriid, $EBonNumber, $txt_amount, $nomor_akun) {
        foreach ($detail as $row) {
            $EBonMemo = $row->EBonMemo;
            $Amount = $row->EBonAmount;

            $detail_cashbon = array(
                'EBonAmount' => $Amount,
                'ExpCategoryID' => $kategoriid,
                'EBonMemo' => $EBonMemo,
                'EbonAmountConvert' => $txt_amount,
                'EBonAccountNumber' => $nomor_akun,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_expense_cashbon->update_detail_cashbon($detail_cashbon, $EBonNumber);
            $this->trans_data['update_detail']['data'][] = $detail_cashbon;
            $this->trans_data['update_detail']['TransNumber'][] = $EBonNumber;
        }
    }

    public function update() {
        //set post data
        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');
        $DepartmentCode = $this->input->post('cmb_departement');
        $EmployeeCode = $this->input->post('cmb_employee');
        $EBonDate = date("Y-m-d", strtotime($this->input->post('txt_cashbon_date')));
        $EBonNumber = $this->input->post('txt_exp_cashbon_no');
        $EBonDesc = $this->input->post('txa_description');
        $BankPayment = $this->input->post('cmb_bank');
        $bank_number = $this->input->post('bank_number');
        $CurrencyCode = $this->input->post('currency_code');
        $CurrencyRate = $this->input->post('txt_rate');
        $ChequeNumber = $this->input->post('txtcheque_no');
        $ChequeDate = date("Y-m-d", strtotime($this->input->post('txt_cheque_date')));
        $ChequeAmount = $this->input->post('txt_cheque_amount');
        $txt_amount = $this->input->post('txt_amount');
        $kategoriid = $this->input->post('kategoriid');
        $total_amount = $txt_amount * $CurrencyRate;

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

        /* ======================================== get sys preference ========================================= */
        $account_advance = $this->m_expense_cashbon->get_account_advance_cashbon($kategoriid);

        if ($account_advance == false) {
            $hasil = 0;
            $this->trans_rollback('journal');
        } else {

            /* ====================== set account no cash bon================================================ */
            $akun_number = $account_advance;

            /* ======================================= delete journal ============================================== */
            //$this->m_expense_cashbon->m_delete_journal($EBonNumber);
            $this->trans_data['delete_journal']['TransNumber'] = $EBonNumber;

            /* ======================================= update group ================================================= */
            $this->update_group($EBonNumber, $BranchCode, $DepartmentCode, $EmployeeCode, $EBonDate, $EBonDesc, $txt_amount, $BankPayment, $CurrencyCode, $CurrencyRate, $ChequeNumber, $ChequeDate, $ChequeAmount);

            /* ======================================= update detail ================================================ */
            $this->update_detail($detail_expense_cashbon, $kategoriid, $EBonNumber, $txt_amount, $akun_number);

            /* ======================================= insert journal ============================================== */
            $this->insert_journal($EBonDate, $EBonNumber, $akun_number, $BankPayment, $total_amount, $EBonDesc, $txt_amount);

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

            $this->trans_data = [];

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

    function approved_mgr() {
        $EBonNumber = $this->input->post('txt_exp_cashbon_no');
        $data_approval = array(
            "TransStatus" => 1,
            "AppFinished" => 1,
            "AppLevel1Status" => 1,
            "AppLevel1Code" => $this->session->userdata('username'),
            "AppLevel1Date" => date('Y-m-d'),
            "EBonLockStatus" => 0,
            "LastUser" => $this->session->userdata('username')
        );

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

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

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

        $arr_no = explode("/", $EBonNumber);
        $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_cashbon = array(
            "TransStatus" => 4,
            "AppFinished" => 0,
            "AppLevel1Status" => 0,
            "AppLevel1Date" => 0,
            "EBonLockStatus" => 1,
            "LastUser" => $this->session->userdata('username')
        );

        /* ==================================== cek payment cash bon ================================= */
        $cek_payment = $this->m_expense_cashbon->m_cek_payment($EBonNumber);

        if ($cek_payment) {

            /* =================================== get no payment ==================================================== */
            $no_payment = $this->m_expense_cashbon->get_no_payment($EBonNumber);

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

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

            if ($check_period == false) {

                /* =============================update piutang karyawan/ reverse =================================== */
                //$this->m_expense_cashbon->update_to_reverse_cashbon($EBonNumber,$data_cashbon);
                $this->trans_data['reverse_data']['data'] = $data_cashbon;
                $this->trans_data['reverse_data']['TransNumber'] = $EBonNumber;

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

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

                $this->trans_data = [];

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

                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_detail($EBonNumber) {
        $CompanyCode = $this->session->userdata('company');
        $replace_no = str_replace(".", "/", $EBonNumber);
        $cashbon_number = str_replace("_", "-", $replace_no);

        //$arr_no 			= explode('/',$cashbon_number);
        //$year_transaction 	= 2000 + (int)substr($arr_no[1],2,2);

        $cabon = $this->m_expense_cashbon->get_cash_bon_grup($cashbon_number);
        $cabon_branch = $cabon->BranchCode;
        $data['date_journal'] = $this->m_expense_cashbon->get_date_journal_cashbon($cashbon_number);
        $data['list_jurnal'] = $this->m_expense_cashbon->get_all_journal_cashbon($cashbon_number, $cabon->BranchCode);

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

    public function to_print($EBonNumber) {
        $id = str_replace(".", "/", $EBonNumber);

        $data['list_header'] = $this->m_expense_cashbon->get_detail_header($id);
        $data['detail_cashbon'] = $this->m_expense_cashbon->get_detail_cashbon($id);

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

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

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

        if ($EBonNumber != "") {

            $data['list_transaksi'] = $this->m_expense_cashbon->get_detail_item_print($EBonNumber, $BranchCode, '=');


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

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

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

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

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

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'suspend', 1, $EBonNumber);
        } 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) {
            $cashbon_number = $this->input->post('txt_exp_cashbon_no');

            $cek_app_status_mgr = $this->m_expense_cashbon->cek_status_app_mgr($cashbon_number);
            if (!empty($cek_app_status_mgr)) {
                $TransStatus = 1;
            } else {
                $TransStatus = 4;
            }

            $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_expense_cashbon->approval_status($data, $cashbon_number);

            $app_finished = array('AppFinished' => 1);
            $cek_app = $this->m_expense_cashbon->cek_app($cashbon_number);

            if (!empty($cek_app)) {
                $this->m_expense_cashbon->status_finished($app_finished, $cashbon_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) {
            $cashbon_number = $this->input->post('txt_exp_cashbon_no');

            /* $cek_app_status_dir = $this->m_expense_cashbon->cek_status_app_dir($cashbon_number);
              if(!empty($cek_app_status_dir)){
              $TransStatus = 1;
              } else {
              $TransStatus = 5;
              } */

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

            // transaction begin
            $this->db->trans_begin();
            $this->m_expense_cashbon->approval_status($data, $cashbon_number);

            $app_finished = array('AppFinished' => 1);
            $cek_app = $this->m_expense_cashbon->cek_app($cashbon_number);

            //if(!empty($cek_app)){
            $this->m_expense_cashbon->status_finished($app_finished, $cashbon_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 trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status'] = false;

        if ($modus == 'journal') {
            $result['message'] = get_notification('preference', 0);
        } else {
            $result['message'] = get_notification_transaksi($this->name, $modus, 0);
        }

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

    public function get_ebon_number() {
        $ebon_date = $this->input->post('ebon_af_date') == '' ? date('d-m-Y') : $this->input->post('ebon_af_date');
        $ebon_no = $this->m_expense_cashbon->create_ebon_number($ebon_date);

        $result['status'] = true;
        $result['number'] = $ebon_no;

        echo json_encode($result);
    }

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

}
