<?php

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

/* 	
 * 	Author 	: Tagor \ Tanggal : 07-10-2014	
 * 	Revisi 	: 
 */
/*
  Author : Fachri Nugraha
  Revisi : 20-01-2015
 */

class Piutang_afiliasi extends CI_Controller {

    //initial menu id dari tabel m_menu
    public $menu_id = 236;
    public $menu_model = 'm_piutang_afiliasi';
    public $name = 'Piutang Afiliasi';
    public $trans_data = array();
    //initial 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_piutang_afiliasi');
        $this->load->model('m_payment_afiliasi');
        $this->load->model('m_account_journal');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
        $this->load->helper('convert_date');
        $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 {
                    //untuk ambil data dari session dan hak akses
                    $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);

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

    //Function Menampilkan Data Pada Data Grid View
    // public function ajax(){
    // 	$sess_company		= $this->session->userdata('company');
    //        $sess_branch		= $this->session->userdata('branch');
    //        $sess_branch_status	= $this->session->userdata('branch_status');
    //        $data = $this->m_piutang_afiliasi->get_all($sess_company,$sess_branch,$sess_branch_status);       
    //        echo json_encode($data);
    //    }

    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');
        $CompanyNameFrom = isset($param['txt_TransferFrom']) ? mysql_real_escape_string($param['txt_TransferFrom']) : '';
        $CompanyNameTo = isset($param['txt_TransferTo']) ? mysql_real_escape_string($param['txt_TransferTo']) : '';

