<?php

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

/* 	
 * 	Author 	: Tagor / Tanggal : 23-07-2014	
 * 	Revisi 	: Fachri
 */

class Customers extends CI_Controller {

    public $menu_id = 117;
    public $menu_model = 'm_customer';
    public $trans_data = array();
    public $arr_number = array('SI' => array(), 'JV' => array());
    public $add = "add";
    public $edit = "edit";
    public $delete = "delete";
    public $to_preview = "to_preview";
    public $to_pdf = "to_pdf";
    public $to_excel = "to_excel";
    public $name = "Customer";

    public function __construct() {
        parent::__construct();
        $this->load->model('m_customer');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
        $this->load->library('PHPExcel');
        $this->load->model('m_sales_invoice');
        $this->load->model('m_delivery_order');
        $this->load->model('m_account_journal');
        $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('customer/v_customers', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

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

        $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('am_customer.BranchCode', $BranchCode);
			$this->db->where('am_currency.CompanyCode', $CompanyCode);
        } else {
            $this->db->where('am_customer.BranchCode', $this->session->userdata('branch'));
			$this->db->where('am_currency.CompanyCode', $sess_company);
        }

        if ($Code != "") {
            $this->db->like('am_customer.CustomerCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('am_customer.CustomerName', $Name);
        }

        if ($TransStatus != '') {
            $this->db->where_in('am_customer.TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('am_customer.TransStatus', array(0, 1));
        }

        if ($CurrencyCode != "") {
            $this->db->where('am_customer.CurrencyCode', $CurrencyCode);
        }
        /* ==========================end================================================================= */
		
		$this->db->join('am_currency', 'am_currency.CurrencyCode = am_customer.CurrencyCode', 'inner');
        $this->db->join('am_city', 'am_city.CityCode = am_customer.CustomerCity', 'left');
		$this->db->join('am_termspayment', 'am_termspayment.TermsPaymentID = am_customer.TermsPaymentID', 'inner');
		 
        $count_data = $this->db->count_all_results('am_customer');

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

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

            $hasil[] = array(
                'TransNumber' => $result[$i]->CustomerCode,
                'CustomerName' => $result[$i]->CustomerName,
                'PhoneNumber' => str_replace(',','',$result[$i]->PhoneNumber),
                'ContactPerson' => $result[$i]->ContactPerson,
                'OutStanding' => $result[$i]->OutStanding,
                'CurrencyName' => $result[$i]->CurrencyName,
                'BranchCode' => $result[$i]->BranchCode,
				'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);
        }
    }

    //function get info percent terms
    function get_termspercent_value($terms_id) {
        $result = $this->m_customer->get_termspercent_value($terms_id);

        foreach ($result as $row) {
            $array = array(
                'disc_days' => $row->PaidWithin,
                'disc_percent' => $row->DiscountPercent,
                'net_days' => $row->NetDueIn
            );

            $result = json_encode($array);
            echo $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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

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

                    $ceknourut = $this->m_customer->get_last_customer_code($sess_brach);

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

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

                        $count_recnumb = strlen($pay_numb3);

                        if ($count_recnumb == 1) {
                            $data['next_customer_numb'] = '0000' . $pay_numb3;
                        } elseif ($count_recnumb == 2) {
                            $data['next_customer_numb'] = '000' . $pay_numb3;
                        } elseif ($count_recnumb == 3) {
                            $data['next_customer_numb'] = '00' . $pay_numb3;
                        } elseif ($count_recnumb == 4) {
                            $data['next_customer_numb'] = '0' . $pay_numb3;
                        } elseif ($count_recnumb == 5) {
                            $data['next_customer_numb'] = $pay_numb3;
                        }

                        $data['branch_code'] = $sess_brach;
                    } else {
                        $data['branch_code'] = $sess_brach;
                        $data['next_customer_numb'] = '0001';
                    }
                    //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('customer/v_new_customers', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function insert() {
        $txt_customerno = $this->input->post('txt_customerno');
        $chk_suspend = $this->input->post('chk_suspend');

        $txt_customername = $this->input->post('txt_customername');
        $address1 = $this->input->post('txt_address');
        $address2 = $this->input->post('txt_addressdetail');
        $txt_address = "$address1 $address2";
        $taxaddress1 = $this->input->post('txt_taxaddress');
        $taxaddress2 = $this->input->post('txt_taxaddressdetail');
        $txt_taxaddress = "$taxaddress1 $taxaddress2";
        $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_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');
        $txt_salesorderlimit = $this->input->post('txt_salesorderlimit_hidden');
        $txt_outstanding = $this->input->post('txt_outstanding_hidden');
        $cmb_currency = $this->input->post('cmb_currency');
        $rd_vendor_type = $this->input->post('rd_vendor_type');

        $txa_message_terms = $this->input->post('txa_message_terms');
        $chk_print_cust_stat_report = $this->input->post('chk_print_cust_stat_report');

        $cmb_tax1 = $this->input->post('cmb_tax1');
        $cmb_tax2 = $this->input->post('cmb_tax2');
        $chk_taxincluded = $this->input->post('chk_taxincluded');
        $txt_taxnumber = $this->input->post('txt_taxnumber');
        $txt_nppkp = $this->input->post('txt_nppkp');
        $cmb_taxtype = $this->input->post('cmb_taxtype');
        $cmb_region = $this->input->post('cmb_region');
        $txa_notes = $this->input->post('txa_notes');

        if ($this->m_customer->check_code_exist($txt_customerno) == TRUE) {
            $result['status'] = false;
            $result['message'] = 'Customer 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 ($cmb_region != "") {
            if ($this->m_customer->check_code_exist_region($cmb_region) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf region ' . $cmb_region . ' 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 ($cmb_terms == "") {
            $result['status'] = false;
            $result['message'] = 'Maaf terms belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($cmb_currency == "") {
            $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'),
            'CustomerCode' => strtoupper($txt_customerno),
//              'TransStatus' 			=> ($chk_suspend == 3)? $chk_suspend: 0,
            'TransStatus' => 1,
            'CustomerName' => strtoupper($txt_customername)." ".$cmb_currency,
            'CustomerAddress' => $txt_address,
            'CustTaxAddress' => $txt_taxaddress,
            'CustomerCity' => $cmb_city,
            'CustomerState' => $cmb_state,
            'CustomerPostalCode' => $txt_zipcode,
            'CustomerCountry' => $cmb_country,
            'PhoneNumber' => $txt_phone,
            'FacsimileNumber' => $txt_fax,
            'ContactPerson' => $txt_contactperson,
            'EmailAddress' => $txt_email,
            'WebAddress' => $txt_webpage,
            'TermsPaymentID' => $cmb_terms,
            'SalesLimit' => $txt_salesorderlimit,
            'CurrencyCode' => $cmb_currency,
            'CurrencyMemo' => $txa_message_terms,
            'Taxes1Code' => ($cmb_tax1 == '') ? null : $cmb_tax1,
            'Taxes2Code' => ($cmb_tax2 == '') ? null : $cmb_tax2,
            'TaxIncludedStatus' => ($chk_taxincluded == 1) ? $chk_taxincluded : 0,
            'TaxesNumber' => $txt_taxnumber,
            'PPKPNumber' => $txt_nppkp,
            'TaxesTypeID' => ($cmb_taxtype == '') ? null : $cmb_taxtype,
            'RegionCode' => ($cmb_region == '') ? null : $cmb_region,
            'CustomerDesc' => $txa_notes,
            'CustomerStatus' => $rd_vendor_type,
            'TransStatus' => 1,
            'OutStanding' => $txt_outstanding,
            'LastUser' => $this->session->userdata("username")
        );

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

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    $group_menu = $this->session->userdata('group_menu');
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

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

                    $data['row'] = $this->m_customer->get_by_id($customer_code);
					$Customer = implode(' ', explode(' ', $data['row']->CustomerName, -1)); 
					
					$data['Customer'] = $Customer;
                    //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('customer/v_edit_customer', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

        $txt_customerno = $this->input->post('txt_customerno');
        $chk_suspend = $this->input->post('chk_suspend');
        $txt_customername = $this->input->post('txt_customername');
        $address1 = $this->input->post('txt_address');
        $address2 = $this->input->post('txt_addressdetail');
        $txt_address = "$address1 $address2";
        $taxaddress1 = $this->input->post('txt_taxaddress');
        $taxaddress2 = $this->input->post('txt_taxaddressdetail');
        $txt_taxaddress = "$taxaddress1 $taxaddress2";
        $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');
        $rd_vendor_type = $this->input->post('rd_vendor_type');

        $txt_fax = $this->input->post('txt_fax');
        $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');
        $txt_salesorderlimit = $this->input->post('txt_salesorderlimit_hidden');
        $txt_outstanding_hidden = $this->input->post('txt_outstanding_hidden');
        $cmb_currency = $this->input->post('cmb_currency');
        $txa_message_terms = $this->input->post('txa_message_terms');
        $chk_print_cust_stat_report = $this->input->post('chk_print_cust_stat_report');

        $cmb_tax1 = $this->input->post('cmb_tax1');
        $cmb_tax2 = $this->input->post('cmb_tax2');
        $chk_taxincluded = $this->input->post('chk_taxincluded');
        $txt_taxnumber = $this->input->post('txt_taxnumber');
        $txt_nppkp = $this->input->post('txt_nppkp');
        $cmb_taxtype = $this->input->post('cmb_taxtype');
        $cmb_region = $this->input->post('cmb_region');
        $txa_notes = $this->input->post('txa_notes');
        $detail = $this->input->post('detail');
        $txt_cust_balance = $this->input->post('txt_cust_balance');
        $klik = $this->input->post('id_klik');
        $branchCode = $this->session->userdata('branch');
        $hasil = 0;
        $konversi = $this->input->post('konversi');
        $rate_data = $this->input->post('rate_data');

        $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 ($cmb_region != "") {
            if ($this->m_customer->check_code_exist_region($cmb_region) == FALSE) {
                $result['status'] = false;
                $result['message'] = 'Maaf region ' . $cmb_region . ' 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 ($cmb_terms == "") {
            $result['status'] = false;
            $result['message'] = 'Maaf terms belum terdaftar, silahkan cek kembali';
            echo json_encode($result);
            die();
        } else if ($cmb_currency == "") {
            $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();
            }
        }
        //if ($status == 1){
        $data = array(
            'CustomerName' => $txt_customername,
            'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 0,
            'CustomerName' => strtoupper($txt_customername)." ".$cmb_currency,
            'CustomerAddress' => $txt_address,
            'CustTaxAddress' => $txt_taxaddress,
            'CustomerCity' => $cmb_city,
            'CustomerState' => $cmb_state,
            'CustomerPostalCode' => $txt_zipcode,
            'CustomerCountry' => $cmb_country,
            'PhoneNumber' => $txt_phone,
            'FacsimileNumber' => $txt_fax,
            'ContactPerson' => $txt_contactperson,
            'EmailAddress' => $txt_email,
            'WebAddress' => $txt_webpage,
            'CustomerStatus' => $rd_vendor_type,
            'TermsPaymentID' => $cmb_terms,
            'SalesLimit' => $txt_salesorderlimit,
            'CurrencyCode' => $cmb_currency,
            'CurrencyMemo' => $txa_message_terms,
            'Taxes1Code' => ($cmb_tax1 == '') ? null : $cmb_tax1,
            'Taxes2Code' => ($cmb_tax2 == '') ? null : $cmb_tax2,
            'TaxIncludedStatus' => ($chk_taxincluded == 1) ? $chk_taxincluded : 0,
            'TaxesNumber' => $txt_taxnumber,
            'PPKPNumber' => $txt_nppkp,
            'TaxesTypeID' => ($cmb_taxtype == '') ? null : $cmb_taxtype,
            'RegionCode' => ($cmb_region == '') ? null : $cmb_region,
            'CustomerDesc' => $txa_notes,
            'OutStanding' => $txt_cust_balance,
            'TransStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //function update
        //$this->db->trans_begin();
        //$hasil = $this->m_customer->update($data, $id);
        //if($hasil == 0) {$this->trans_rollback('insert');}
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $id;

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

        if ($klik == 1) {
            $detail = json_decode($detail);
            $no_si_2 = "";
            $NewCategoryAmount = array();
            $ind_arr = 0;

            if ($detail) {
                foreach ($detail as $row) {
                    $no_si = $row->OldSInvNumber;
                    $SInvDate = $row->SInvDate;
                    $OutStanding = $row->OutStanding;
                    $SalesmanName = $row->EmployeeName;
                    $SalesmanCode = $this->m_customer->get_employee_code($SalesmanName,$branchCode);

                    if ($SalesmanCode == false) {
                        $this->trans_rollback('customer', 'EmployeeName', '');
                    }

                    if (count($this->arr_number['SI']) < 1) {
                        $sales_in = $this->m_sales_invoice->create_si_number(date('d-m-Y'));
                        array_push($this->arr_number['SI'], $sales_in);
                    } else {
                        $index_number = count($this->arr_number['SI']) - 1;
                        $si_number_before = $this->arr_number['SI'][$index_number];
                        $arr_no = explode("/", $si_number_before);
                        $no_explode = $arr_no[2];
                        $ordinal_number = sprintf("%03s", (int) $no_explode + 1);
                        $sales_in = $arr_no[0] . '/' . $arr_no[1] . '/' . $ordinal_number;

                        array_push($this->arr_number['SI'], $sales_in);
                    }

                    $term = $this->m_customer->get_terms_by_row($cmb_terms);
                    $term_waktu = $term->NetDueIn;

                    $pecah = explode('-', $SInvDate);
                    $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";
                    $ItemDesc = "ITEM MIGRASI UNTUK SEMUA CURRENCY";

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

                    /*
                      Cek inventori item exis not exis
                     */
                    $get_inventori = $this->m_customer->get_inventories($Item_code);

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

                        echo json_encode($result);
                        die();
                    }
                    /* ======================End============================================================================ */

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

                    $data_sales_invoice = array(
                        'BranchCode' => $this->session->userdata('branch'),
                        'CustomerCode' => strtoupper($txt_customerno),
                        'SInvNumber' => $sales_in,
                        'DOrdNumber' => $sales_in,
                        'SOrdNumber' => $sales_in,
                        'ShippingAddress' => $txt_address,
                        'BillingAddress' => $txt_address,
                        'TermsPaymentID' => $cmb_terms,
                        'ImportStatus' => 1,
                        'SInvDate' => date('Y-m-d'),
                        'ShipDate' => date("Y-m-d", strtotime($SInvDate)),
                        'ShipmentID' => 1,
						'FOBID' => 1,
                        'CustPONumber' => $sales_in,
                        'CurrencyCode' => $cmb_currency,
                        'CurrencyRate' => $Rate,
                        'DOrdDate' => date('Y-m-d'),
                        'SInvDueDate' => $tgl_tempo,
                        'TransStatus' => 1,
                        'AppLevel1Status' => 1,
                        'SInvEstFreight' => 0,
                        'SInvDesc' => "Item Migrasi Database, Tgl Invoice (".$SInvDate.")",
                        'OldSInvNumber' => $no_si,
                        'FiscalRate' => 1,
                        'AppLevel1Code' => $this->session->userdata("username"),
                        'AppLevel1Date' => date('Y-m-d'),
                        'CreatedBy' => $this->session->userdata("username"),
                        'CreatedAt' => date('Y-m-d'),
                        'LastUser' => $this->session->userdata("username")
                    );
                    

                    $data_detail_si = array(
                        'SOrdNumber' => $sales_in,
                        'SInvNumber' => $sales_in,
                        'ItemCode' => $item_inventori,
                        'ItemQty' => 1,
                        'ItemDesc' => $ItemDesc,
                        'ItemUnit' => 'Unit',
                        'ItemCategoryID' => $item_kategori,
                        'ItemPrice' => $OutStanding,
                        'ItemPriceCogs' => 0,
                        'SalesmanCode' => $SalesmanCode,
                        'ItemAmount' => $OutStanding,
                        'ItemTotalAmount' => $OutStanding,
                        'ItemCategoryID' => $item_kategori,
                        'ItemCategoryCode' => $item_kategori,
                        'ItemType' => 0,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $data_invoice_receipt = array(
                        'BranchCode' => $this->session->userdata('branch'),
                        'CustomerCode' => strtoupper($txt_customerno),
                        'InvoiceCurrCode' => $cmb_currency,
                        'InvoiceCurrRate' => doubleval($Rate),
                        'InvoiceFiscalRate' => 1,
                        'InvoiceNumber' => $sales_in,
                        'InvoiceDate' => date('Y-m-d'),
                        'ItemCategoryID' => $item_kategori,
                        'ItemCategoryCode' => $item_kategori,
                        'InvoiceType' => 0,
                        'PPnFiscalStatus' => 0,
                        'LastUser' => $this->session->userdata('username')
                    );

                    if ($no_si_2 != $no_si) {

                        $this->trans_data['detail_si']['total'] += 1;
                        //$this->m_customer->insert_sales_invoice($data_sales_invoice);
                        $this->trans_data['insert_sales_invoice']['data'][] = $data_sales_invoice;

                        //$this->m_customer->insert_detail($data_detail_si);
                        $this->trans_data['insert_detail']['data'][] = $data_detail_si;

                        //$this->m_sales_invoice->insert_sinv_receipt($data_invoice_receipt);
                        $this->trans_data['insert_sinv_receipt']['data'][] = $data_invoice_receipt;
                    }

                    $no_si_2 = $no_si;

                    //ganti ke opening balance untuk pasangan disini
                    $OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
                    if ($OpeningBalance == false) {
                        $this->trans_rollback('journal', 'Opening Balance', '');
                    }

                    $Openig_journal = $cmb_currency == 'IDR' ? $OutStanding : $OutStanding * $Rate;
                    $Openig_currency = $OutStanding;

                    $data_Inventori_journal = array(
                        'SInvDate' => date('Y-m-d'),
                        'SInvNumber' => $sales_in,
                        'SInvAccountNumber' => $OpeningBalance->AccountNumber,
                        'SInvSaldoDebet' => 0,
                        'SInvSaldoCredit' => $Openig_journal,
                        'AmountCurrency' => doubleval($Openig_currency),
                        'SInvSignStatus' => 0,
                        'LastUser' => $this->session->userdata('username')
                    );

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

                    $ReceivableAccount = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $item_kategori, $cmb_currency);
                    if ($ReceivableAccount == false) {
                        $this->trans_rollback('journal', 'Piutang Dagang', '');
                    }

                    $receivable_journal = $cmb_currency == 'IDR' ? $OutStanding : $OutStanding * $Rate;
                    $receivable_currency = $OutStanding;

                    $data_receivable_journal = array(
                        'SInvDate' => date('Y-m-d'),
                        'SInvNumber' => $sales_in,
                        'SInvAccountNumber' => $ReceivableAccount->AccountNumber,
                        'SInvSaldoDebet' => $receivable_journal,
                        'SInvSaldoCredit' => 0,
                        'AmountCurrency' => doubleval($receivable_currency),
                        'SInvSignStatus' => 0,
                        'LastUser' => $this->session->userdata('username')
                    );

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

                    @$CategoryAmount[$row->OldSInvNumber] += $OutStanding; // summing sub total balance
                    @$NewCategoryAmount[$sales_in] += $OutStanding; // summing by ne invoice number

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

                    $ind_arr++;
                }
            }

            foreach ($NewCategoryAmount as $key => $value) {
                $data_update_receipt = array(
                    'InvoiceAmount' => doubleval($value),
                    'InvoiceOwing' => doubleval($value),
                    'InvoiceCurrency' => doubleval($value),
                    'ItemCategoryRatio' => 100,
                );
                //$this->m_sales_invoice->update_sinv_receipt_2($data_update_receipt, $key);
                $this->trans_data['update_sinv_receipt_2']['data'][] = $data_update_receipt;
                $this->trans_data['update_sinv_receipt_2']['key'][] = $key;
            }

            foreach ($CategoryAmount as $key => $value) {
                $data_update_total = array(
                    'SInvSubTotal' => $value,
                    'SInvTotalAmount' => $value
                );

                //$this->m_customer->update_sales_invoice($data_update_total, $key, $branchCode);
                $this->trans_data['update_sales_invoice']['data'][] = $data_update_total;
                $this->trans_data['update_sales_invoice']['key'][] = $key;
                $this->trans_data['update_sales_invoice']['BranchCode'][] = $branchCode;
            }
        }

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

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

                //$hasil = $this->m_customer->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']['BranchCode'][] = $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 Penjualan', $cmb_currency);

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

            $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_so_detail_dp = array(
                'SOrdNumber' => $JVchNumber,
                'CustomerCode' => strtoupper($txt_customerno),
                'InvoiceNumber' => $JVchNumber,
                'SRecNumber' => $JVchNumber,
                'SOrdTotalDP' => $JVAmount,
                'Owing' => 0,
                'PaymentAmount' => $JVAmount,
                'PaymentDate' => date('Y-m-d'),
                'PaidStatus' => 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_sord_detail_dp']['data'][] = $data_so_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' => 0,
                'JVchCreditSaldo' => $JVAmount,
                'JVchDetailMemo' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchDetailDept' => $this->session->userdata('department'),
                'JVchRate' => $Rate,
                'CustomerCode' => strtoupper($txt_customerno),
                'CurrencyCode' => $cmb_currency,
                'VendorCode' => null,
                '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_journal_jv_debet = array(
                'JVchDate' => date('Y-m-d'),
                'JVchNumber' => $JVchNumber,
                'JVchDesc' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchAccountNumber' => $UangMuka->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_debet;

            $data_detail_jv_credit = array(
                'JVchNumber' => $JVchNumber,
                'JVchAccount' => $OpeningBalance->AccountNumber,
                'JVchDebetSaldo' => $JVAmount,
                'JVchCreditSaldo' => 0,
                'JVchDetailMemo' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchDetailDept' => $this->session->userdata('department'),
                'JVchRate' => $Rate,
                'CustomerCode' => strtoupper($txt_customerno),
                'CurrencyCode' => $cmb_currency,
                'VendorCode' => null,
                '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_credit = array(
                'JVchDate' => date('Y-m-d'),
                'JVchNumber' => $JVchNumber,
                'JVchDesc' => 'Journal Voucher Item Migrasi dan Opening Balance',
                'JVchAccountNumber' => $OpeningBalance->AccountNumber,
                'JVchSaldoDebet' => $cmb_currency == 'IDR' ? $JVAmount : ($JVAmount * $Rate),
                'JVchSaldoCredit' => 0,
                'JVchSignStatus' => 1,
                '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_customer->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);
    }

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

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

        $data = array(
            'cust_stat_number' => $cust_number_status,
            'cust_stat_saldo' => $cust_saldo_balance
        );

        echo json_encode($data);
    }

    public function suspend() {
        $id = $this->input->post('id');
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('user')
        );

        $hasil = $this->m_customer->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);
    }

    // Function Print
    public function to_preview($obj_string = NULL) {
//		$sess_company		= $this->session->userdata('company');
//		$sess_branch		= $this->session->userdata('branch');
//		$sess_branch_status	= $this->session->userdata('branch_status');		
//		$data['list'] = $this->m_customer->preview_all_by_search($sess_company,$sess_branch,$sess_branch_status);
        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_customer->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('customer/v_print_customer', $data);
        $this->load->view('v_footer');
    }

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

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

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

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

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

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

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

        $sql = $this->m_userpofile->view_all();
        $header = array(
            'MenuId' => 'ID',
            'MenuLabel' => 'Name',
            'MenuLink' => 'Rate',
            'MenuLevel' => 'Country'
        );
        $this->export->to_excel($sql, 'List Currency', $header);
    }

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

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

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

    function temporary_save() {
        include_once(APPPATH . "libraries/PHPExcel/IOFactory.php");
        $inputFileName = $_FILES["cust_file"]["tmp_name"];

        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);

        //$objPHPExcel 	= PHPExcel_IOFactory::load($filename);		

        $sheetCount = $objPHPExcel->getSheetCount();

        for ($i = 0; $i <= $sheetCount; $i++) {
            if ($i == 0) {
                $objPHPExcel->setActiveSheetIndex($i);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);

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

                for ($j = 2; $j <= $lastRow; $j++) {
                    $CustCode = $sheetData[$j]['A'];
                    $CheckCustCode[] = $this->m_customer->get_customer_code($CustCode);
                    $CustCodeArr[] = $CustCode;
                }

                $CheckCustCode = array_filter($CheckCustCode);
                $a = count($CheckCustCode);
                $b = count($CustCodeArr);

                // if($a != $b){
                // $hasil 		= 1;
                // $Code		= 1;
                // $keterangan	= 'CustomerCode tidak kosong, silahkan rubah dan upload ulang semua data';
                // }
                // else
                if (!empty($CheckCustCode)) {
                    $hasil = 2;
                    $Code = 2;
                    $keterangan = $CheckCustCode;
                } else {
                    $ceknourut = $this->m_customer->get_last_customer_code($BranchCode);
                    if (!empty($ceknourut) || $ceknourut != null) {
                        foreach ($ceknourut as $row) {
                            $number = $row->CustomerCode;
                            $explode_number = explode("-", $number);
                            $last_index = (count($explode_number) - 1);
                            $last_number = $explode_number[$last_index];
                            if (empty($last_index)) {
                                $pay_numb3 = '00001';
                            } else {
                                $pay_numb3 = $last_number + 1;
                            }
                        }

                        $count_recnumb = strlen($pay_numb3);
                        if ($count_recnumb == 1) {
                            $next_customer_numb = '0000' . $pay_numb3;
                        } elseif ($count_recnumb == 2) {
                            $next_customer_numb = '000' . $pay_numb3;
                        } elseif ($count_recnumb == 3) {
                            $next_customer_numb = '00' . $pay_numb3;
                        } elseif ($count_recnumb == 4) {
                            $next_customer_numb = '0' . $pay_numb3;
                        } elseif ($count_recnumb == 5) {
                            $next_customer_numb = $pay_numb3;
                        }
                        $branch_code = $BranchCode;
                    } else {
                        $branch_code = $BranchCode;
                        $next_customer_numb = '0001';
                    }
                    for ($j = 1; $j <= $lastRow; $j++) {
                        $CustomerCode = $branch_code . "-" . $next_customer_numb;
                        $CustomerName = $sheetData[$j]['A'];
                        $CustomerAddress1 = $sheetData[$j]['B'];
                        $CustomerAddress2 = $sheetData[$j]['C'];
                        $CustomerCity = $sheetData[$j]['D'];
                        $CustomerProv = $sheetData[$j]['E'];
                        $CustomerZipCode = $sheetData[$j]['F'];
                        $CustomerCountry = $sheetData[$j]['G'];
                        $PhoneNumber = $sheetData[$j]['H'];
                        $ContactPerson = $sheetData[$j]['I'];
                        $FacsimileNumber = $sheetData[$j]['J'];
                        $EmailAddress = $sheetData[$j]['K'];
                        $WebAddress = $sheetData[$j]['L'];
                        $TaxesNumber = $sheetData[$j]['M'];
                        $PPKPNumber = $sheetData[$j]['N'];
                        $Notes = $sheetData[$j]['O'];
                        $TaxType = $sheetData[$j]['P'];
                        $SalesLimit = $sheetData[$j]['Q'];

                        $data = array(
                            'BranchCode' => $BranchCode,
                            'CustomerCode' => $CustomerCode,
                            'CustomerName' => $CustomerName,
                            'CustomerAddress' => $CustomerAddress1 . $CustomerAddress2,
                            'CustomerCity' => $CustomerCity,
                            'CustomerState' => $CustomerProv,
                            'CustomerCountry' => $CustomerCountry,
                            'CustomerPostalCode' => $CustomerZipCode,
                            'PhoneNumber' => $PhoneNumber,
                            'FacsimileNumber' => $FacsimileNumber,
                            'ContactPerson' => $ContactPerson,
                            'EmailAddress' => $EmailAddress,
                            'WebAddress' => $WebAddress,
                            'SalesLimit' => $SalesLimit,
                            'CurrencyCode' => 'IDR',
                            'CurrencyMemo' => $Notes,
                            'TaxesNumber' => $TaxesNumber,
                            'PPKPNumber' => $PPKPNumber,
                            'LastUser' => $this->session->userdata('username')
                        );
                        $hasil = $this->m_customer->import_customer($data);
                        $hasil = $hasil;
                        $Code = 0;
                        $keterangan = 'Success Import';
                    }
                }
                $notif = array(
                    'Code' => $Code,
                    'keterangan' => $keterangan
                );
                echo json_encode($notif);
            }
        }
    }


    function list_salesman(){
        $branch = $this->session->userdata('branch');
        $list_sales = $this->m_customer->get_list_salesman($branch);
        //echo $this->db->last_query();
        echo json_encode($list_sales);
    }

}
