<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 06-10-2014	
 * 	Revisi 	: 
 */

class Other_payment extends CI_Controller {

    public $menu_id = 356;
    public $menu_model = 'm_other_payment';
    public $name = 'Other Payment';
    public $trans_data = array();

    public function __construct() {
        parent::__construct();
        $this->load->model('m_other_payment');
        $this->load->model('m_account_journal');
        $this->load->helper('message_helper');
        $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();
            }
        }
    }

    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');
                    $data['menu_model'] = $this->menu_model;

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

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

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

    //Function Menampilkan Data Pada Datagrid
    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================= */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('CPMoreNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('CPMoreDesc', $Desc);
        } //change
        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_otherpayment.CPMoreDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_otherpayment.CPMoreDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_otherpayment'); //change
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_other_payment->get_all(); //change

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

            $hasil[] = array(
                'TransNumber' => $result[$i]->CPMoreNumber, //change
                'CPayDate' => $result[$i]->CPMoreDate, //change
                'CPayTotalAmount' => $result[$i]->CPMoreTotalAmount, //change
                'CPayDesc' => $result[$i]->CPMoreDesc, //change
                'CreatedBy' => $result[$i]->CreatedBy, //change
                'BranchName' => $result[$i]->BranchName,
                'CPMoreDate' => $result[$i]->CPMoreDate,
                'AccountName' => $result[$i]->AccountName,
                'TransStatus' => $TransStatus
            );
        }

        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 accountgl() {
        $data = $this->load->m_payment->get_accountgl();
        echo json_encode($data);
    }

    public function all_accountpembiayaan($company_code) {
        $data = $this->m_other_payment->get_account_by_company($company_code);
        echo json_encode($data);
    }

    public function all_department($company_code) {
        $data = $this->m_payment->get_department_by_company($company_code);
        echo json_encode($data);
    }

    public function get_payment_number() {
        $preg_date = $this->input->post('Pay_date') == '' ? date('d-m-Y') : $this->input->post('Pay_date');
        $pay_number = $this->m_payment->create_pay_number($preg_date);

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

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

    public function get_account_bank($branch_code) {
        $branch = str_replace('_', '-', $branch_code);
        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');
        $account_bank = $this->m_other_payment->get_account_bank_2($CompanyCode, $branch);
        echo "$account_bank";
    }

    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');
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $sess_brach = $this->session->userdata('branch');

                    //$data['account_bank'] 		= $this->m_other_payment->get_account_bank($this->session->userdata('company'),$sess_brach);
                    //$data['pay_number']  			= $this->m_payment->create_pay_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);

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

    public function get_account_bank_add() {

        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');
        $list_bank = $this->m_other_payment->get_account_bank($CompanyCode, $BranchCode);

        echo "$list_bank";
    }

    public function proses_tutup() {
        $this->db->trans_rollback();
        die();
    }

    public function insert() {
        /* =======================deklar variabel saat insert========================= */
        $txt_payment_date = $this->input->post('txt_payment_date');
        $cmb_bank_account = $this->input->post('cmb_bank_account');
        $txa_memo = $this->input->post('txa_memo');
        $txt_amount = $this->input->post('txt_amount');
        $currency_code = $this->input->post('currency_code');
        $cheque_number = $this->input->post('cheque_number');
        $currency_rate = $this->input->post('txt_rate');
        $detail = $this->input->post('detail');
        $result_insert = 0;
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

        /* =====================================cashpayment number========================================== */
        $txt_payment_no = $this->m_other_payment->create_payment_number($txt_payment_date);


        /* =====================================fungsi insert ke table cash payment========================================= */
        $this->insert_group($txt_payment_no, $txt_payment_date, $cmb_bank_account, $txa_memo, $txt_amount, $currency_code, $currency_rate,$cheque_number);
        /* =====================================end fungsi insert ke table cash payment========================================= */
        /* =====================================fungsi insert to at_cpaydetail========================================= */
        $this->insert_detail($detail, $txt_payment_no);
        /* =====================================fungsi insert to journal========================================= */
        $this->insert_journal($txt_payment_no, $currency_code, $currency_rate, $cmb_bank_account, $txt_amount, $txa_memo, $detail, $txt_payment_date, true);
        /* =====================================end fungsi insert to at_cpayjournal ========================================= */

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

        $this->trans_data = [];

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

        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');
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

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

                    $data['payment'] = $this->m_other_payment->get_payment($payment_number);
                    $data['payment_detail'] = $this->m_other_payment->get_payment_detail($payment_number);
                    $data['account_bank'] = $this->m_other_payment->get_account_bank($this->session->userdata('company'), $this->session->userdata('branch'));

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

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

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

        $exsist_trans_status = $this->input->post('exsist_trans_status');
        $chk_suspend = $this->input->post('copy_suspend');
        $code_appmgrspv = $this->input->post('code_appmgrspv');
        $code_appdir = $this->input->post('code_appdir');
        $txa_memo = $this->input->post('txa_memo');
        $txt_amount = $this->input->post('txt_amount');
        $cmb_bank_account = $this->input->post('cmb_bank_account');
        $txt_payment_date = $this->input->post('txt_payment_date');
        $app_level1_status = null;
        $app_level1_code = null;
        $app_level1_date = null;
        $app_level2_status = null;
        $app_level2_code = null;
        $app_level2_date = null;
        $result_insert = 0;
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

        $total_amount = 0;

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


        /* =============================delete detail =================================== */
        foreach ($detail as $row) {

            $AccountName = $row->AccountName;
            $CPayAmount = $row->CPayAmount;
            $CPayMemo = $row->CPayMemo;
            $DepartmentName = $row->DepartmentName;
            $CPayDetailID = $row->CPayDetailID;
            $DepartmentAccountCode = $row->DepartmentAccountCode;
            $RowStatus = $row->RowStatus;

            $AccountNumber = $this->m_payment->get_accountnumber($row->AccountName);
            foreach ($AccountNumber as $acc_numb) {
                $acc = $acc_numb->AccountNumber;
            }

            $DepartmentCode = $this->m_payment->get_departmentcode($row->DepartmentName);
            foreach ($DepartmentCode as $dept_numb) {
                $dept = $dept_numb->DepartmentCode;
            }

            if ($RowStatus == 3) {

                /* ==================delete cpydetail table dengan rowstatus= 3 ============================= */
                $this->m_payment->m_delete_detail($CPayDetailID);
            } else {
                $total_amount += $CPayAmount;
            }
        }

        /* ==================update group ============================= */
        $this->update_group($txt_payment_no, null, null, null, $total_amount, true);

        /* =============================delete journal =================================== */
        $this->m_payment->m_delete_journal($txt_payment_no);
        /* ==================insert journal ============================= */
        $this->insert_journal($txt_payment_no, $cmb_bank_account, $total_amount, $txa_memo, $detail, $txt_payment_date);


        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('delete', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('delete', 1);
        }

        /* ============================= End Transac =================================== */

        echo json_encode($result);
    }

    public function insert_group($txt_payment_no, $txt_payment_date, $cmb_bank_account, $txa_memo, $txt_amount, $currency_code, $currency_rate,$cheque_number) {
        /* =========$data = variabel array untuk insert ke at_cashpayment table============== */
        $data = array(
            'BranchCode' => $this->session->userdata('branch'),
            'CPMoreNumber' => $txt_payment_no,
            'CPMoreDate' => date("Y-m-d", strtotime($txt_payment_date)),
            'BankPayment' => $cmb_bank_account,
            'CPMoreDesc' => $txa_memo,
            'CPMoreTotalAmount' => $txt_amount,
            'CurrencyCode' => $currency_code,
            'CurrencyRate' => $currency_rate,
            'TransStatus' => 5,
            'ChequeNumber' => $cheque_number,
            'CreatedBy' => $this->session->userdata('username'),
            'CreatedAt' => date("Y-m-d H:i:s"),
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_other_payment->m_insert_group($data);
        $this->trans_data['insert_group']['data'] = $data;
    }

    public function insert_detail($detail, $pay_number) {
        /* =============fungsi insert to at_cpaydetail=================== */
        foreach ($detail as $row) {

            $CPayAmount = $row->Amount;
            $CPayMemo = $row->Memo;


            $AccountNumber = $this->m_other_payment->get_accountnumber($row->AccountName);
            foreach ($AccountNumber as $acc_numb) {
                $acc = $acc_numb->AccountNumber;
            }

            $detail_data = array(
                'CPMoreNumber' => $pay_number,
                'CPMoreAccountNumber' => $acc,
                'CPMoreAmount' => $CPayAmount,
                'CPMoreMemo' => $CPayMemo,
                'LastUser' => $this->session->userdata("username")
            );


            //$this->m_other_payment->m_insert_detail($detail_data);
            $this->trans_data['insert_detail']['data'][] = $detail_data;
        }
    }

    public function insert_journal($txt_payment_no, $currency_code, $CurrencyRate, $cmb_bank_account, $total_amount, $txa_memo, $detail, $txt_payment_date, $validasi = false) {
        /* =====================================fungsi insert to at_cpayjournal========================================= */
        foreach ($detail as $row) {

            $AccountName = $row->AccountName;
            $CPayAmount = $validasi == false ? $row->CPMoreAmount : $row->Amount;
            $CPayMemo = $validasi == false ? $row->CPMoreMemo : $row->Memo;
            //$DepartmentName 		= $row->DepartmentName;
            $CPayDetailID = $validasi == false ? $row->CPMoreDetailID : '';
            //$DepartmentAccountCode 	= $validasi == false ? $row->DepartmentAccountCode:'';
            $RowStatus = $validasi == false ? $row->RowStatus : '';


            $AmountCurrency = $CPayAmount;

            $AccountNumber = $this->m_other_payment->get_accountnumber($row->AccountName);
            foreach ($AccountNumber as $acc_numb) {
                $acc = $acc_numb->AccountNumber;
                $Acc_Type_Name = $acc_numb->Acc_Type_Name;
                $Sub_Type_name = $acc_numb->Sub_Type_Name;
            }

            $debet_credit = $this->m_account_journal->debet_kredit($Acc_Type_Name, $Sub_Type_name);

            $data_journal_debet = array(
                'CPMoreDate' => date("Y-m-d", strtotime($txt_payment_date)),
                'CPMoreNumber' => $txt_payment_no,
                'CPMoreAccountNumber' => trim($acc),
                'CPMoreSaldoDebet' => ($CPayAmount * $CurrencyRate),
                'CPMoreSaldoCredit' => 0,
                'AmountCurrency' => $AmountCurrency,
                'CPMoreDesc' => $txa_memo,
                'CPMoreSignStatus' => $debet_credit == 'Debet' ? 0 : 1,
                'LastUser' => $this->session->userdata('username')
            );

            if ($validasi == false) {
                if ($RowStatus != 3) {
                    //$this->m_other_payment->m_insert_journal($data_journal_debet);
                    $this->trans_data['insert_journal']['data'][] = $data_journal_debet;
                }
            } else {
                $this->trans_data['insert_journal']['data'][] = $data_journal_debet;
            }
        }


        if ($currency_code == "IDR") {
            $AmountCurrency = $total_amount;
        } else {
            $AmountCurrency = $total_amount * $CurrencyRate;
        }

        $data_journal_credit = array(
            'CPMoreDate' => date("Y-m-d", strtotime($txt_payment_date)),
            'CPMoreNumber' => $txt_payment_no,
            'CPMoreAccountNumber' => trim($cmb_bank_account),
            'CPMoreSaldoDebet' => 0,
            'CPMoreSaldoCredit' => $AmountCurrency,
            'AmountCurrency' => $total_amount,
            'CPMoreDesc' => $txa_memo,
            'CPMoreSignStatus' => 1,
            'LastUser' => $this->session->userdata('username')
        );

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

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

        $exsist_trans_status = $this->input->post('exsist_trans_status');
        $chk_suspend = $this->input->post('copy_suspend');
        $code_appmgrspv = $this->input->post('code_appmgrspv');
        $code_appdir = $this->input->post('code_appdir');
        $txa_memo = $this->input->post('txa_memo');
        $txt_amount = $this->input->post('txt_amount');
        $cmb_bank_account = $this->input->post('cmb_bank_account');
        $txt_payment_date = $this->input->post('txt_payment_date');
        $currency_code = $this->input->post('currency_code');
        $currency_rate = $this->input->post('txt_rate');
        $cheque_number = $this->input->post('cheque_number');
        $app_level1_status = null;
        $app_level1_code = null;
        $app_level1_date = null;
        $app_level2_status = null;
        $app_level2_code = null;
        $app_level2_date = null;
        $result_insert = 0;
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);


        /* ===========================update group===================================================================== */
        $update_group = $this->update_group($txt_payment_no, $cmb_bank_account, $txt_payment_date, $txa_memo, $txt_amount, $currency_code, $currency_rate,$cheque_number);

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

        /* ===========================delete detail================================================================= */
        $this->trans_data['delete_detail']['total'] = count($detail_id);
        if (count($detail_id) > 0) {
            foreach ($detail_id as $CPMoreDetailID) {
                //$this->m_other_payment->m_delete_detail($CPMoreDetailID);
                $this->trans_data['delete_detail']['CPMoreDetailID'][] = $CPMoreDetailID;
            }
        }

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

        /* =================================================== Insert JOurnal =============================================================== */
        $this->insert_journal($txt_payment_no, $currency_code, $currency_rate, $cmb_bank_account, $txt_amount, $txa_memo, $detail, $txt_payment_date);

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    /* ===================update group===================================================================== */

    function update_group($txt_payment_no, $cmb_bank_account, $txt_payment_date, $txa_memo, $txt_amount, $currency_code, $currency_rate,$cheque_number,$validasi = false) {
        if ($validasi == false) {
            $data = array(
                'BankPayment' => $cmb_bank_account,
                //'CPayDate' 			=> date("Y-m-d", strtotime($txt_payment_date)),
                'CPMoreDesc' => $txa_memo,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'CPMoreTotalAmount' => $txt_amount,
                'ChequeNumber' => $cheque_number,
                'LastUser' => $this->session->userdata('username')
            );
        } else {

            $data = array(
                'CPMoreDate' => $txt_payment_date,
                'CPMoreTotalAmount' => $txt_amount,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'ChequeNumber' => $cheque_number,
                'LastUser' => $this->session->userdata('username')
            );
        }

        //$this->m_other_payment->m_update_group($data, $txt_payment_no);
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $txt_payment_no;
    }

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

    /* ===================update detail===================================================================== */

    function update_detail($detail) {
        foreach ($detail as $row) {

            $CPMoreAmount = $row->CPMoreAmount;
            $CPMoreMemo = $row->CPMoreMemo;
            $CPMoreDetailID = $row->CPMoreDetailID;

            $AccountNumber = $this->m_other_payment->get_accountnumber($row->AccountName);
            foreach ($AccountNumber as $acc_numb) {
                $acc = $acc_numb->AccountNumber;
            }

            $detail_data = array(
                'CPMoreAccountNumber' => $acc,
                'CPMoreAmount' => $CPMoreAmount,
                'CPMoreMemo' => $CPMoreMemo,
                'LastUser' => $this->session->userdata("username")
            );

            //$update_detail 	= $this->m_other_payment->m_update_detail($detail_data, $CPMoreDetailID);
            $this->trans_data['update_detail']['data'][] = $detail_data;
            $this->trans_data['update_detail']['CPMoreDetailID'][] = $CPMoreDetailID;
            ;
        }
    }

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

    /* ===================Approv Dir===================================================================== */

    function approved_dir() {
        $txt_payment_no = $this->input->post('id');
        $data = array(
            "TransStatus" => 2,
            "AppFinished" => 1,
            "AppLevel1Status" => 1,
            "AppLevel1Code" => $this->session->userdata('username'),
            "AppLevel1Date" => date('Y-m-d'),
            "LastUser" => $this->session->userdata('username')
        );

        /* =============================Fungsi Update payment =================================== */
        //$this->m_other_payment->update_approved_data($data,$txt_payment_no);

        $this->trans_data['approve_data']['data'] = $data;
        $this->trans_data['approve_data']['TransNumber'] = $txt_payment_no;

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

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

    function detail_payment($payment_number) {
        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $id = $uri4 . '/' . $uri5 . '/' . $uri6;

        $detail = $this->m_other_payment->get_payment_detail($id);
        echo json_encode($detail);
    }

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

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

        /* ==================== update suspend data ================== */
        //$this->m_other_payment->suspend($data, $id);

        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = trim($id);

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

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification('suspend', 1);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        }

        echo json_encode($result);
    }

    function get_status_transaki() {
        $trans_number = $this->input->post('number');
        $get_number = $this->m_payment->get_all_by_no($trans_number);

        foreach ($get_number as $row) {
            $cash_number[] = $row->TransStatus;
        }

        $data = array(
            'number_cash' => $cash_number
        );
        echo json_encode($data);
    }

    public function suspend() {
        $id = $this->input->post('id');
        $hasil = 0;

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

        $this->db->trans_begin();
        $hasil = $this->m_payment->suspend($data, $id);
        if ($hasil == 0) {
            $this->proses_tutup();
        }

        if ($hasil == 0) {
            $this->db->trans_rollback();
            $hasil = 0;
        } else {
            $this->db->trans_commit();
            $hasil = 1;
        }

        if ($hasil == 1) {
            $result['status'] = true;
            $result['message'] = get_notification('suspend', $hasil);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', $hasil);
        }
        echo json_encode($result);
    }

    //Function view print data
    public function to_preview($obj_string = null) {
        $data['company'] = $this->m_other_payment->get_company_by_branch($this->session->userdata('branch'));
        //$data['list']	 = $this->m_other_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);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_other_payment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('cash_and_bank/other_payment/v_print_other_payment', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_other_payment->get_company_by_branch($this->session->userdata('branch'));
        //$data['list']	 = $this->m_other_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('cash_and_bank/other_payment/v_print_other_payment', $data);
        $this->load->view('v_footer');
    }

    //Function view print data by payment number
    public function to_preview_by_payment_number() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

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

        $data['company'] = $this->m_payment->get_company_by_branch($this->session->userdata('branch'));
        $data['list'] = $this->m_payment->get_by_payment_number($payment_number);
        $this->load->view('v_header');
        $this->load->view('cash_and_bank/payment/v_print_payment', $data);
        $this->load->view('v_footer');
    }

    //Daswan Fungsi untuk print detail
    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);
        $companyCode = $this->session->userdata('company');

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

        if ($id != "") {
            $data['detail'] = $this->m_other_payment->get_detail_print($id);
            $data['list'] = $this->m_other_payment->get_detail_item_print($data['detail']->CPMoreNumber);

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

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

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

        $data['department'] = $this->m_payment->get_department_name($this->session->userdata('department'));

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

    public function to_journal() {
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_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());

        $potongan_id = explode("/", $payment_number);
        $id_branch = $potongan_id[0];

        $data['company_name'] = $this->m_other_payment->get_company_name($CompanyCode);
        $data['list'] = $this->m_other_payment->get_datatojournal($payment_number);
        $data['list_detail'] = $this->m_other_payment->get_datatojournal_detail($payment_number, $CompanyCode, $id_branch);

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

    /* ===================================Fungsi reverse transaksi========================================== */

    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_payment = array(
            "TransStatus" => 5,
            "AppFinished" => 0
        );

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

        if ($check_period == false) {

            /* =============================update at_cashpayment/ reverse =================================== */
            //$this->m_other_payment->update_to_reverse_payment($txt_payment_no,$data_payment);

            /* ============================= delete reconcile =============================================== */
            //$this->m_other_payment->delete_reconcile($txt_payment_no);

            $this->trans_data['reverse_data']['data'] = $data_payment;
            $this->trans_data['reverse_data']['TransNumber'] = trim($txt_payment_no);

            $this->trans_data['delete_reconcile']['TransNumber'] = trim($txt_payment_no);

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

            $this->trans_data = [];

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

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

    public function get_AccountBsStatus($acc_number) {
        return $this->m_payment->get_AccountBsStatus($acc_number);
    }

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

}