        $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============================================================ */
        $this->db->join('am_company as CompanyFrom', 'CompanyFrom.CompanyCode = at_afiliasidebt.CompTransCode', 'INNER');
        $this->db->join('am_company as CompanyTo', 'CompanyTo.CompanyCode = at_afiliasidebt.CompRecpCode', 'INNER');
        /* ========================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'));
        }

        /* ===================================find by trasnfer from dan transfer to========================================================= */
        if ($CompanyNameFrom != '') {
            $this->db->like('CompanyFrom.CompanyName', $CompanyNameFrom);
        }
        if ($CompanyNameTo != '') {
            $this->db->like('CompanyTo.CompanyName', $CompanyNameTo);
        }
        /* =============================================end=================================================================== */
        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_afiliasidebt.ADebtDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_afiliasidebt.ADebtDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }

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

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

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

            $hasil[] = array(
                'TransNumber' => $result[$i]->AfiliasiNo,
                'FromCompany' => $result[$i]->FromCompany, //change
                'ToCompany' => $result[$i]->ToCompany, //change
                'ChequeNumber' => $result[$i]->ChequeNumber, //change
                'ADebtDate' => $result[$i]->ADebtDate, //change
                'ADebtAmount' => $result[$i]->ADebtAmount, //change
                'TransStatus' => $TransStatus,
                'LinkNumber' => $result[$i]->LinkNumber,
                'CompTransCode' => $result[$i]->CompTransCode,
                'BranchName' => $result[$i]->BranchName,
                'BankFrom' => $result[$i]->BankFrom,
                'BankTo' => $result[$i]->BankTo,
                '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);
        }
    }

    function company_by_login($company_code) {
        $result = $this->m_piutang_afiliasi->company_by_login($company_code);
        echo json_encode($result);
    }

    function company_not_by_login($company_code) {
        $result = $this->m_piutang_afiliasi->company_not_by_login($company_code);
        echo json_encode($result);
    }

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

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

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

    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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $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');

                    $afiliasi_number = $this->m_piutang_afiliasi->get_latest_afiliasi_number($sess_brach);
                    $company_code = $this->session->userdata('company');

                    $data['detail'] = $this->m_piutang_afiliasi->company_new_form($company_code);

                    $data['piutang_afiliasi_number'] = $this->m_piutang_afiliasi->create_piutang_afiliasi_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('list/cash_and_bank/pinjaman_afiliasi/v_new_pinjamanafiliasi', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function proses_tutup() {
        $this->db->trans_rollback();
        $hasil = 0;
        $result['status'] = false;
        $result['message'] = get_notification('proses_tutup', $hasil);
        echo json_encode($result);
        die();
    }

    public function get_piutang_afiliasi_number() {
        $preg_date = $this->input->post('Piutang_af_date') == '' ? date('d-m-Y') : $this->input->post('Piutang_af_date');
        $af_number = $this->m_piutang_afiliasi->create_piutang_afiliasi_number($preg_date);

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

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

    public function insert_group_company_transaksi($cmb_fromcompany, $cmb_bankfrom, $afiliasi_no, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $chk_giromundur, $txt_cheque_date, $txt_amount, $txa_memo, $Var_gabungan) {
        $data_group = array(
            'BranchCode' => $this->session->userdata('branch'),
            'CompTransCode' => $cmb_fromcompany,
            'BankTransfer' => $cmb_bankfrom,
            'ADebtNumber' => $afiliasi_no,
            'CompRecpCode' => $cmb_tocompany,
            'BankReceipt' => $cmb_bankto,
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ChequeNumber' => $txt_chequeno,
            'CqTermStatus' => $chk_giromundur,
            'ChequeDate' => date('Y-m-d', strtotime($txt_cheque_date)),
            'ADebtAmount' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'TransStatus' => 5,
            'LinkNumber' => $Var_gabungan,
            'AdebtIsLock' => 1,
            'CreditStatus' => 0,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['insert_group_piutang']['data'] = $data_group;
    }

    public function insert_group_company_receipt($BranchCode, $cmb_fromcompany, $cmb_bankfrom, $NextAfilNoCompTo, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $chk_giromundur, $txt_cheque_date, $txt_amount, $txa_memo, $Var_gabungan) {
        $data_to_company = array(
            'BranchCode' => $BranchCode, //$BrchCodeCompTo->BranchCode,
            'CompTransCode' => $cmb_fromcompany,
            'BankTransfer' => $cmb_bankfrom,
            'ADebtNumber' => $NextAfilNoCompTo,
            'CompRecpCode' => $cmb_tocompany,
            'BankReceipt' => $cmb_bankto,
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ChequeNumber' => $txt_chequeno,
            'CqTermStatus' => $chk_giromundur,
            'ChequeDate' => date('Y-m-d', strtotime($txt_cheque_date)),
            'ADebtAmount' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'TransStatus' => 5,
            'LinkNumber' => $Var_gabungan,
            'AdebtIsLock' => 1,
            'CreditStatus' => 1,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['insert_group_hutang']['data'] = $data_to_company;
    }

    public function cek_sys_other_account($cmb_fromcompany, $cmb_tocompany) {

        $nomor_akun = 0;
        $nomor_akun_recip = 0;

        $get_sys_otheraccount_paymen_afiliasi = $this->m_piutang_afiliasi->get_sys_otheraccount_paymen_afiliasi($cmb_fromcompany);
        foreach ($get_sys_otheraccount_paymen_afiliasi as $row_paymen) {
            $nomor_akun = $row_paymen->AccountNumber;
        }

        $get_sys_otheraccount_recip_afiliasi = $this->m_piutang_afiliasi->get_sys_otheraccount_recip_afiliasi($cmb_tocompany);
        foreach ($get_sys_otheraccount_recip_afiliasi as $row_recip) {
            $nomor_akun_recip = $row_recip->AccountNumber;
        }

        $return['nomor_akun'] = $nomor_akun;
        $return['nomor_akun_recip'] = $nomor_akun_recip;
        return $return;
    }

    public function insert_journal_company_transaksi($txt_afiliasi_date, $afiliasi_no, $nomor_akun_recip, $cmb_bankfrom, $txt_amount, $txa_memo) {
        //inisialiasi to journal debet
        $data_journal_debet = array(
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ADebtNumber' => $afiliasi_no,
            'ADebtAccountNumber' => $nomor_akun_recip,
            'ADebtSaldoDebet' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'ADebtSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

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

        //inisialiasi to journal credit
        $data_journal_credit = array(
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ADebtNumber' => $afiliasi_no,
            'ADebtAccountNumber' => $cmb_bankfrom,
            'ADebtSaldoCredit' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'ADebtSignStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

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

    public function insert_journal_company_receipt($txt_afiliasi_date, $NextAfilNoCompTo, $cmb_bankto, $nomor_akun, $txt_amount, $txa_memo) {

        $data_journal_debet_comp_to = array(
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ADebtNumber' => $NextAfilNoCompTo,
            'ADebtAccountNumber' => $cmb_bankto,
            'ADebtSaldoDebet' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'ADebtSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

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

        //inisialiasi to journal credit Company To
        $data_journal_credit_comp_to = array(
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ADebtNumber' => $NextAfilNoCompTo,
            'ADebtAccountNumber' => $nomor_akun,
            'ADebtSaldoCredit' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'ADebtSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

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

    public function create_number_company_receipt_insert($BrchCodeCompTo) {

        $AfilNoCompTo = $this->m_piutang_afiliasi->get_latest_afiliasi_number_comp_to($BrchCodeCompTo->BranchCode);

        $pecah = explode("/", $AfilNoCompTo);
        $last_index = (count($pecah) - 1);
        $last_number = $pecah[$last_index];
        $result_numb = $last_number + 1;

        $count_afnumb = strlen($result_numb);

        if ($count_afnumb == 1) {
            $next_afiliasi_numb = '00' . $result_numb;
        } elseif ($count_afnumb == 2) {
            $next_afiliasi_numb = '0' . $result_numb;
        } elseif ($count_afnumb == 3) {
            $next_afiliasi_numb = $result_numb;
        } else {
            $next_afiliasi_numb = '001';
        }

        $NextAfilNoCompTo = $BrchCodeCompTo->BranchCode . "/" . date('m') . date('y') . "AP" . "/" . $next_afiliasi_numb;
        return $NextAfilNoCompTo;
    }

    function insert() {

        if (isset($_POST['chk_giromundur'])) {
            $chk_giromundur = $this->input->post('chk_giromundur');
        } else {
            $chk_giromundur = '0';
        }

        $Nm_Branchcode = $this->session->userdata('branch');
        $cmb_fromcompany = $this->input->post('cmb_fromcompany');
        $cmb_bankfrom = $this->input->post('cmb_bankfrom');
        $txt_afiliasi_date = $this->input->post('txt_afiliasi_date');

        /* ======================================= Fungsi Create Piutang Afiliasi Number ============================== */
        $afiliasi_no = $this->m_piutang_afiliasi->create_piutang_afiliasi_number($txt_afiliasi_date);

        $cmb_tocompany = $this->input->post('cmb_tocompany');
        $cmb_bankto = $this->input->post('cmb_bankto');
        $txt_chequeno = $this->input->post('txt_chequeno');
        $txt_cheque_date = $this->input->post('txt_cheque_date');
        $txt_amount = $this->input->post('txt_amount');
        $txa_memo = $this->input->post('txa_memo');
        $result_insert = 0;


        $Var_gabungan = $afiliasi_no;

        /* ====================================== Get Branchcode untuk company receipt =============================== */
        $BrchCodeCompTo = $this->m_piutang_afiliasi->branch_code_comp_to($cmb_tocompany);

        /* ====================================== Fungsi Create Afiliasi No untuk Company Receipt =============================== */
        $NextAfilNoCompTo = $this->m_piutang_afiliasi->create_piutang_afiliasi_number($txt_afiliasi_date, $BrchCodeCompTo->BranchCode);

        /* ============================================================ Fungsi cek_sys_other_account  =================================== */
        $cek_sys_other_account = $this->cek_sys_other_account($cmb_fromcompany, $cmb_tocompany);

        /* ====================================== Cek Coa kedua company =============================== */
        $cek_coa_by_company_from = $this->m_piutang_afiliasi->get_coa_comapny_cmb_from($cmb_fromcompany, $cek_sys_other_account['nomor_akun_recip']);
        $cek_coa_by_company_to = $this->m_piutang_afiliasi->get_coa_comapny_cmb_to($cmb_tocompany, $cek_sys_other_account['nomor_akun']);

        if (($cek_sys_other_account['nomor_akun'] == 0) || ($cek_sys_other_account['nomor_akun_recip'] == 0)) {
            $result['status'] = false;
            $result['message'] = get_notification('preference', 0);
            echo json_encode($result);
        } elseif (($cek_coa_by_company_from == false ) || ($cek_coa_by_company_to == false)) {
            $result['status'] = false;
            $result['message'] = get_notification('coa', 0);
            echo json_encode($result);
        } else {

            /* ============================================================ Fungsi Insert group company Transaksi =================================== */
            $this->insert_group_company_transaksi($cmb_fromcompany, $cmb_bankfrom, $afiliasi_no, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $chk_giromundur, $txt_cheque_date, $txt_amount, $txa_memo, $Var_gabungan);

            /* ============================================================ Fungsi Insert group company Receipt =================================== */
            $this->insert_group_company_receipt($BrchCodeCompTo->BranchCode, $cmb_fromcompany, $cmb_bankfrom, $NextAfilNoCompTo, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $chk_giromundur, $txt_cheque_date, $txt_amount, $txa_memo, $Var_gabungan);

            /* ====================================================== Fungsi Insert Journal company transaksi =============================================== */
            $this->insert_journal_company_transaksi($txt_afiliasi_date, $afiliasi_no, $cek_sys_other_account['nomor_akun_recip'], $cmb_bankfrom, $txt_amount, $txa_memo);

            /* ====================================================== Fungsi Insert Journal company receipt =============================================== */
            $this->insert_journal_company_receipt($txt_afiliasi_date, $NextAfilNoCompTo, $cmb_bankto, $cek_sys_other_account['nomor_akun'], $txt_amount, $txa_memo);

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

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $afiliasi_no);
            } else {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $afiliasi_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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $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);

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

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

                    $data['afiliasi'] = $this->m_piutang_afiliasi->get_by_afiliasi_number($piutang_number);

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

    public function update_group($cmb_fromcompany, $cmb_bankfrom, $afiliasi_no, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $txt_amount, $txa_memo) {

        $data_group = array(
            'CompTransCode' => $cmb_fromcompany,
            'BankTransfer' => $cmb_bankfrom,
            'CompRecpCode' => $cmb_tocompany,
            'BankReceipt' => $cmb_bankto,
            'ADebtDate' => date('Y-m-d', strtotime($txt_afiliasi_date)),
            'ChequeNumber' => $txt_chequeno,
            'ADebtAmount' => $txt_amount,
            'ADebtDesc' => nl2br($txa_memo),
            'TransStatus' => 5,
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['update_group']['data'] = $data_group;
        $this->trans_data['update_group']['link_number'] = $afiliasi_no;
    }

    public function create_number_company_receipt_update($company_receipt_before, $BrchCodeCompTo) {

        if ($company_receipt_before['BranchCode'] == $BrchCodeCompTo->BranchCode) {

            $NextAfilNoCompTo = $company_receipt_before['ADebtNumber'];
        } else {

            /* ====================================== Fungsi Create Afiliasi No untuk Company Receipt =============================== */
            $AfilNoCompTo = $this->m_piutang_afiliasi->get_latest_afiliasi_number_comp_to($BrchCodeCompTo->BranchCode);

            $pecah = explode("/", $AfilNoCompTo);
            $last_index = (count($pecah) - 1);
            $last_number = $pecah[$last_index];
            $result_numb = $last_number + 1;

            $count_afnumb = strlen($result_numb);

            if ($count_afnumb == 1) {
                $next_afiliasi_numb = '00' . $result_numb;
            } elseif ($count_afnumb == 2) {
                $next_afiliasi_numb = '0' . $result_numb;
            } elseif ($count_afnumb == 3) {
                $next_afiliasi_numb = $result_numb;
            } else {
                $next_afiliasi_numb = '001';
            }

            $NextAfilNoCompTo = $BrchCodeCompTo->BranchCode . "/" . date('m') . date('y') . "AP" . "/" . $next_afiliasi_numb;
            /* ====================================== END Fungsi Create Afiliasi No untuk Company Receipt =============================== */
        }

        return $NextAfilNoCompTo;
    }

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

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

        $branch_code_hidden = $this->input->post('branch_code_hidden');
        $cmb_fromcompany = $this->input->post('cmb_fromcompany');
        $cmb_bankfrom = $this->input->post('cmb_bankfrom');
        $afiliasi_no = $this->input->post('afiliasi_no');
        $cmb_tocompany = $this->input->post('cmb_tocompany');
        $cmb_bankto = $this->input->post('cmb_bankto');
        $txt_afiliasi_date = $this->input->post('txt_afiliasi_date');
        $txt_chequeno = $this->input->post('txt_chequeno');
        $txt_cheque_date = $this->input->post('txt_cheque_date');
        $txt_amount = $this->input->post('txt_amount');
        $txa_memo = $this->input->post('txa_memo');
        $credit_status = $this->input->post('credit_status');
        $result_insert = 0;

        /* ====================================== Get Branchcode untuk company receipt =============================== */
        $BrchCodeCompTo = $this->m_piutang_afiliasi->branch_code_comp_to($cmb_tocompany);

        /* =================================== Fungsi get no afiliasi company receipt sebelumnya ================================ */
        $company_receipt_before = $this->m_piutang_afiliasi->get_afiliasi_number_company_receipt($link_number, $BranchCode);

        /* =================================== Fungsi create no afilasi company receipt ================================ */
        $NextAfilNoCompTo = $this->create_number_company_receipt_update($company_receipt_before, $BrchCodeCompTo);

        /* ====================================== Fungsi cek_sys_other_account  =================================== */
        $cek_sys_other_account = $this->cek_sys_other_account($cmb_fromcompany, $cmb_tocompany);

        /* ====================================== Cek Coa kedua company =============================== */
        $cek_coa_by_company_from = $this->m_piutang_afiliasi->get_coa_comapny_cmb_from($cmb_tocompany, $cek_sys_other_account['nomor_akun_recip']);
        $cek_coa_by_company_to = $this->m_piutang_afiliasi->get_coa_comapny_cmb_to($cmb_fromcompany, $cek_sys_other_account['nomor_akun']);

        if (($cek_sys_other_account['nomor_akun'] == 0) || ($cek_sys_other_account['nomor_akun_recip'] == 0)) {
            $result['status'] = false;
            $result['message'] = get_notification('preference', 0);

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

            echo json_encode($result);
        } else {

            /* ================================== Update group company transaksi ========================= */
            $this->update_group($cmb_fromcompany, $cmb_bankfrom, $afiliasi_no, $cmb_tocompany, $cmb_bankto, $txt_afiliasi_date, $txt_chequeno, $txt_amount, $txa_memo);

            /* ================================== Delete Journal ========================================== */
            $this->trans_data['delete_journal']['TransNumber'][] = $afiliasi_no;
            $this->trans_data['delete_journal']['TransNumber'][] = $company_receipt_before['ADebtNumber'];

            /* ================================== Insert Journal Company transaksi ======================= */
            $this->insert_journal_company_transaksi($txt_afiliasi_date, $afiliasi_no, $cek_sys_other_account['nomor_akun_recip'], $cmb_bankfrom, $txt_amount, $txa_memo);

            /* ================================== Insert Journal company receipt =================== */
            $this->insert_journal_company_receipt($txt_afiliasi_date, $NextAfilNoCompTo, $cmb_bankto, $cek_sys_other_account['nomor_akun'], $txt_amount, $txa_memo);

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

            $this->trans_data = [];

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

            echo json_encode($result);
        }
    }

    public function suspend() {
        $id = $this->input->post('id');
        $result_insert = 0;
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );
        $this->db->trans_begin();
        $result_insert = $this->m_piutang_afiliasi->suspend($data, $id);
        if ($result_insert == 0) {
            $this->proses_tutup();
        }

        if ($result_insert == 0) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('suspend', $result_insert);
        } else {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('suspend', $result_insert);
        }
        echo json_encode($result);
    }

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

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

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

        $result_return = $this->m_piutang_afiliasi->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_bank_bycompany($comp_code) {
        $branch = $this->session->userdata('branch');
        $pecah = explode("-", $branch);
        if ($pecah[1] == "HO") {
            $result = $this->m_piutang_afiliasi->get_bank_bycompany($comp_code);
            //echo $this->db->last_query();
        }
        echo json_encode($result);
    }

    //Function view print data
    public function to_preview($obj_string = null) {
        $branch = $this->session->userdata('branch');
        $data['company'] = $this->m_piutang_afiliasi->get_company_by_branch($branch);

        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['list']           = $this->m_piutang_afiliasi->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/pinjaman_afiliasi/v_print_pinjamanafiliasi', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA($data_grid = null) {
        $branch = $this->session->userdata('branch');
        $data['company'] = $this->m_piutang_afiliasi->get_company_by_branch($branch);
        //$data['list']	 	= $this->m_piutang_afiliasi->get_all_to_print($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('list/cash_and_bank/pinjaman_afiliasi/v_print_pinjamanafiliasi', $data);
        $this->load->view('v_footer');
    }

    //Function view print data by afiliasi number
    public function to_preview_by_afiliasi_number() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $piutang_number = str_replace($data['menu_link'] . '/to_preview_by_afiliasi_number/', "", $this->uri->uri_string());
        $data['list'] = $this->m_piutang_afiliasi->get_by_afiliasi_number($piutang_number);

        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/pinjaman_afiliasi/v_print_pinjamanafiliasi', $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);

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

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


        $data['list_to'] = $this->m_piutang_afiliasi->get_datatojournal_to($piutang_number);
        //echo $this->db->last_query();

        foreach ($data['list_to'] as $comp_receipt) {
            $comp_receipt_code = $comp_receipt->CompRecpCode;
            $CompTransCode = $comp_receipt->CompTransCode;
        }

        $data['akun_payment_from'] = $this->m_piutang_afiliasi->akun_payment_afiliasi($CompTransCode);

        $data['akun_payment_to'] = $this->m_piutang_afiliasi->akun_penerimaan_afiliasi($comp_receipt_code);

        $data['list_from'] = $this->m_piutang_afiliasi->get_datatojournal_from($piutang_number);

        $data['list_detail_from'] = $this->m_piutang_afiliasi->get_datatojournal_detail_from($piutang_number, $CompTransCode);

        $data['list_detail_to'] = $this->m_piutang_afiliasi->get_datatojournal_detail_to($piutang_number, $comp_receipt_code);

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

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

        $sess_department = $this->session->userdata('department');
        $piutang_number = str_replace($data['menu_link'] . '/to_print/', "", $this->uri->uri_string());

        $data['department'] = $this->m_piutang_afiliasi->get_department_name($sess_department);

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

    public function approved_dir() {

        $link_number = $this->input->post('link_id');
        $app_level2_status = 1;
        $app_level2_code = $this->session->userdata('username');
        $app_level2_date = date('Y-m-d');

        $data_approval = array(
            'TransStatus' => 1,
            'AppLevel2Status' => $app_level2_status,
            'AppLevel2Code' => $app_level2_code,
            'AppLevel2Date' => $app_level2_date,
            'AppFinished' => 1,
            'AdebtIsLock' => 0
        );

        /* ========================= Fungsi Approval data direktur =============================== */
        //$this->m_piutang_afiliasi->update_status_approval($link_number,$data_approval);
        $this->trans_data['approve_data']['data'] = $data_approval;
        $this->trans_data['approve_data']['link_number'] = $link_number;

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

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

    public function reversed_data() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */

        $link_number = $this->input->post('id');
        $sess_branch = $this->session->userdata('branch');

        /* ==================================== get no afiliasi receipt & transaksi =================================================== */
        $no_afiliasi_receipt = $this->m_piutang_afiliasi->get_no_afiliasi($link_number, $sess_branch, '!=');
        $no_afiliasi_transac = $this->m_piutang_afiliasi->get_no_afiliasi($link_number, $sess_branch, '=');

        $arr_no = explode("/", $no_afiliasi_transac);
        $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 = array(
            'AppLevel2Status' => 0,
            'AppLevel2Code' => null,
            'AppLevel2Date' => 0,
            "TransStatus" => 5,
            "AppFinished" => 0,
            'AdebtIsLock' => 1
        );

        /* =================================== cek payment transaction =============================================== */
        /* =================================== true = ada transaksi, false = tidak ada transaksi ===================== */
        $cek_payment = $this->m_piutang_afiliasi->cek_payment_transaction($no_afiliasi_receipt);
        $cek_payment_journal = $this->m_piutang_afiliasi->cek_payment_transaction_journal($no_afiliasi_receipt);

        if ($cek_payment) {

            /* =================================== get no payment afiliasi ==================================================== */
            $no_payment_afiliasi = $this->m_piutang_afiliasi->get_no_payment_afiliasi($no_afiliasi_receipt, $sess_branch);

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

            /* =================================== get no payment afiliasi ==================================================== */
            $no_payment_afiliasi = $this->m_piutang_afiliasi->get_no_payment_afiliasi_journal($no_afiliasi_receipt, $sess_branch);

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

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

            if ($check_period == false) {

                $this->trans_data['reverse_data']['data'] = $data_reversed;
                $this->trans_data['reverse_data']['link_number'] = trim($link_number);

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

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

                $this->trans_data = [];

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

                echo json_encode($result);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('reverse_in_period', 0);
                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');

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

        if ($id != "") {

            /* ===================== fungsi get link number ================================== */
            $link_number = $this->m_piutang_afiliasi->get_link_number($id);

            $data['list_transaksi'] = $this->m_piutang_afiliasi->get_detail_item_print($link_number, $BranchCode, '=');
            $data['list_receipt'] = $this->m_piutang_afiliasi->get_detail_item_print($link_number, $BranchCode, '!=');

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

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

}
