<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 01-09-2014	
 * 	Revisi 	: 
 */

/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 08-10-2014	
 * 	Revisi 	: 
 */
/*
  Revisi : Fachri

  Revisi : Daswan
 */

class Payment_afiliasi_journal extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 368;
    public $menu_model = 'm_payment_afiliasi_journal';
    public $name = 'Payment Afiliasi Journal';
    // 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 $trans_data = array();

    public function __construct() {
        parent::__construct();
        $this->load->model('m_menu');
        $this->load->model('m_payment_afiliasi_journal');
        $this->load->model('m_piutang_afiliasi');
        $this->load->model('m_account_journal');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('convert_date_helper');
        $this->load->helper('custom_string_helper');
        $this->load->model('login/m_login');
        $is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
        if($is_login){

        }else{
            $username       = $this->session->userdata('username');
            $session_id     = $this->session->userdata('session_id');
            $this->m_login->delete_session($username,$session_id);
            $this->session->sess_destroy();

            $uri_func = $this->uri->segment(3);
            if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
                redirect(base_url() . 'login', 'refresh');
            }else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
                $result['status']   = 'session';
                $result['message']  = get_notification('session_destroy',0);
                echo json_encode($result);
                die();
            }
        }
    }

    // Function Index	
    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    $group_menu = $this->session->userdata('group_menu');
                    $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/payment_afiliasi_journal/v_paymentafiliasi_journal', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax() {

        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $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_branch', 'am_branch.BranchCode = at_afiliasiinstallment_journal.BranchCode', 'INNER');
        $this->db->join('am_company as FromCompany', 'FromCompany.CompanyCode = at_afiliasiinstallment_journal.CompTransCode', 'INNER');
        $this->db->join('am_company as ToCompany', 'ToCompany.CompanyCode = at_afiliasiinstallment_journal.CompRecpCode', 'INNER');
        $this->db->join('am_accountgl as GLBankFrom', 'GLBankFrom.AccountNumber = at_afiliasiinstallment_journal.BankTransfer', 'INNER');
        $this->db->join('am_employee', 'at_afiliasiinstallment_journal.CreatedBy=am_employee.EmployeeCode', 'LEFT');
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        if ($BranchCode != "") {
            $this->db->where('at_afiliasiinstallment_journal.BranchCode', $BranchCode);
        } else {
            $this->db->where('at_afiliasiinstallment_journal.BranchCode', $this->session->userdata('branch'));
        }

        /* ===================================find by trasnfer from dan transfer to========================================================= */
        // if($CompanyNameFrom != ''){ $this->db->like('FromCompany.CompanyName', $CompanyNameFrom); }
        // if($CompanyNameTo != ''){ $this->db->like('ToCompany.CompanyName', $CompanyNameTo); }
        /* =============================================end=================================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('at_afiliasiinstallment_journal.TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('at_afiliasiinstallment_journal.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }


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

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

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

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

            $hasil[] = array(
                'CompTransCode' => $result[$i]->CompTransCode,
                'CompTransName' => $result[$i]->CompTransName,
                'CompRecptName' => $result[$i]->CompRecptName,
                'TransNumber' => $result[$i]->AInjNumber,
                'ADebtNumber' => $result[$i]->ADebtNumber,
                'AInsDate' => $result[$i]->AInjDate,
                'AInjDate' => $result[$i]->AInjDate,
                'APayAmount' => $result[$i]->APayAmount,
                'APayDesc' => $result[$i]->APayDesc,
                'LinkNumber' => $result[$i]->LinkNumber,
                'TransStatus' => $TransStatus,
                'BranchName' => $result[$i]->BranchName,
                'BankFrom' => $result[$i]->BankFrom,
                'CreatedBy' => $result[$i]->Created
            );
        }

        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
    }

    public function get_payment_afiliasi_number() {
        $preg_date = $this->input->post('Payment_af_date') == '' ? date('d-m-Y') : $this->input->post('Payment_af_date');
        $payment_af_number = $this->m_payment_afiliasi_journal->create_payment_afiliasi_number($preg_date);

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

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

    function get_company($comp_code) {
        $result = $this->m_payment_afiliasi_journal->get_company_bycompanycode($comp_code);

        echo json_encode($result);
    }

    function get_bank($comp_code) {
        $result = $this->m_payment_afiliasi_journal->get_bank_bycompany($comp_code);
        echo json_encode($result);
    }

    //function get last status
    function get_status_transaki() {
        $trans_number = $this->input->post('number');
        $get_number = $this->m_payment_afiliasi_journal->get_all_by_no($trans_number);

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

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

    public function list_piutangafiliasi() {
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');

        $total_piutang = 0;
        $amount_piutang = 0;
        $hasil = "";
        $result = $this->m_payment_afiliasi_journal->list_piutangafiliasi($sess_company, $sess_branch, $sess_branch_status);
        //echo $this->db->last_query();
        foreach ($result as $row) {
            $amount_piutang = $row->ADebtAmount;
            $journal_voucher_balance = $row->JVoucherBalance;
            $check_payment_to_piutang_no = $this->m_payment_afiliasi_journal->check_payment_to_piutang_no($row->ADebtNumber, $sess_branch);

            if (!empty($check_payment_to_piutang_no)) {
                $total_payment = $check_payment_to_piutang_no->total_payment;
                $BalanceAmount = $amount_piutang - ($total_payment + $journal_voucher_balance);
            } else {
                $BalanceAmount = 0;
            }

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

            $hasil[] = array(
                'BalanceAmount' => $BalanceAmount,
                'ADebtAmount' => $row->ADebtAmount,
                'CompFrom' => $row->CompFrom,
                'BankFrom' => $row->BankFrom,
                'CompTo' => $row->CompTo,
                'BankTo' => $row->BankTo,
                'ADebtNumber' => $row->ADebtNumber,
                'CompFromCode' => $row->CompFromCode,
                'CompToCode' => $row->CompToCode,
                'BankFromCode' => $row->BankFromCode,
                'BankToCode' => $row->BankToCode,
                'ChequeNumber' => $row->ChequeNumber,
                'IsLock' => $IsLock,
                'CqTermStatus' => $row->CqTermStatus,
                'ADebtDesc' => $row->ADebtDesc
            );
        }
        if (!empty($hasil)) {
            echo json_encode($hasil);
        } else {
            $emptyVar = array($hasil);
            echo json_encode($emptyVar);
        }
    }

    //function datafrid from piutang afiliasi
    function grid_bypiutang_no() {
        $piutang_no = $this->uri->segment(4);
        $piutang1 = str_replace('.', '/', $piutang_no);
        $piutang2 = str_replace('.', '/', $piutang1);
        $result = $this->m_payment_afiliasi_journal->get_by_piutang($piutang2);
        echo json_encode($result);
    }

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

                    $data['payment_afiliasi_number'] = $this->m_payment_afiliasi_journal->create_payment_afiliasi_number(date('d-m-Y'), $this->session->userdata('branch'));
                    $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/payment_afiliasi_journal/v_new_paymentafiliasi_journal', $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 insert_group_comp_piutang($BrchCodeCompFrom, $txt_payment_afiliasi_date, $payment_afiliasi_no_from, $txt_payment_for, $cmb_fromcompany, $loss_account, $cmb_tocompany, $txa_memo, $payment_amount, $link_number) {

        $data = array(
            'BranchCode' => $BrchCodeCompFrom,
            'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
            'AInjNumber' => $payment_afiliasi_no_from,
            'ADebtNumber' => $txt_payment_for,
            'CompTransCode' => $cmb_fromcompany,
            'BankTransfer' => $loss_account,
            'CompRecpCode' => $cmb_tocompany,
            'APayDesc' => $txa_memo,
            'APayAmount' => $payment_amount,
            'Payment_Type' => 1,
            'TransStatus' => 5,
            'CreditStatus' => 1,
            'LinkNumber' => $link_number,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata("username")
        );

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

    public function insert_group_comp_hutang($BrchCodeCompTo, $txt_payment_afiliasi_date, $payment_afiliasi_no_to, $txt_payment_for, $cmb_fromcompany, $loss_account, $cmb_tocompany, $txa_memo, $payment_amount, $link_number) {
        $data = array(
            'BranchCode' => $BrchCodeCompTo,
            'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
            'AInjNumber' => $payment_afiliasi_no_to,
            'ADebtNumber' => $txt_payment_for,
            'CompTransCode' => $cmb_fromcompany,
            'BankTransfer' => $loss_account,
            'CompRecpCode' => $cmb_tocompany,
            'APayDesc' => $txa_memo,
            'APayAmount' => $payment_amount,
            'Payment_Type' => 1,
            'TransStatus' => 5,
            'CreditStatus' => 0,
            'LinkNumber' => $link_number,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $this->session->userdata("username")
        );

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

    public function insert_detail($payment_afiliasi_no_from, $detail) {
        foreach ($detail as $row) {

            $currency_code = $this->m_account_journal->get_currency_code('', $row->GainAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GainAccount, $currency_code->CurrencyCode, '1');
            if ($acc_number == false) {
                $this->trans_rollback('journal', 'Gain Account', '');
            }

            $detail_data = array(
                'AInjNumber' => $payment_afiliasi_no_from,
                'AInjAccountNumber' => $acc_number->AccountNumber,
                'AInjAmount' => $row->PaymentAmount,
                'AInjMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

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

    public function trans_rollback($modus, $AccounName, $Currency) {
        //$this->db->trans_rollback();
        $result['status'] = false;

        if ($modus == 'approval') {
            $result['message'] = get_notification($modus, 0);
        } else {
            $result['message'] = get_notification_preference($modus, 0, $AccounName, $Currency);
        }

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

    public function insert_journal($detail, $txt_payment_afiliasi_date, $payment_afiliasi_no_from, $account_piutang_afiliasi, $loss_account, $payment_afiliasi_no_to, $account_hutang_afiliasi, $payment_amount, $txa_memo, $link_number) {

        /* ========================= insert journal loss / rugi =========================== */
        $acc_type = $this->m_account_journal->m_get_account_type($loss_account);
        $debet_kredit = $this->m_account_journal->debet_kredit_profit_loss($acc_type->Type_Name, $acc_type->Sub_Type_Name);

        $data_journal_loss_account = array(
            'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
            'AInjNumber' => $payment_afiliasi_no_from,
            'AInjAccountNumber' => $loss_account,
            'AInjSaldoDebet' => $payment_amount,
            'AInjSaldoCredit' => 0,
            'AmountCurrency' => $payment_amount,
            'AInjDesc' => $txa_memo,
            'AInjSignStatus' => ($debet_kredit['plus'] == 'Debet') ? 0 : 1,
            'LinkNumber' => $link_number,
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['insert_journal']['data'][] = $data_journal_loss_account;
        /* ========================== end insert journal loss / rugi ======================== */

        foreach ($detail as $row) {
            /* ============================== journal credit revenue ============================= */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GainAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GainAccount, $currency_code->CurrencyCode, '1');
            if ($acc_number == false) {
                $this->trans_rollback('journal', 'Gain Account', '');
            }

            $acc_type = $this->m_account_journal->m_get_account_type($acc_number->AccountNumber);
            $debet_kredit = $this->m_account_journal->debet_kredit_profit_loss($acc_type->Type_Name, $acc_type->Sub_Type_Name);

            $data_credit_revenue = array(
                'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
                'AInjNumber' => $payment_afiliasi_no_to,
                'AInjAccountNumber' => $acc_number->AccountNumber,
                'AInjSaldoDebet' => 0,
                'AInjSaldoCredit' => $row->PaymentAmount,
                'AmountCurrency' => $row->PaymentAmount,
                'AInjDesc' => $row->Memo,
                'AInjSignStatus' => ($debet_kredit['plus'] == 'Debet') ? 1 : 0,
                'LinkNumber' => $link_number,
                'LastUser' => $this->session->userdata("username")
            );

            $this->trans_data['insert_journal']['data'][] = $data_credit_revenue;
            /* ============================== end journal credit piutang ========================== */
        }

        /* ======================= insert journal debet hutang ============================ */
        $data_journal_transfer_debet = array(
            'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
            'AInjNumber' => $payment_afiliasi_no_to,
            'AInjAccountNumber' => $account_hutang_afiliasi,
            'AInjSaldoDebet' => $payment_amount,
            'AInjSaldoCredit' => 0,
            'AmountCurrency' => $payment_amount,
            'AInjDesc' => $txa_memo,
            'AInjSignStatus' => 1,
            'LinkNumber' => $link_number,
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['insert_journal']['data'][] = $data_journal_transfer_debet;
        /* ======================== end insert journal debet hutang ======================== */

        /* ============================== journal credit piutang ============================= */
        $data_credit_piutang = array(
            'AInjDate' => date('Y-m-d', strtotime($txt_payment_afiliasi_date)),
            'AInjNumber' => $payment_afiliasi_no_from,
            'AInjAccountNumber' => $account_piutang_afiliasi,
            'AInjSaldoDebet' => 0,
            'AInjSaldoCredit' => $payment_amount,
            'AmountCurrency' => $payment_amount,
            'AInjDesc' => $txa_memo,
            'AInjSignStatus' => 1,
            'LinkNumber' => $link_number,
            'LastUser' => $this->session->userdata("username")
        );

        $this->trans_data['insert_journal']['data'][] = $data_credit_piutang;
        /* ============================== end journal credit piutang ========================== */
    }

    public function insert() {

        $txt_payment_for = $this->input->post('txt_payment_for');
        $txt_payment_afiliasi_date = $this->input->post('txt_payment_afiliasi_date');

        /* ================ company yang kasih hutang =============================== */
        $cmb_fromcompany = $this->input->post('comp_from');
        $loss_account = $this->input->post('loss_account');
        $BrchCodeCompFrom = $this->session->userdata('branch');

        /* ================ company yang mau bayar ==================================== */
        $cmb_tocompany = $this->input->post('comp_to');
        $BrchCodeCompTo = $this->m_payment_afiliasi_journal->branch_code_comp_to($cmb_tocompany);

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

        /* ================== amount payment ========================== */
        $payment_amount = $this->input->post('txt_amount');

        /* =================== loan amount ============================= */
        $loan_amount = $this->input->post('loan_amount');

        /* ================== detail transaction from datagrid ======================= */
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

        $arr_company = array($cmb_fromcompany, $cmb_tocompany);
        $arr_branch = array($BrchCodeCompFrom, $BrchCodeCompTo);
        $arr_type_afiliasi = array('PaymentAfiliasi', 'ReceiptAfiliasi');

        /* ===================================== Fungsi create afiliasi no ============================== */
        $payment_afiliasi_no_from = $this->m_payment_afiliasi_journal->create_payment_afiliasi_number($txt_payment_afiliasi_date, $BrchCodeCompFrom);
        $payment_afiliasi_no_to = $this->m_payment_afiliasi_journal->create_payment_afiliasi_number($txt_payment_afiliasi_date, $BrchCodeCompTo);

        /* ========================= get link number piutang afiliasi ======================================== */
        $link_number_piutang = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);

        $data_islock_status = array(
            'AdebtIsLock' => 1
        );

        $link_number = $payment_afiliasi_no_from;

        /* =================================== get Account Number Payment Afiliasi ======================================== */
        $cek_sys_otheraccount_paymen_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_afiliasi($arr_company, $arr_branch, $arr_type_afiliasi);

        /* ==================================== get account hutang payment afiliasi ==================================================== */
        $account_hutang_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_payment_receipt_afiliasi($cmb_fromcompany, $BrchCodeCompFrom, 'PaymentAfiliasi');

        /* ==================================== get account piutang payment afiliasi ==================================================== */
        $account_piutang_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_payment_receipt_afiliasi($cmb_tocompany, $BrchCodeCompTo, 'ReceiptAfiliasi');

        if (count($cek_sys_otheraccount_paymen_afiliasi) < 8) {
            $result['status'] = false;
            $result['message'] = get_notification('preference', 0);
            echo json_encode($result);
        } else {

            /* ======================================================== Fungsi Insert group payment ===================================================== */
            $this->insert_group_comp_piutang($BrchCodeCompFrom, $txt_payment_afiliasi_date, $payment_afiliasi_no_from, $txt_payment_for, $cmb_fromcompany, $loss_account, $cmb_tocompany, $txa_memo, $payment_amount, $link_number);

            /* ======================================================== Fungsi Insert group receipt ===================================================== */
            $this->insert_group_comp_hutang($BrchCodeCompTo, $txt_payment_afiliasi_date, $payment_afiliasi_no_to, $txt_payment_for, $cmb_fromcompany, $loss_account, $cmb_tocompany, $txa_memo, $payment_amount, $link_number);

            /* ============================================== update piutang afiliasi to lock ================================== */
            $this->trans_data['islock_status']['data'] = $data_islock_status;
            $this->trans_data['islock_status']['link_number'] = $link_number_piutang;

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

            /* ============================================ insert journal======================================================================== */
            $this->insert_journal($detail, $txt_payment_afiliasi_date, $payment_afiliasi_no_from, $account_piutang_afiliasi, $loss_account, $payment_afiliasi_no_to, $account_hutang_afiliasi, $payment_amount, $txa_memo, $link_number);

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

            $this->trans_data = [];

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

            echo json_encode($result);
        }
    }

    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);
                    $pay_afil_numb = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());

                    $data['row'] = $this->m_payment_afiliasi_journal->get_payment($pay_afil_numb);

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

    public function update_group($loss_account, $txa_memo, $payment_amount, $link_number) {
        $data_group = array(
            'BankTransfer' => $loss_account,
            'APayDesc' => $txa_memo,
            'APayAmount' => $payment_amount,
            'LastUser' => $this->session->userdata("username")
        );

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

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

            $currency_code = $this->m_account_journal->get_currency_code('', $row->GainAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GainAccount, $currency_code->CurrencyCode, '1');

            $detail_data = array(
                'AInjNumber' => $payment_afiliasi_no_from,
                'AInjAccountNumber' => $acc_number->AccountNumber,
                'AInjAmount' => $row->PaymentAmount,
                'AInjMemo' => $row->Memo,
                'LastUser' => $this->session->userdata('username')
            );

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

    function update() {
        $txt_payment_for = $this->input->post('txt_payment_for');
        $txt_payment_afiliasi_date = $this->input->post('txt_payment_afiliasi_date');

        /* ================ company yang kasih hutang =============================== */
        $cmb_fromcompany = trim($this->input->post('comp_from'));
        $loss_account = trim($this->input->post('loss_account'));
        $BrchCodeCompFrom = $this->session->userdata('branch');

        /* ================ company yang mau bayar ==================================== */
        $cmb_tocompany = trim($this->input->post('comp_to'));
        $BrchCodeCompTo = $this->m_payment_afiliasi_journal->branch_code_comp_to($cmb_tocompany);

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

        /* ================== amount payment ========================== */
        $payment_amount = $this->input->post('txt_amount');

        /* =================== loan amount ============================= */
        $loan_amount = $this->input->post('loan_amount');

        /* ================== detail transaction from datagrid ======================= */
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);

        $arr_company = array($cmb_fromcompany, $cmb_tocompany);
        $arr_branch = array($BrchCodeCompFrom, $BrchCodeCompTo);
        $arr_type_afiliasi = array('PaymentAfiliasi', 'ReceiptAfiliasi');


        /* ========================= get link number piutang afiliasi  & payment afiliasi no ======================================== */
        $link_number_piutang = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);
        $payment_afiliasi_no_from = $this->input->post('payment_afiliasi_no');
        $link_number = $payment_afiliasi_no_from;
        $payment_afiliasi_no_to = $this->m_payment_afiliasi_journal->get_payment_afiliasi_number($BrchCodeCompTo, $link_number);

        /* =================================== get Account Number Payment Afiliasi ======================================== */
        $cek_sys_otheraccount_paymen_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_afiliasi($arr_company, $arr_branch, $arr_type_afiliasi);

        /* ==================================== get account hutang payment afiliasi ==================================================== */
        $account_hutang_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_payment_receipt_afiliasi($cmb_fromcompany, $BrchCodeCompFrom, 'PaymentAfiliasi');

        /* ==================================== get account piutang payment afiliasi ==================================================== */
        $account_piutang_afiliasi = $this->m_payment_afiliasi_journal->get_sys_otheraccount_payment_receipt_afiliasi($cmb_tocompany, $BrchCodeCompTo, 'ReceiptAfiliasi');

        /* ================================= 8 adalah 4 total piutang dari company a dan b n 4 total hutang dari company a dan b ====================== */
        if (count($cek_sys_otheraccount_paymen_afiliasi) < 8) {
            $result['status'] = false;
            $result['message'] = get_notification('preference', 0);
            echo json_encode($result);
        } else {

            /* ======================================== Update Group ================================== */
            $this->update_group($loss_account, $txa_memo, $payment_amount, $link_number);

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

            foreach ($detail_id as $AInjDetailID) {
                $this->trans_data['delete_detail']['AInjDetailID'][] = $AInjDetailID;
            }

            /* ======================================= Update detail ================================== */
            $this->update_detail($detail, $payment_afiliasi_no_from);

            /* ============================== Delete Journal ================================= */
            $this->trans_data['delete_journal']['link_number'] = $link_number;

            /* ============================================ insert journal======================================================================== */
            $this->insert_journal($detail, $txt_payment_afiliasi_date, $payment_afiliasi_no_from, $account_piutang_afiliasi, $loss_account, $payment_afiliasi_no_to, $account_hutang_afiliasi, $payment_amount, $txa_memo, $link_number);

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

            $this->trans_data = [];

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

            echo json_encode($result);
        }
    }

    public function approved_dir() {

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

        /* ====================== link number = payment afiliasi user login ================= */
        $link_number = $this->input->post('payment_afiliasi_no');

        /* =========================== piutang number =========================== */
        $txt_payment_for = $this->input->post('txt_payment_for');
        $app_level2_status = 1;
        $app_level2_code = $this->session->userdata('username');
        $app_level2_date = date('Y-m-d');

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

        $data_piutang = array(
            'TransStatus' => 2,
            'AdebtIsLock' => 0
        );

        /* ================================== get link number from piutang afiliasi ================ */
        $link_number_piutang = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);

        /* ================================= piutang ============================================= */
        $piutang = $this->m_payment_afiliasi_journal->m_get_total_piutang($txt_payment_for);

        /* ================================= get total payment ========================================== */
        $total_payment = $this->m_payment_afiliasi_journal->m_get_total_payment($txt_payment_for, $branch);

        $cek_payment = $piutang['ADebtAmount'] - ($total_payment + $piutang['JVoucherBalance']);

        /* ================================== check status piutang afiliais =============================== */
        /* ================================== true = status 1, false = status bukan 1 =========================== */
        $check_status_piutang_afiliasi = $this->m_payment_afiliasi_journal->check_status_piutang_afiliasi($txt_payment_for);

        if ($check_status_piutang_afiliasi == false) {

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

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

            $this->trans_data['approve_data']['data'] = $data_approval;
            $this->trans_data['approve_data']['link_number'] = trim($link_number);

            $this->trans_data['update_piutang']['data'] = $data_piutang;
            $this->trans_data['update_piutang']['link_number'] = $link_number_piutang;

            $result_return = $this->m_payment_afiliasi_journal->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=================================== */
        $id = $this->input->post('id');
        $arr_id = explode(',', $id);

        /* ======================= link number pAYMENT afiliasi ============================== */
        $link_number = $arr_id[0];

        /* ============================== no piutang afiliasi =============================== */
        $txt_payment_for = $arr_id[1];

        $data_reversed_payment = array(
            'AppLevel2Status' => 0,
            'AppLevel2Code' => null,
            'AppLevel2Date' => 0,
            'TransStatus' => 5,
            'AppFinished' => 0,
        );

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


        /* ================================== get link number from piutang afiliasi ================ */
        $link_number_piutang = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);

        /* =============================== get max period ========================================= */
        //$max_period 			= $this->m_payment_afiliasi_journal->get_max_period($txt_payment_for);
        /* ============ LINK NUMBER = AInsNumber branch yang sedang login ============= */
        //$payment_period 		= $this->m_payment_afiliasi_journal->get_payment_period($link_number);

        /* ================================== payment number ======================================= */
        $no_payment = $this->m_payment_afiliasi_journal->get_payment_number($link_number);

        $arr_no = explode("/", $no_payment);
        $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;

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

        if ($check_period == false) {

            // if($payment_period == $max_period){

            $this->trans_data['reverse_payment']['data'] = $data_reversed_payment;
            $this->trans_data['reverse_payment']['link_number'] = trim($link_number);

            $this->trans_data['reverse_piutang']['data'] = $data_reversed_piutang;
            $this->trans_data['reverse_piutang']['link_number'] = trim($link_number_piutang);

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

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

            $this->trans_data = [];

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

            echo json_encode($result);

            // }else{
            // 	$result['status'] 	= false;
            // 	$result['message']	= get_notification('max_period',0);
            // }

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

    function detail_payment($AInjNumber) {

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

        $payment_detail = $this->m_payment_afiliasi_journal->get_payment_detail($AInjNumber);
        //echo $this->db->last_query();

        echo json_encode($payment_detail);
    }

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

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

        $get_link_number_suspend = $this->m_payment_afiliasi_journal->get_link_number_suspen($id);
        $txt_payment_for = $get_link_number_suspend->ADebtNumber;

        $cek_adeb_transstatus_2 = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);
        $link_number_adeb_2 = $cek_adeb_transstatus_2;

        $data_islock_status = array(
            'AdebtIsLock' => 0
        );

        $this->db->trans_begin();
        $hasil = $this->m_payment_afiliasi_journal->update_is_lock($data_islock_status, $link_number_adeb_2);
        if ($hasil == 0) {
            $this->proses_tutup();
        }

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

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

    public function suspend_data() {
        $AInjNumber     = $this->input->post('id');
        $hasil = 0;
        $link_number    = $this->m_payment_afiliasi_journal->get_link_numberafiliasijournal($AInjNumber);

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

        /* =========================== get number afiliasi piutang ================================= */
        $afiliasi_number_piutang    = $this->m_payment_afiliasi_journal->get_link_number_suspen($link_number);
        $txt_payment_for            = $afiliasi_number_piutang->ADebtNumber;

        /* =========================== get link number piutang afiliasi ============================= */
        $adeb_transstatus_2 = $this->m_payment_afiliasi_journal->cek_at_adebt_number($txt_payment_for);
        $link_number_adeb_2 = $adeb_transstatus_2;

        $data_islock_status = array(
            'AdebtIsLock' => 0
        );

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

        $this->trans_data['update_piutang']['data'] = $data_islock_status;
        $this->trans_data['update_piutang']['link_number'] = trim($link_number_adeb_2);

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    //Function view print data
    public function to_preview($obj_string = null) {
        $data['company'] = $this->m_payment_afiliasi_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list']		= $this->m_payment_afiliasi_journal->get_all_to_print($this->session->userdata('branch'));
        
        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['list']           = $this->m_payment_afiliasi_journal->get_all_to_print($data_filter);
                
        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/payment_afiliasi_journal/v_print_paymentafiliasi_journal', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_payment_afiliasi_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list']		= $this->m_payment_afiliasi_journal->get_all_to_print($this->session->userdata('branch'));
        $data_grid = str_replace('__', '/', $data_grid);
        $data_grid = str_replace('_', '-', $data_grid);
        $data_grid = str_replace('%20', ' ', $data_grid);
        $arr_grid_lv1 = explode('linebaru', $data_grid);

        $obj_string = '[';

        for ($x = 0; $x < count($arr_grid_lv1) - 1; $x++) {
            $arr_data_lv1 = $arr_grid_lv1[$x];
            $arr_grid_lv2 = explode('spasi', $arr_data_lv1);

            $obj_string .= '{';
            for ($i = 0; $i < count($arr_grid_lv2); $i++) {
                $arr_grid_lv3 = explode(':', $arr_grid_lv2[$i]);
                if ($i < count($arr_grid_lv2) - 1) {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '",';
                } else {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '"';
                }
            }

            if ($x < count($arr_grid_lv1) - 2) {
                $obj_string .= '},';
            } else {
                $obj_string .= '}';
            }
        }

        $obj_string .= ']';
        $data['list'] = json_decode($obj_string);

        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/payment_afiliasi_journal/v_print_paymentafiliasi_journal', $data);
        $this->load->view('v_footer');
    }

    //Function view print data by afiliasi number
    public function to_preview_by_payment_number() {
        //$id = $this->input->post('id');
        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $id = $uri4 . '/' . $uri5 . '/' . $uri6;

        $data['company'] = $this->m_payment_afiliasi_journal->get_company_by_branch($this->session->userdata('branch'));
        $data['list'] = $this->m_payment_afiliasi_journal->get_by_payment_number($id);
        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/payment_afiliasi_journal/v_print_paymentafiliasi_journal', $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);

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

        $company_from_n_to = $this->m_payment_afiliasi_journal->get_company_from_n_to($link_number);
        $data['company'] = $company_from_n_to;

        $data['branch_by_company_to'] = $this->m_payment_afiliasi_journal->branch_code_by_company_transfer($company_from_n_to->CompRecpCode);
        $data['branch_by_company_from'] = $this->m_payment_afiliasi_journal->branch_code_by_company_transfer($company_from_n_to->CompTransCode);

        $data['detail_journal'] = $this->m_payment_afiliasi_journal->detail_to_journal($link_number);

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

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

        if ($id != "") {

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

            $data['detail'] = $this->m_payment_afiliasi_journal->get_group_item_print_journal($link_number, $BranchCode);
            $data['list'] = $this->m_payment_afiliasi_journal->get_detail_item_print_journal($link_number, $BranchCode);

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

    function get_bank_balance() {
        $AccountNumber = $this->input->post('AccountNumber');
        $branch = $this->session->userdata('branch');

        $bank_balance = $this->m_account_journal->m_get_bank_balance($branch, $AccountNumber);

        if ($bank_balance == false) {
            $return = array('message' => false, 'value' => 0);
        } else {
            $return = array('message' => true, 'value' => $bank_balance);
        }

        echo json_encode($return);
    }

    function get_other_expense($comp_code) {
        $result = $this->m_payment_afiliasi_journal->m_get_other_expense($comp_code);
        echo json_encode($result);
    }

    function get_other_revenue($comp_code) {
        $result = $this->m_payment_afiliasi_journal->m_get_other_revenue($comp_code);
        echo json_encode($result);
    }

}
