<?php

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

/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 16-08-2014
 * 	Revisi 	: 
 */

class Vendors extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 120;
    public $menu_model = 'm_vendors';
    PUBLIC $name = 'Vendors';
    public $trans_data = array();
    public $arr_number = array('PI' => array(), 'JV' => array());
    // inisialisasi otomatis
    public $add = "add";
    public $edit = "edit";
    public $delete = "delete";
    public $to_preview = "to_preview";
    public $to_pdf = "to_pdf";
    public $to_excel = "to_excel";

    public function __construct() {
        parent::__construct();

        $this->load->model('m_vendors');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
        $this->load->model('m_purchase_invoice');
        $this->load->model('m_receive_item');
        $this->load->model('m_account_journal');
        $this->load->model('m_customer');
        $this->load->model('m_period_end');
		$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_id'] = $this->menu_id;

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

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

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

    function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');
		$status = array(0, 1);
        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* ===========================declar post by find================================================ */
        $Code = $this->input->post('VendorCode') ? $this->input->post('VendorCode') : '';
        $Name = $this->input->post('VendorName') ? $this->input->post('VendorName') : '';

        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        $BranchCode = $this->input->post('BranchCode') ? $this->input->post('BranchCode') : '';
		$CompanyCode = ($this->input->post('CompanyCode')) ? $this->input->post('CompanyCode') : '';
        $CurrencyCode = $this->input->post('CurrencyCode') ? $this->input->post('CurrencyCode') : '';
        /* ========================================end================================================== */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if============ */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
			$this->db->where('am_currency.CompanyCode', $CompanyCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
			$this->db->where('am_currency.CompanyCode', $sess_company);
        }

        if ($Code != "") {
            $this->db->like('am_vendor.VendorCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('am_vendor.VendorName', $Name);
        }
        
		if ($TransStatus != '') {
            $this->db->where_in('am_vendor.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('am_vendor.TransStatus', $status);
        }
		
        if ($CurrencyCode != "") {
            $this->db->where('CurrencyCode', $CurrencyCode);
        }
        /* ==========================end================================================================= */
		$this->db->join('am_currency', 'am_currency.CurrencyCode = am_vendor.CurrencyCode');
        $this->db->join('am_city', 'am_city.CityCode = am_vendor.VendorCity','left');
		$this->db->join('am_termspayment', 'am_termspayment.TermsPaymentID = am_vendor.TermsPaymentID');
        $count_data = $this->db->count_all_results('am_vendor');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_vendors->get_all();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            $TransStatus = get_status_master($result[$i]->Status);

            $hasil[] = array(
                'TransNumber' => $result[$i]->VendorCode,
                'VendorName' => $result[$i]->VendorName,
                'PhoneNumber' => str_replace(',','',$result[$i]->PhoneNumber),
                'ContactPerson' => $result[$i]->ContactPerson,
                'OutStanding' => $result[$i]->OutStanding,
                'CurrencyName' => $result[$i]->CurrencyName,
				'CityName' => $result[$i]->CityName,
				'TermDesc' => $result[$i]->TermDesc,
                'TransStatus' => $TransStatus
            );
        }

        if ($hasil == "") {
            $result = array();
            echo json_encode($result);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            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)
                     */
                    //ambil data dari session untuk 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);

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

                    $ceknourut = $this->m_vendors->get_last_vendor_code($sess_brach);

                    if (!empty($ceknourut) || $ceknourut != null) {
                        foreach ($ceknourut as $row) {
                            $number = $row->VendorCode;
                            $explode_number = explode("-", $number);
                            $last_index = (count($explode_number) - 1);
                            $last_number = $explode_number[$last_index];

                            if (empty($last_index)) {
                                $pay_numb3 = '001';
                            } else {
                                $pay_numb3 = $last_number + 1;
                            }
                        }

                        $count_recnumb = strlen($pay_numb3);

                        if ($count_recnumb == 1) {
                            $data['next_vendor_numb'] = '00' . $pay_numb3;
                        } elseif ($count_recnumb == 2) {
                            $data['next_vendor_numb'] = '0' . $pay_numb3;
                        } elseif ($count_recnumb == 3) {
                            $data['next_vendor_numb'] = $pay_numb3;
                        }

                        $data['branch_param1'] = $sess_brach;
                    } else {
                        $data['branch_param1'] = $sess_brach;
                        $data['next_vendor_numb'] = '001';
                    }

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

    public function insert() {
        $txt_vendorno = $this->input->post('txt_vendorno');
        $chk_suspend = $this->input->post('chk_suspend');
        $txt_vendorname = $this->input->post('txt_vendorname');
        $txt_address1 = $this->input->post('txt_address');
        $txt_addressdetail = $this->input->post('txt_addressdetail');
        $txt_address = "$txt_address1 $txt_addressdetail";
        $txt_taxaddress1 = $this->input->post('txt_taxaddress');
        $txt_taxaddressdetail = $this->input->post('txt_taxaddressdetail');
        $txt_taxaddress = "$txt_taxaddress1 $txt_taxaddressdetail";
        $cmb_city = $this->input->post('cmb_city');
        $cmb_state = $this->input->post('cmb_state');
        $txt_zipcode = $this->input->post('txt_zipcode');
        $cmb_country = $this->input->post('cmb_country');
        $txt_phone = $this->input->post('txt_phone');
        $txt_fax = $this->input->post('txt_fax');
        $txt_kategori = $this->input->post('txt_kategori');
        $txt_group = $this->input->post('txt_group');
        $txt_contactperson = $this->input->post('txt_contactperson');
        $txt_email = $this->input->post('txt_email');
        $txt_outstanding_hidden = $this->input->post('txt_outstanding_hidden');
        $txt_webpage = $this->input->post('txt_webpage');
        $cmb_terms = $this->input->post('cmb_terms');
        $cmb_currency = $this->input->post('cmb_currency');
        $txt_termsdefaultdesctiption = $this->input->post('txt_termsdefaultdesctiption');
        $cmb_tax1 = $this->input->post('cmb_tax1');
        $cmb_tax2 = $this->input->post('cmb_tax2');
        $chk_termsdefaultinvoice = $this->input->post('chk_termsdefaultinvoice');
        $txt_termsvendortaxno = $this->input->post('txt_termsvendortaxno');
        $txt_termspkpno = $this->input->post('txt_termspkpno');
        $txt_vendor_balance = $this->input->post('txt_vendor_balance');
        $cmb_taxtype = $this->input->post('cmb_taxtype');
        $txa_notes = $this->input->post('txa_notes');
        $hasil = 0;

        if ($this->m_vendors->check_code_exist($txt_vendorno) == TRUE) {
            $result['status'] = false;
            $result['message'] = 'Vendor Code telah digunakan';
            echo json_encode($result);
            die();
        }

        if ($cmb_tax2 != "") {
            if ($this->m_customer->check_code_exist_taxes($cmb_tax2) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax 2 ' . $cmb_tax2 . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }

        if ($cmb_taxtype != "") {
            if ($this->m_customer->check_code_exist_tax_type($cmb_taxtype) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax type ' . $cmb_taxtype . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }

        if ($this->m_customer->check_code_exist_city($cmb_city) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf nama city ' . $cmb_city . ' belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        }


        if ($this->m_customer->check_code_exist_term($cmb_terms) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf terms belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($this->m_customer->check_code_exist_currency($cmb_currency) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf Currency belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($cmb_tax1 != "") {
            if ($this->m_customer->check_code_exist_taxes($cmb_tax1) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax 1 ' . $cmb_tax1 . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }
        //else {
        $data = array(
            'BranchCode' => $this->session->userdata('branch'),
            'VendorCode' => strtoupper($txt_vendorno),
            'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 0,
            'VendorName' => strtoupper($txt_vendorname).' '.$cmb_currency,
            'VendorAddress' => $txt_address,
            'VendorTaxAddress' => $txt_taxaddress,
            'VendorCity' => $cmb_city,
            'VendorState' => $cmb_state,
            'VendorPostalCode' => $txt_zipcode,
            'VendorCountry' => $cmb_country,
            'PhoneNumber' => $txt_phone,
            'FacsimileNumber' => $txt_fax,
            'VendorCategory' => $txt_kategori,
            'VendorGroup' => $txt_group,
            'ContactPerson' => $txt_contactperson,
            'EmailAddress' => $txt_email,
            'WebAddress' => $txt_webpage,
            'TermsPaymentID' => $cmb_terms,
            'CurrencyCode' => $cmb_currency,
            'Tax1Code' => ($cmb_tax1 == '') ? null : $cmb_tax1,
            'Tax2Code' => ($cmb_tax2 == '') ? null : $cmb_tax2,
            'TaxIncludedStatus' => ($chk_termsdefaultinvoice == 1) ? $chk_termsdefaultinvoice : 0,
            'VendorTaxNumber' => $txt_termsvendortaxno,
            'PKPNumber' => $txt_termspkpno,
            'TaxTypeID' => ($cmb_taxtype == '') ? null : $cmb_taxtype,
            'VendorDesc' => $txt_termsdefaultdesctiption,
            'VendorNotes' => $txa_notes,
            'TransStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$hasil = $this->m_vendors->insert($data);
        $this->trans_data['insert_group']['data'] = $data;

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

        $this->trans_data = [];

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

        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)
                     */
                    //ambil data dari session untuk 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);

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

                    $data['row'] = $this->m_vendors->get_by_id($vendor_code);
					
					$VendorName = implode(' ', explode(' ', $data['row']->VendorName, -1)); 
					
					$data['VendorName'] = $VendorName;
					
                    $this->load->view('v_header');
                    $this->load->view('vendors/v_edit_vendors', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

        $txt_vendorno = $this->input->post('txt_vendorno');
        $chk_suspend = $this->input->post('chk_suspend');
        $txt_vendorname = $this->input->post('txt_vendorname');
        $txt_address1 = $this->input->post('txt_address');
        $txt_addressdetail = $this->input->post('txt_addressdetail');
        $txt_address = "$txt_address1 $txt_addressdetail";
        $txt_taxaddress1 = $this->input->post('txt_taxaddress');
        $txt_taxaddressdetail = $this->input->post('txt_taxaddressdetail');
        $txt_taxaddress = "$txt_taxaddress1 $txt_taxaddressdetail";
        $cmb_city = $this->input->post('cmb_city');
        $cmb_state = $this->input->post('cmb_state');
        $txt_zipcode = $this->input->post('txt_zipcode');
        $cmb_country = $this->input->post('cmb_country');
        $txt_phone = $this->input->post('txt_phone');
        $txt_fax = $this->input->post('txt_fax');
        $txt_kategori = $this->input->post('txt_kategori');
        $txt_group = $this->input->post('txt_group');
        $txt_contactperson = $this->input->post('txt_contactperson');
        $txt_email = $this->input->post('txt_email');
        $txt_webpage = $this->input->post('txt_webpage');
        $cmb_terms = $this->input->post('cmb_terms');
        $cmb_currency = $this->input->post('cmb_currency');
        $txt_termsdefaultdesctiption = $this->input->post('txt_termsdefaultdesctiption');
        $cmb_tax1 = $this->input->post('cmb_tax1');
        $cmb_tax2 = $this->input->post('cmb_tax2');
        $txt_outstanding_hidden = $this->input->post('txt_outstanding_hidden');
        $chk_termsdefaultinvoice = $this->input->post('chk_termsdefaultinvoice');
        $txt_termsvendortaxno = $this->input->post('txt_termsvendortaxno');
        $txt_termspkpno = $this->input->post('txt_termspkpno');
        $cmb_taxtype = $this->input->post('cmb_tax_type');
        $txa_notes = $this->input->post('txa_notes');
        $detail = $this->input->post('detail');
        $klik = $this->input->post('id_klik');
        $branchCode = $this->session->userdata('branch');
        $txt_vendor_balance = $this->input->post('txt_vendor_balance');
        $konversi = $this->input->post('konversi');
        $rate_data = $this->input->post('rate_data');
        $rd_vendor_type = $this->input->post('rd_vendor_type');

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

        if ($cmb_tax2 != "") {
            if ($this->m_customer->check_code_exist_taxes($cmb_tax2) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax 2 ' . $cmb_tax2 . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }

        if ($cmb_taxtype != "") {
            if ($this->m_customer->check_code_exist_tax_type($cmb_taxtype) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax type ' . $cmb_taxtype . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }

        if ($this->m_customer->check_code_exist_city($cmb_city) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf nama city ' . $cmb_city . ' belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        }


        if ($this->m_customer->check_code_exist_term($cmb_terms) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf terms belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($this->m_customer->check_code_exist_currency($cmb_currency) == FALSE) {
            $result['status'] = false;
            $result['message'] = 'Maaf Currency belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($cmb_tax1 != "") {
            if ($this->m_customer->check_code_exist_taxes($cmb_tax1) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf tax 1 ' . $cmb_tax1 . ' belum terdaftar, silahkan cek kembali';
                echo json_encode($result);
                die();
            }
        }
			
        $data = array(
            'VendorCode' => strtoupper($txt_vendorno),
            'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 0,
            'VendorName' => strtoupper($txt_vendorname).' '.$cmb_currency,
            'VendorAddress' => $txt_address,
            'VendorTaxAddress' => $txt_taxaddress,
            'VendorCity' => $cmb_city,
            'VendorState' => $cmb_state,
            'VendorPostalCode' => $txt_zipcode,
            'VendorCountry' => $cmb_country,
            'PhoneNumber' => $txt_phone,
            'FacsimileNumber' => $txt_fax,
            'VendorCategory' => $txt_kategori,
            'VendorGroup' => $txt_group,
            'ContactPerson' => $txt_contactperson,
            'EmailAddress' => $txt_email,
            'WebAddress' => $txt_webpage,
            'TermsPaymentID' => $cmb_terms,
            'CurrencyCode' => $cmb_currency,
            'Tax1Code' => ($cmb_tax1 == '') ? null : $cmb_tax1,
            'Tax2Code' => ($cmb_tax2 == '') ? null : $cmb_tax2,
            'TaxIncludedStatus' => $chk_termsdefaultinvoice,
            'VendorTaxNumber' => $txt_termsvendortaxno,
            'PKPNumber' => $txt_termspkpno,
            'TaxTypeID' => ($cmb_taxtype == '') ? null : $cmb_taxtype,
            'VendorDesc' => $txt_termsdefaultdesctiption,
            'VendorNotes' => $txa_notes,
            'OutStanding' => $txt_vendor_balance,
            'VendorStatus' => $rd_vendor_type,
            'TransStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_vendors->update($data, $id, $this->session->userdata('branch'));
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $id;
        $this->trans_data['update_group']['branch'] = $this->session->userdata('branch');

        $this->trans_data['detail_pi']['total'] = 0;

        if ($klik == 1) {
            $detail = json_decode($detail);
            $no_pi_2 = "";
            $ind_arr = 0;

            if ($detail) {
                foreach ($detail as $row) {
                    $no_pi = $row->OldPInvNumber;

                    $OutStanding = $row->OutStanding;
                    $PInvDate = $row->PInvDate;
                    $term = $this->m_vendors->get_terms_by_row($cmb_terms);
                    $term_waktu = $term->NetDueIn;
                    $pecah = explode('-', $PInvDate);
                    $tahun = $pecah[2];
                    $bulan = $pecah[1];
                    $tanggal = $pecah[0];
                    $nextN = mktime(0, 0, 0, $bulan, $tanggal + $term_waktu, $tahun);
                    $tgl_tempo = date('Y-m-d', $nextN);
                    $Item_code = "ITM-MGRS";

                    if (count($this->arr_number['PI']) < 1) {
                        $Purchase_number = $this->m_purchase_invoice->create_pi_number();
                        array_push($this->arr_number['PI'], $Purchase_number);
                    } else {
                        $index_number = count($this->arr_number['PI']) - 1;
                        $pi_number_before = $this->arr_number['PI'][$index_number];
                        $arr_no = explode("/", $pi_number_before);
                        $no_explode = $arr_no[2];
                        $ordinal_number = sprintf("%03s", (int) $no_explode + 1);
                        $Purchase_number = $arr_no[0] . '/' . $arr_no[1] . '/' . $ordinal_number;

                        array_push($this->arr_number['PI'], $Purchase_number);
                    }

                    if ($cmb_currency == "IDR") {
                        $CurrencyRate = 1;
                    } else {
                        $CurrencyRate = $row->Rate;
                    }

                    $get_inventori = $this->m_vendors->get_inventories($Item_code);

                    if ($get_inventori == false) {
                        $this->db->trans_rollback();
                        $result['status'] = false;
                        $result['message'] = "Maaf item dengan kode " . $Item_code . " Belum Tersedia Di Inventori";

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

                    $item_inventori = $get_inventori->ItemCode;
                    $item_kategori = $get_inventori->ItemCategoryID;

                    $data_purchase_invoice = array(
                        'BranchCode' => $this->session->userdata('branch'),
                        'VendorCode' => strtoupper($txt_vendorno),
                        'PInvNumber' => $Purchase_number,
                        'PRecNumber' => $Purchase_number,
                        'VendorAddress' => $txt_address,
                        'PInvDate' => date('Y-m-d'),
                        'PRecDate' => date('Y-m-d'),
                        'PInvDueDate' => $tgl_tempo,
                        //'FiscalRate' 		=> $tgl_tempo,
                        'CurrencyRate' => $CurrencyRate,
                        'CurrencyCode' => $cmb_currency,
                        'ImportStatus' => 1,
                        'TransStatus' => 1,
						'FOBID' => 1,
                        'TermsPaymentID' => $cmb_terms,
                        'ShipmentDate' => date("Y-m-d", strtotime($PInvDate)),
                        'ShipmentID' => 1,
                        'AppLevel1Status' => 1,
                        'PInvDesc' => "Item Migrasi Database, Tgl Invoice ".$PInvDate."",
                        'OldPInvNumber' => $no_pi,
                        'AppLevel1Code' => $this->session->userdata("username"),
                        'AppLevel1Date' => date('Y-m-d'),
                        'AppLevel2Status' => 1,
                        'AppLevel2Code' => $this->session->userdata("username"),
                        'AppLevel2Date' => date('Y-m-d'),
                        'CreatedBy' => $this->session->userdata("username"),
                        'CreatedAt' => date('Y-m-d'),
                        'LastUser' => $this->session->userdata("username")
                    );

                    $data_detail_pi = array(
                        'PRecNumber' => $Purchase_number,
                        'PInvNumber' => $Purchase_number,
                        'ItemCode' => $item_inventori,
                        'ItemDesc' => 'Item Migrasi Database',
                        'ItemQty' => 1,
                        'ItemCategoryID' => $item_kategori,
                        'ItemUnit' => 'Unit',
                        'ItemPrice' => $OutStanding,
                        'ItemAmount' => $OutStanding,
                        'ItemTotalAmount' => $OutStanding,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $data_payment = array(
                        'BranchCode' => $this->session->userdata('branch'),
                        'VendorCode' => strtoupper($txt_vendorno),
                        'InvoiceNumber' => $Purchase_number,
                        'InvoiceDate' => date('Y-m-d'),
                        'InvoiceCurrCode' => $cmb_currency,
                        'InvoiceCurrRate' => $CurrencyRate,
                        'InvoiceFiscalRate' => 1,
                        'InvoiceTotalDP' => 0,
                        'ItemCategoryID' => $item_kategori,
                        'ItemCategoryCode' => $item_kategori,
                        'ItemStatus' => 0,
                        'InvoiceType' => 0,
                        'PPnFiscalStatus' => 0,
                        'LastUser' => $this->session->userdata("username")
                    );

                    if ($no_pi_2 != $no_pi) {
                        $this->trans_data['detail_pi']['total'] += 1;

                        //$this->m_vendors->insert_purchase_invoice($data_purchase_invoice);
                        //$this->m_vendors->insert_detail($data_detail_pi);
                        //$this->m_purchase_invoice->insert_payment($data_payment); 
                        $this->trans_data['insert_purchase_invoice']['data'][] = $data_purchase_invoice;
                        $this->trans_data['insert_detail']['data'][] = $data_detail_pi;
                        $this->trans_data['insert_payment']['data'][] = $data_payment;
                    }
                    $no_pi_2 = $no_pi;

                    $OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
                    if ($OpeningBalance == false) {
                        $this->trans_rollback('journal', 'Opening Balance', '');
                    }

                    $opening_journal = $cmb_currency == 'IDR' ? $OutStanding : $OutStanding * $CurrencyRate;
                    $opening_currency = $OutStanding;

                    $journal_unbilled = array(
                        'PInvDate' => date('Y-m-d'),
                        'PInvNumber' => $Purchase_number,
                        'PInvDesc' => "Migrasi",
                        'PInvAccountNumber' => $OpeningBalance->AccountNumber,
                        'PInvSaldoDebet' => $opening_journal,
                        'PInvSaldoCredit' => 0,
                        'AmountCurrency' => $opening_currency,
                        'PInvSignStatus' => 1,
                        'ItemCategoryCode' => $item_kategori,
                        'LastUser' => $this->session->userdata("username")
                    );

                    //$this->m_purchase_invoice->insert_journal($journal_unbilled);
                    $this->trans_data['insert_journal'][$ind_arr]['data'][] = $journal_unbilled;

                    $PayableAccount = $this->m_account_journal->get_cat_purchase_account('Payable', $item_kategori, $cmb_currency); // Hutang Dagang
                    if ($PayableAccount == false) {
                        $this->trans_rollback('preference', 'Payable,Hutang Dagang', '');
                    }

                    $payable_value = $cmb_currency == 'IDR' ? $OutStanding : $OutStanding * $CurrencyRate;
                    $payable_currency = $OutStanding;

                    $journal_purchase = array(
                        'PInvDate' => date('Y-m-d'),
                        'PInvNumber' => $Purchase_number,
                        'PInvDesc' => "Migrasi",
                        'PInvAccountNumber' => $PayableAccount->AccountNumber,
                        'PInvSaldoDebet' => 0,
                        'PInvSaldoCredit' => $payable_value,
                        'AmountCurrency' => $payable_currency,
                        'PInvSignStatus' => 0,
                        'ItemCategoryCode' => $item_kategori,
                        'LastUser' => $this->session->userdata("username")
                    );

                    //$this->m_purchase_invoice->insert_journal($journal_purchase);
                    $this->trans_data['insert_journal'][$ind_arr]['data'][] = $journal_purchase;

                    @$CategoryAmount[$row->OldPInvNumber] += $OutStanding; // summing sub total balance
                    @$NewCategoryAmount[$Purchase_number] += $OutStanding; // summing sub total by invoicenumber

                    if ($cmb_currency == "IDR") {
                        @$ItemKategori[$row->OldPInvNumber] += $OutStanding;
                    } else {
                        @$ItemKategori[$row->OldPInvNumber] += $OutStanding *= $row->Rate;
                    }

                    $ind_arr++;
                }
            }

            foreach ($NewCategoryAmount as $key => $value) {
                $update_inv_payment = array(
                    'InvoicePurchase' => $value,
                    'InvoiceAmount' => $value,
                    'InvoiceOwing' => $value,
                    'ItemCategoryRatio' => 100,
                );
                //$this->m_purchase_invoice->update_payment($update_inv_payment, $key);
                $this->trans_data['update_payment']['data'][] = $update_inv_payment;
                $this->trans_data['update_payment']['key'][] = $key;
            }

            $no_pinv_2 = "";
            foreach ($CategoryAmount as $key => $value) {
                $data_update_total = array(
                    'PInvSubTotal' => $value,
                    'PInvTotalAmount' => $value,
                    'PInvTotalInvoice' => $value
                );
                //$this->m_vendors->update_purchase_invoice($data_update_total, $key, $branchCode);
                $this->trans_data['update_purchase_invoice']['data'][] = $data_update_total;
                $this->trans_data['update_purchase_invoice']['key'][] = $key;
                $this->trans_data['update_purchase_invoice']['branch'][] = $branchCode;
            }
        }

        if ($klik == 1) {
            foreach ($ItemKategori as $key_3 => $nilai) {

                $update_appfinis = array(
                    'AppFinished' => 1
                );

                //$hasil = $this->m_vendors->update_appfinis($update_appfinis, $key_3, $branchCode);
                $this->trans_data['update_appfinis']['data'][] = $update_appfinis;
                $this->trans_data['update_appfinis']['key'][] = $key_3;
                $this->trans_data['update_appfinis']['branch'][] = $branchCode;
            }
        }

        $ind_jv = 0;
        $this->trans_data['detail_dp']['total'] = count($detail_dp);

        foreach ($detail_dp as $row) {
            $OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
            $UangMuka = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $cmb_currency);

            if ($OpeningBalance == false) {
                $this->trans_rollback('journal', 'Opening Balance', '');
            }
            if ($UangMuka == false) {
                $this->trans_rollback('journal', 'Uang Muka Pembelian', '');
            }

            $Rate = doubleval($row->Rate);
            $NoTransaksi = $row->NoTransaksi;
            $JVAmount = doubleval($row->DownPayment);

            if (count($this->arr_number['JV']) < 1) {
                $JVchNumber = $this->m_period_end->create_jv_number(date('Y-m-d'), $this->session->userdata('branch'));
                array_push($this->arr_number['JV'], $JVchNumber);
            } else {
                $index_number = count($this->arr_number['JV']) - 1;
                $jv_number_before = $this->arr_number['JV'][$index_number];
                $arr_no = explode("/", $jv_number_before);
                $no_explode = $arr_no[2];
                $ordinal_number = sprintf("%03s", (int) $no_explode + 1);
                $JVchNumber = $arr_no[0] . '/' . $arr_no[1] . '/' . $ordinal_number;

                array_push($this->arr_number['JV'], $JVchNumber);
            }

            $data_po_detail_dp = array(
                'POrdNumber' => $JVchNumber,
                'VendorCode' => strtoupper($txt_vendorno),
                'PPayNumber' => $JVchNumber,
                'POrdTotalDP' => $JVAmount,
                'Owing' => 0,
                'PaymentAmount' => $JVAmount,
                'PaymentDate' => date('Y-m-d'),
                'PaymentBefore' => 0,
                'DPUsed' => 0,
                'CurrencyRate' => $Rate,
                'SaldoDPBalance' => $JVAmount,
                'DPUsedBook' => 0,
                'IsEdit' => 0,
                'SOrdStatus' => 1,
                'StatusDPFor' => 1,
                'JVoucherBalance' => 0,
                'LastUser' => $this->session->userdata('username')
            );

            $this->trans_data['insert_pord_detail_dp']['data'][] = $data_po_detail_dp;

            $data_group_jv = array(
                'BranchCode' => $this->session->userdata('branch'),
                'JVchDate' => date('Y-m-d'),
                'JVchNumber' => $JVchNumber,
                'JVchDesc' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchTotalDebet' => $JVAmount,
                'JVchTotalCredit' => $JVAmount,
                'JVchType' => 2,
                'AppLevel1Status' => 1,
                'AppLevel1Code' => $this->session->userdata('username'),
                'AppLevel1Date' => date('Y-m-d'),
                'AppLevel2Status' => 1,
                'AppLevel2Code' => $this->session->userdata('username'),
                'AppLevel2Date' => date('Y-m-d'),
                'OldJVchNumber' => $NoTransaksi,
                'TransStatus' => 2,
                'CreatedBy' => $this->session->userdata('username'),
                'CreatedAt' => date('Y-m-d H:i:s'),
                'LastUser' => $this->session->userdata('username'),
                'LastEdited' => $this->session->userdata('username')
            );

            $this->trans_data['insert_dp_group']['data'][] = $data_group_jv;

            $data_detail_jv_debet = array(
                'JVchNumber' => $JVchNumber,
                'JVchAccount' => $UangMuka->AccountNumber,
                'JVchDebetSaldo' => $JVAmount,
                'JVchCreditSaldo' => 0,
                'JVchDetailMemo' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchDetailDept' => $this->session->userdata('department'),
                'JVchRate' => $Rate,
                'CustomerCode' => null,
                'CurrencyCode' => $cmb_currency,
                'VendorCode' => strtoupper($txt_vendorno),
                'ReconcileStatus' => 0,
                'LastUser' => $this->session->userdata('username'),
                'LastEdited' => $this->session->userdata('username')
            );

            $this->trans_data['insert_dp_detail'][$ind_jv]['data'][] = $data_detail_jv_debet;

            $data_detail_jv_credit = array(
                'JVchNumber' => $JVchNumber,
                'JVchAccount' => $OpeningBalance->AccountNumber,
                'JVchDebetSaldo' => 0,
                'JVchCreditSaldo' => $JVAmount,
                'JVchDetailMemo' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchDetailDept' => $this->session->userdata('department'),
                'JVchRate' => $Rate,
                'CustomerCode' => null,
                'CurrencyCode' => $cmb_currency,
                'VendorCode' => strtoupper($txt_vendorno),
                'ReconcileStatus' => 0,
                'LastUser' => $this->session->userdata('username'),
                'LastEdited' => $this->session->userdata('username')
            );

            $this->trans_data['insert_dp_detail'][$ind_jv]['data'][] = $data_detail_jv_credit;

            $data_journal_jv_debet = array(
                'JVchDate' => date('Y-m-d'),
                'JVchNumber' => $JVchNumber,
                'JVchDesc' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchAccountNumber' => $UangMuka->AccountNumber,
                'JVchSaldoDebet' => $cmb_currency == 'IDR' ? $JVAmount : ($JVAmount * $Rate),
                'JVchSaldoCredit' => 0,
                'JVchSignStatus' => 0,
                'AmountCurrency' => $JVAmount,
                'LastUser' => $this->session->userdata('username'),
                'LastEdited' => $this->session->userdata('username')
            );

            $this->trans_data['insert_dp_journal'][$ind_jv]['data'][] = $data_journal_jv_debet;

            $data_journal_jv_credit = array(
                'JVchDate' => date('Y-m-d'),
                'JVchNumber' => $JVchNumber,
                'JVchDesc' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchAccountNumber' => $OpeningBalance->AccountNumber,
                'JVchSaldoDebet' => 0,
                'JVchSaldoCredit' => $cmb_currency == 'IDR' ? $JVAmount : ($JVAmount * $Rate),
                'JVchSignStatus' => 0,
                'AmountCurrency' => $JVAmount,
                'LastUser' => $this->session->userdata('username'),
                'LastEdited' => $this->session->userdata('username')
            );

            $this->trans_data['insert_dp_journal'][$ind_jv]['data'][] = $data_journal_jv_credit;

            $data_update_jv = array('AppFinished' => 1);
            $this->trans_data['update_group_jv']['data'][] = $data_update_jv;
            $this->trans_data['update_group_jv']['TransNumber'][] = $JVchNumber;

            $ind_jv++;
        }

        /* =============================trans roll back dan trans commit============================/ */
        $result_return = $this->m_vendors->update_transsaction($this->trans_data);

        $this->trans_data = [];

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

        echo json_encode($result);
    }

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

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

        $hasil = $this->m_vendors->suspend($data, $id);
        if ($hasil == 0) {
            $result['status'] = true;
            $result['message'] = get_notification('delete', $hasil);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('delete', $hasil);
        }

        echo json_encode($result);
    }

    public function to_preview($obj_string = null) {
        //ambil data dari session untuk hak akses
        $group_menu = $this->session->userdata('group_menu');
//        $sess_company = $this->session->userdata('company');
//        $sess_branch = $this->session->userdata('branch');
//        $sess_branch_status = $this->session->userdata('branch_status');

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

        $data['company'] = $this->m_vendors->get_company();
//        $data['list']		= $this->m_vendors->preview_all_by_search($sess_company,$sess_branch,$sess_branch_status);
        $data_filter = arrayParamInUrlToStr($obj_string);
        $data['list'] = $this->m_vendors->get_all_to_print($data_filter);

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

    public function to_preview_LAMA() {
        //ambil data dari session untuk hak akses
        $group_menu = $this->session->userdata('group_menu');
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');

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

        $data['company'] = $this->m_vendors->get_company();
        $data['list'] = $this->m_vendors->preview_all_by_search($sess_company, $sess_branch, $sess_branch_status);

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

    // Function Pdf
    public function to_pdf() {
        $this->load->library('html2pdf');
        $this->html2pdf->folder('./asset/pdfs/');
        $this->html2pdf->filename('List vendors.pdf');
        $this->html2pdf->paper('a4', 'portrait');

        $data['list'] = $this->m_vendors->get_all();

        $this->html2pdf->html($this->load->view('vendors/v_print_vendors', $data, true));
        $this->html2pdf->create();
    }

    // Function Excel
    public function to_excel() {
        $this->load->library('export');

        $sql = $this->m_vendors->view_all();

        $header = array(
            'MenuId' => 'ID',
            'MenuLabel' => 'Name',
            'MenuLink' => 'Rate',
            'MenuLevel' => 'Country'
        );

        $this->export->to_excel($sql, 'List vendors', $header);
    }

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

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

        $data = array(
            'vend_trans_status_no' => $vendor_trans_status_no,
            'balance_saldo' => $saldo_balance
        );

        echo json_encode($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();
    }

}
