<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Author      : Herpan / 22/7/2014 / controller for chart of account
Edited      : Ferry / 28-11-2014 / - Appear COA Based on Company and Branch - Appear Branch P/L Account
Edited      : Fachri / 30-07-2015 / - Edit Function Global
*/

class Coa extends CI_Controller {
    public $menu_id             = 94;
    public $menu_model          = array('m_coa','m_compaccountgl','list/m_currency','list/m_journalvoucher','list/m_account_journal');	
    public $name				= "Account Name";
    public $HaveBranch          = "";
    public $CompanyName         = "";
    public $app1				= array("1");
    public $app2				= array("0");
    public $BranchStatus        = 0;
		
    public function __construct() {
        parent::__construct();
		$this->load->model($this->menu_model);
		$this->load->model('login/m_login');
		$this->load->model('custom/m_custom');
		$this->load->helper('regex');
		$this->load->helper('message');
		$this->load->helper('status');
                $this->load->helper('notices_import_file'); 
                $this->load->helper('custom_string');
		
		$this->load->model('setup/m_branchinfo');
		
		//$this->load->library('../modules_core/custom/controllers/get_data');
		
		$Company			= $this->m_compaccountgl->get_company_by_code($this->session->userdata('company'));
		$this->BranchStatus = $this->session->userdata('branch_status');
		$this->CompanyName 	= $Company->CompanyName;
		$this->HaveBranch  	= $Company->CompBranchStatus;	
    }		

    public function index() {
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$group_menu         	= $this->session->userdata('group_menu');
					$data['menu_id']        = $this->menu_id;
					$data['coa_num_rows']   = $this->m_coa->get_all_num_rows();        
					$data['menu_link'] 	= $this->m_menu->get_menulink($this->menu_id);
					
					$data['BranchStatus']   = $this->BranchStatus;
					$data['HaveBranch']     = $this->HaveBranch;
					$data['cek_data_gl'] 	= $this->m_coa->check_data_from_master_gl();
					//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('coa/v_coa',$data);
					$this->load->view('v_footer');			
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
    }
        
    public function add(){
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					$group_menu         	= $this->session->userdata('group_menu');
					
					$data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
					$data['AccountNumber']  = $this->m_coa->create_account_number('');
					
					//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('coa/v_add_coa',$data);
					$this->load->view('v_footer');		
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
    }
	
    public function insert() {	
        try{
            //=========== deklar variacel harus di atas ======================//
            $AccountSubTypeID   = $this->input->post('cmb_account_sub_type');
            $AccountName        = $this->input->post('txt_account_name');
            $AccountParent      = $this->input->post('cmb_account_parent');
            $AccountNumber      = $this->m_coa->create_account_number($AccountParent);//ga masuk ke model karena create statis(sekali doank)
            $CurrencyCode       = $this->input->post('cbg_currency');
            $dataSend   = [];
            $dataSend['data_accountgl']   = [];
            $dataSend['data_companygl']   = [];
            //=========== End deklar variacel harus di atas ==================//

            //=========== cek duplikasi jika nama coa sudah ada maka gagal ===//
            $check_auto_status  = $this->m_coa->check_auto_status($AccountSubTypeID);   

            if($check_auto_status == 1){
                $Cek_Name = $AccountName.' '.$CurrencyCode;
            }else{
                $Cek_Name = $AccountName;
            }
            $check_gl_coa       = $this->m_coa->check_name_exist($Cek_Name);
            //=========== end cek duplikasi jika nama coa sudah ada maka gagal//
		
            $gl_company         = $this->input->post('chk_company');        
            $gl_company_data    = json_decode($gl_company);
            $spell_name         = explode(' ', $AccountName);
            $count_spell        = count($spell_name);
        
            //=========== akun name tidak boleh menggunakan currency =========//
            if($check_auto_status == 1){
                $check_spell        = $spell_name[$count_spell - 1] == 'IDR' ? TRUE : FALSE;
            }else{
                $check_spell        = FALSE;
            }
            //=========== end akun name tidak boleh menggunakan currency =====//
                    
            if (($check_gl_coa == FALSE) && ($check_spell == FALSE) && (count($gl_company_data) > 0)) {
                //======= cek coa auto status ================================//
                $check_auto_status  = $this->m_coa->check_auto_status($AccountSubTypeID);            
                $new_account_name   = $check_auto_status ? $AccountName . ' ' . $CurrencyCode : $AccountName;
                $account_level      = $this->m_coa->get_level($AccountParent);
                //======= end cek coa auto status ============================//

                //======= 1. Insert new COA into am_accountgl (adding coa status 6) ===//
                $dataSend['data_accountgl']     = array (
                    'AccountSubTypeID'      => $AccountSubTypeID,
                    'AccountNumber'         => $AccountNumber,
                    'AccountName'           => $new_account_name,
                    'CurrencyCode'          => $CurrencyCode,
                    'AccountParent'         => $AccountParent,
                    'AccountLevel'          => $account_level,
                    'BankID'                => NULL,
                    'AccountChild'          => 1,
                    'TransStatus'           => 5,
                    'LastUser'              => $this->session->userdata("username")
                );
//                $this->m_coa->insert($account_gl);
                //======= End 1. Insert new COA into am_accountgl (adding coa status 6) ===//

                //======= 2. Insert new COA into at_compaccountgl for each Company Code ===//
                foreach($gl_company_data as $row) {
                    $dataSend['data_companygl'][] = array(
                        'CompanyCode'       => $row->CompanyCode,
                        'BranchCode'        => $row->BranchCode,
                        'AccountNumber'     => $AccountNumber,
                        'TransStatus'       => 5,
                        'GLSaldoYears'      => date('Y')
                    );
//                   $this->m_compaccountgl->insert($glcompany_data);	
                }
                //======= End 2. Insert new COA into at_compaccountgl for each Company Code ===//
                
                $rstDataSend = $this->m_coa->datasend_coa_newinsert($dataSend);
                if($rstDataSend){
                    $result['status'] 	= true;
                    $result['message']	= get_notification_transaksi_master('Chart Of Account', 'insert', 1);                
                }else{
                    $result['status'] 	= false;
                    $result['message']	= get_notification_transaksi_master('Chart Of Account', 'insert', 0);
                }
                echo json_encode($result);
            }else{
                if($check_gl_coa == TRUE){ 
                    throw new Exception("Maaf Pendaftaraan COA Gagal, Nama Akun Tidak Boleh Sama");
                }else if($check_spell == TRUE){
                    throw new Exception("Account Name tidak boleh menggunakan Currency Code : '" . $CurrencyCode . "'");               
                }else{    
                    throw new Exception("Silahkan pilih Company Name terlebih dahulu'");
                } 
            }			
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }    
    public function insert_LAMA() {	
        /*==================================deklar variacel harus di atas===============================*/
		$AccountSubTypeID   = $this->input->post('cmb_account_sub_type');
        $AccountName        = $this->input->post('txt_account_name');
        $AccountParent      = $this->input->post('cmb_account_parent');
        $AccountNumber      = $this->m_coa->create_account_number($AccountParent);
        $CurrencyCode       = $this->input->post('cbg_currency');

		/*
			cek duplikasi jika nama coa sudah ada maka gagal
		*/
		$check_auto_status  = $this->m_coa->check_auto_status($AccountSubTypeID);    
		
		if($check_auto_status == 1){
			$Cek_Name = $AccountName.' '.$CurrencyCode;
		}
		else{
			$Cek_Name = $AccountName;
		}
        
		$check_gl_coa       = $this->m_coa->check_name_exist($Cek_Name);
		/*========================end======================================*/
		
        $gl_company         = $this->input->post('chk_company');        
        $gl_company_data    = json_decode($gl_company);
        $spell_name         = explode(' ', $AccountName);
        $count_spell        = count($spell_name);
        
		/*
			akun name tidak boleh menggunakan currency
		*/
		if($check_auto_status == 1){
			$check_spell        = $spell_name[$count_spell - 1] == 'IDR' ? TRUE : FALSE;
		}
		else{
			$check_spell        = FALSE;
		}
		/*==========================end=================================================================*/
		
		/*============================================end===============================================*/
        
        if (($check_gl_coa == FALSE) && ($check_spell == FALSE) && (count($gl_company_data) > 0)) {
            $this->db->trans_begin();
			
			/*===================cek coa auto status======================================================*/
            $check_auto_status  = $this->m_coa->check_auto_status($AccountSubTypeID);            
            $new_account_name   = $check_auto_status ? $AccountName . ' ' . $CurrencyCode : $AccountName;
            $account_level      = $this->m_coa->get_level($AccountParent);
            /*===========================end==============================================================*/
			
            /*
				1. Insert new COA into am_accountgl (adding coa status 6)
			*/
            $account_gl     = array (
                                'AccountSubTypeID'      => $AccountSubTypeID,
                                'AccountNumber'         => $AccountNumber,
                                'AccountName'           => $new_account_name,
                                'CurrencyCode'          => $CurrencyCode,
                                'AccountParent'         => $AccountParent,
                                'AccountLevel'          => $account_level,
                                'BankID'                => NULL,
                                'AccountChild'          => 1,
                                'TransStatus'           => 5,
                                'LastUser'              => $this->session->userdata("username")
                            );

           	$this->m_coa->insert($account_gl);
            /*=======================================end=============================================*/

            /*
				2. Insert new COA into at_compaccountgl for each Company Code
			*/
            foreach($gl_company_data as $row) {
                $glcompany_data = array(
                                    'CompanyCode'       => $row->CompanyCode,
                                    'BranchCode'        => $row->BranchCode,
                                    'AccountNumber'     => $AccountNumber,
									'TransStatus'       => 5,
                                    'GLSaldoYears'      => date('Y')
                                );

               $this->m_compaccountgl->insert($glcompany_data);	
            }
           /*=============================end===========================================================*/
			
			/*===============================trans rol back============================================================*/
			if($this->db->trans_status() == FALSE) {
				$this->db->trans_rollback();
				$result['status']   = false;
                $result['message']  = get_notification_transaksi_master('Chart Of Account', 'insert', 0);
			}
			else {
				$this->db->trans_commit();
				$result['status']   = true;
                $result['message']  = get_notification_transaksi_master('Chart Of Account', 'insert', 1);
			}
			/*========================================end===============================================================*/
        }	
        else{
            $result['status']   = false;
            
            if($check_gl_coa == TRUE){ 
                $result['message']  = "Maaf Pendaftaraan COA Gagal, Nama Akun Tidak Boleh Sama";
            }
            elseif($check_spell == TRUE){
                $result['message']  = "Account Name tidak boleh menggunakan Currency Code : '" . $CurrencyCode . "'";                
            }
            else{
                $result['message']  = "Silahkan pilih Company Name terlebih dahulu'";                                
            } 
        }			

        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)
					*/
					$id         			= $this->uri->segment(4);
					$id_param   			= explode('_', $id);
					$group_menu         	= $this->session->userdata('group_menu');
					
					$data['account_number'] = $id_param[0];
					$data['branch_code']    = $id_param[1];        
					$data['branch_name']    = str_replace('%20', ' ', $id_param[2]);        
					
					$data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
					$data['detail'] 		= $this->m_compaccountgl->get_by_account($id_param[0], $id_param[1]);        
					
					$data['app1']           = $this->app1;
					$data['app2']           = $this->app2;
					
					//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('coa/v_edit_coa', $data);
					$this->load->view('v_footer');	
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
    }	
    
    public function update() {
        try{
            //========= deklar variabel ======================================//
            $branch_code            		= $this->input->post('txt_branch_code');
            $account_number         		= $this->input->post('txt_account_no');
            $account_name 			= $this->input->post('txt_account_name');
            $account_subtype        		= $this->input->post('cmb_account_sub_type');

            $account_subtype_name     		= $this->input->post('txt_sub_type_name');
            $account_type_name        		= $this->input->post('txt_type_name');

            $cbg_currency        		= $this->input->post('cbg_currency');
            $opbalance_status       		= $this->input->post('txt_opbalance_status');
            $bs_status 						= $this->input->post('txt_bs_status');
            $txt_company_code 			= $this->input->post('txt_company_code');
            $opening_balance        		= ($opbalance_status == 1) ? 0 : $this->input->post('txt_opening_balance');
            $txt_saldo_opening 			= $this->input->post('txt_saldo_opening');
            $opening_balance_abs 		= abs($opening_balance);
            $employee_code 			= $this->session->userdata("username");
            $JVchDate 				= date('Y-m-d');
            $dataSend   = [];
            $dataSend['data_coa_update']    = [];
            $dataSend['data_group']         = [];
            $dataSend['data_group_update']  = [];
            $dataSend['data_detail_debet']  = [];
            $dataSend['data_detail_credit'] = [];
            $dataSend['journal_debet']      = [];
            $dataSend['journal_credit']     = [];
            $dataSend['account_subtype']    = $account_subtype;
            $dataSend['account_number']     = $account_number;
            $dataSend['jv_number']          = "";
            //========= end deklar variabel ==================================//

            //========= get lates balance ====================================//
            $dataSend['data_coa_update'] = array (
                'AccountName'       => $account_name,
                'CurrencyCode'      => $cbg_currency,
                'LastUser'          => $this->session->userdata("username")
            );
//            if(($account_subtype != 7)) {//masuk ke model
//                $result_edit = $this->m_coa->update($data, $account_number);
//            }
            //========= end get lates balance ================================//

            //========= bs status 0 = profil losst, 1 = balance sheet ========//
            if($bs_status == 1){
                $data_gl = array (
                    'GLSaldoBSheet'	=> $opening_balance,
                    'LastUserOP'        => $this->session->userdata("username")
                );
            }else{
                $data_gl = array (
                    'GLSaldoOpening'	=> $opening_balance,
                    'LastUserOP'        => $this->session->userdata("username")
                );
            }
            //========= end bs status 0 = profil losst, 1 = balance sheet ====//


            //========= Cek apakah akun yang akan add balance, sudah pernah dibuat dengan openingn balance atau belum, =====//
            //========= jika belum boleh add balance jika sudah tidak boleh add balance                               ======//
            $OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
            if($OpeningBalance == false) {
                throw new Exception(get_notification_preference('journal', 0, 'Opening Balance', ''));
            }                     
            $jv_number    		= $this->m_journalvoucher->create_jv_number_for_add_balance(date('Y-m-d'), $branch_code);
            $currency_code 		= $this->m_currency->get_detail_by_company($cbg_currency, $txt_company_code);
            $dataSend['jv_number']      = $jv_number;
            //======== Insert Group ==========================================//
            $dataSend['data_group'] = array(
                'BranchCode'        => $branch_code,
                'JVchDate' 		    => date('Y-m-d'),
                'JVchNumber' 		=> $jv_number,
                'JVchDesc' 		    => "Opening Balance",
                'JVchTotalDebet' 	=> $opening_balance_abs,
                'JVchTotalCredit' 	=> $opening_balance_abs,
                'JVchType' 		    => 2,
                'AppLevel1Status' 	=> 1,
                'AppLevel1Code' 	=> $employee_code,
                'AppLevel1Date' 	=> date('Y-m-d'),
                'AppLevel2Status' 	=> 1,
                'AppLevel2Code' 	=> $employee_code,
                'AppLevel2Date' 	=> date('Y-m-d'),
                'TransStatus' 		=> 2,
                'LastUser' 		    => $employee_code,
                'CreatedBy' 		=> $employee_code,
                'CreatedAt' 		=> date('Y-m-d')
            );
//            $this->m_journalvoucher->insert($data_group);//masuk ke model
            //======== End Insert Group ======================================//

            //======== Function Cek Opening Blanace ==========================//

            if($opening_balance < 0){
                //$nature_journal     = $this->m_account_journal->debet_kredit($account_type_name, $account_subtype_name);
                // if($nature_journal == "Debet"){
                //         /*jika plusnya di debet dan posisi 
                //           jv ada di debet juga maka masuk kedalam coa ada nambah sign status 0
                //           ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah kurang sign status 1
                //           karna akun number yang akan dimasukan selalu posisi di kredit sign status kurang atau 1
                //           if position == debet
                //                 sign status == 0
                //           else
                //                 sign status == 1
                //         */ 
                //         $sign_status_jv = 1;
                // }else{
                //         /*jika plusnya di kredit dan posisi 
                //           jv ada di debet maka masuk kedalam coa ada kurang sign status 1
                //           ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah nambah sign status 0
                //           karna akun number yang akan dimasukan selalu posisi di kredit sign status nambah atau 0
                //           if position == debet
                //                 sign status == 1
                //           else
                //                 sign status == 0
                //         */ 
                //         $sign_status_jv = 0;
                // }

                $type_acc           = $this->m_account_journal->m_get_account_type($account_number);
                $debet_kredit       = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);
                $dataSend['data_detail_credit'] = array(
                    'JVchNumber'         => $jv_number,
                    'JVchAccount'        => $account_number,
                    'JVchDebetSaldo'     => ($debet_kredit == 'Debet') ? 0:$opening_balance_abs,
                    'JVchCreditSaldo'    => ($debet_kredit == 'Credit') ? 0:$opening_balance_abs,
                    'JVchDetailMemo'     => 'Account From Add Balance COA',
                    'JVchRate'           => $currency_code->CurrencyRate,
                    'CurrencyCode'       => $cbg_currency
                );
//                $this->m_journalvoucher->insert_detail($data_detail_credit);//masuk ke model
                //========= End Insert Detail ================================//

                $dataSend['journal_credit'] = array(
                    'JVchDate'              => $JVchDate,
                    'JVchNumber'            => $jv_number,
                    'JVchAccountNumber'     => $account_number,
                    'JVchSaldoDebet'        => ($debet_kredit == 'Debet') ? 0:$opening_balance_abs * $currency_code->CurrencyRate,
                    'JVchSaldoCredit'       => ($debet_kredit == 'Credit') ? 0:$opening_balance_abs * $currency_code->CurrencyRate,
                    'JVchSignStatus'        => 1,
                    'AmountCurrency'        => $opening_balance_abs,
                    'JVchDesc'              => 'Account Add Balance',
                    'LastUser'              => $employee_code
                );
//              $this->m_journalvoucher->insert_journal($journal_credit);//masuk ke model

                //========= Insert Detail ================================//
                $dataSend['data_detail_debet'] = array(
                    'JVchNumber' 	    => $jv_number,
                    'JVchAccount' 	    => $OpeningBalance->AccountNumber,
                    'JVchDebetSaldo' 	=> ($debet_kredit == 'Debet') ? $opening_balance_abs:0,
                    'JVchCreditSaldo' 	=> ($debet_kredit == 'Credit') ? $opening_balance_abs:0,
                    'JVchDetailMemo' 	=> 'Account Opening Balance Coa',
                    'JVchRate' 		    => $currency_code->CurrencyRate,
                    'CurrencyCode' 	    => $cbg_currency
                );
//                $this->m_journalvoucher->insert_detail($data_detail_debet);//masuk ke model

                //========= Insert Journal ===================================//
                $dataSend['journal_debet'] = array(
                    'JVchDate'              => $JVchDate,
                    'JVchNumber'            => $jv_number,
                    'JVchAccountNumber'     => $OpeningBalance->AccountNumber,
                    'JVchSaldoDebet'        => ($debet_kredit == 'Debet') ? $opening_balance_abs * $currency_code->CurrencyRate:0,
                    'JVchSaldoCredit'       => ($debet_kredit == 'Credit') ? $opening_balance_abs * $currency_code->CurrencyRate:0,
                    'JVchSignStatus'        => ($debet_kredit == 'Debet') ? 1:0,
                    'AmountCurrency'        => $opening_balance_abs,
                    'JVchDesc'              => 'Opening Balance',
                    'LastUser'              => $employee_code
                );
//                $this->m_journalvoucher->insert_journal($journal_debet);//masuk ke model

                //========= Insert Journal ===================================//
            }else{
                $OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
                if($OpeningBalance == false) {$this->trans_rollback_add_balance('journal','Opening Balance', '');} 

                $type_acc       = $this->m_account_journal->m_get_account_type($account_number);
                $debet_kredit   = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);
                $dataSend['data_detail_debet'] = array(
                    'JVchNumber' 	     => $jv_number,
                    'JVchAccount' 	     => $account_number,
                    'JVchDebetSaldo' 	 => ($debet_kredit == 'Debet') ? $opening_balance_abs:0,
                    'JVchCreditSaldo' 	 => ($debet_kredit == 'Credit') ? $opening_balance_abs:0,
                    'JVchDetailMemo' 	 => 'Account From Add Balance COA',
                    'JVchRate' 		     => $currency_code->CurrencyRate,
                    'CurrencyCode' 	     => $cbg_currency
                );
//                $this->m_journalvoucher->insert_detail($data_detail_debet);//masuk ke model

                $dataSend['journal_debet'] = array(
                    'JVchDate'          => $JVchDate,
                    'JVchNumber'        => $jv_number,
                    'JVchAccountNumber' => $account_number,
                    'JVchSaldoDebet'    => ($debet_kredit == 'Debet') ? $opening_balance_abs * $currency_code->CurrencyRate:0,
                    'JVchSaldoCredit'   => ($debet_kredit == 'Credit') ? $opening_balance_abs * $currency_code->CurrencyRate:0,
                    'JVchSignStatus'    => 0,
                    'AmountCurrency'    => $opening_balance_abs,
                    'JVchDesc'          => 'Account Add Balance',
                    'LastUser'          => $employee_code
                );
//                $this->m_journalvoucher->insert_journal($journal_debet);//masuk ke model

                // $nature_journal 	= $this->m_account_journal->debet_kredit($account_type_name, $account_subtype_name);
                // if($nature_journal == "Debet"){
                //         jika plusnya di debet dan posisi 
                //           jv ada di debet juga maka masuk kedalam coa ada nambah sign status 0
                //           ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah kurang sign status 1
                //           karna akun number yang akan dimasukan selalu posisi di debet sign status kurang atau 0
                //           if position == debet
                //                 sign status == 0
                //           else
                //                 sign status == 1
                         
                //     $sign_status_jv = 0;
                // }
                // else{
                //         /*jika plusnya di kredit dan posisi 
                //           jv ada di debet maka masuk kedalam coa ada kurang sign status 1
                //           ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah nambah sign status 0
                //           karna akun number yang akan dimasukan selalu posisi di debet sign status kurang atau 1
                //           if position == debet
                //                 sign status == 1
                //           else
                //                 sign status == 0
                //         */ 
                //     $sign_status_jv = 1;
                // }
                /*================================End============================================*/
                $dataSend['data_detail_credit'] = array(
                    'JVchNumber'        => $jv_number,
                    'JVchAccount'       => $OpeningBalance->AccountNumber,
                    'JVchDebetSaldo'    => ($debet_kredit == 'Debet') ? 0:$opening_balance_abs,
                    'JVchCreditSaldo'   => ($debet_kredit == 'Credit') ? 0:$opening_balance_abs,
                    'JVchDetailMemo'    => 'Account Opening Balance Coa',
                    'JVchRate'          => $currency_code->CurrencyRate,
                    'CurrencyCode'      => $cbg_currency
                );
//                $this->m_journalvoucher->insert_detail($data_detail_credit);

                /*=======================Insert Journal==========================================*/
                $dataSend['journal_credit'] = array(
                    'JVchDate' 			=> $JVchDate,
                    'JVchNumber' 		=> $jv_number,
                    'JVchAccountNumber' => $OpeningBalance->AccountNumber,
                    'JVchSaldoDebet'    => ($debet_kredit == 'Debet') ? 0:$opening_balance_abs * $currency_code->CurrencyRate,
                    'JVchSaldoCredit'   => ($debet_kredit == 'Credit') ? 0:$opening_balance_abs * $currency_code->CurrencyRate,
                    'JVchSignStatus'    => ($debet_kredit == 'Debet') ? 0:1,
                    'AmountCurrency'    => $opening_balance_abs,
                    'JVchDesc' 			=> 'Opening Balance',
                    'LastUser' 			=> $employee_code
                );
//                $this->m_journalvoucher->insert_journal($journal_credit);//masuk ke model
            }            
            //======== End Function Cek Opening Blanace ======================//
            $dataSend['data_group_update'] = array(
                'AppFinished' => 1
            );
//            $this->m_journalvoucher->update($update_data_group, $jv_number);//masuk ke model          
            //========= End Cek apakah akun yang akan add balance, sudah pernah dibuat dengan openingn balance atau belum ======//

            $rstDataSend = $this->m_coa->datasend_coa_update($dataSend);
            if($rstDataSend){
                $result['status'] 	= true;
                $result['message']	= get_notification_transaksi_master('Chart Of Account', 'update', 1);  
                
                $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
                $result['number']       = $account_number;
            }else{
                $result['status'] 	= false;
                $result['message']	= get_notification_transaksi_master('Chart Of Account', 'update', 0);
            }
            echo json_encode($result);
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
            
    }

    public function update_LAMA() {
       	/*====================================deklar variabel=====================================================*/
	    $branch_code            		= $this->input->post('txt_branch_code');
        $account_number         		= $this->input->post('txt_account_no');
        $account_name 					= $this->input->post('txt_account_name');
        $account_subtype        		= $this->input->post('cmb_account_sub_type');
		
		$account_subtype_name     		= $this->input->post('txt_sub_type_name');
		$account_type_name        		= $this->input->post('txt_type_name');
		
		$cbg_currency        			= $this->input->post('cbg_currency');
        $opbalance_status       		= $this->input->post('txt_opbalance_status');
		$bs_status 						= $this->input->post('txt_bs_status');
		$txt_company_code 				= $this->input->post('txt_company_code');
        $opening_balance        		= ($opbalance_status == 1) ? 0 : $this->input->post('txt_opening_balance');
		$txt_saldo_opening 				= $this->input->post('txt_saldo_opening');
		$opening_balance_abs 			= abs($opening_balance);
		$employee_code 					= $this->session->userdata("username");
		$JVchDate 						= date('Y-m-d');
        /*=========================================end==========================================================*/
		
		//get lates balance
		$data = array (
			'AccountName'       => $account_name,
			'CurrencyCode'      => $cbg_currency,
			'LastUser'          => $this->session->userdata("username")
		);
		
		/*
			bs status 0 = profil losst, 1 = balance sheet
		*/
		if($bs_status == 1){
			$data_gl = array (
				'GLSaldoBSheet'		=> $opening_balance,
				'LastUserOP'        => $this->session->userdata("username")
			);
		}
		else{
			$data_gl = array (
				'GLSaldoOpening'	=> $opening_balance,
				'LastUserOP'        => $this->session->userdata("username")
			);
		}
		
							
        $this->db->trans_begin();

        if(($account_subtype != 7)) {
            $result_edit = $this->m_coa->update($data, $account_number);
        }
		
		/*=========================update opening balance===================================================*/
        //$result_edit 		= $this->m_compaccountgl->update_opbalance($data_gl, $account_number, $branch_code); 
		/*===============================end================================================================*/			
		
		/*
			Insert Jv Balance
		*/
		
		/*
			Cek apakah akun yang akan add balance, sudah pernah dibuat dengan openingn balance atau belum
			jika belum boleh add balance jika sudah tidak boleh add balance 
		*/
		$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
		if($OpeningBalance == false) {$this->trans_rollback_add_balance('journal','Opening Balance', '');} 
			
		/*$get_journal_voucher = $this->m_journalvoucher->get_journal_voucher();
		if(){
		
		}*/
		
		$jv_number    		= $this->m_journalvoucher->create_jv_number_for_add_balance(date('Y-m-d'), $branch_code);
		$currency_code 		= $this->m_currency->get_detail_by_company($cbg_currency, $txt_company_code);
		
		/*
			Insert Group
		*/
		$data_group = array(
			'BranchCode' 		=> $branch_code,
			'JVchDate' 			=> date('Y-m-d'),
			'JVchNumber' 		=> $jv_number,
			'JVchDesc' 			=> "Opening Balance",
			'JVchTotalDebet' 	=> $opening_balance_abs,
			'JVchTotalCredit' 	=> $opening_balance_abs,
			'JVchType' 			=> 2,
			'AppLevel1Status' 	=> 1,
			'AppLevel1Code' 	=> $employee_code,
			'AppLevel1Date' 	=> date('Y-m-d'),
			'AppLevel2Status' 	=> 1,
			'AppLevel2Code' 	=> $employee_code,
			'AppLevel2Date' 	=> date('Y-m-d'),
			'TransStatus' 		=> 2,
			'LastUser' 			=> $employee_code,
			'CreatedBy' 		=> $employee_code,
			
			'CreatedAt' 		=> date('Y-m-d')
		);
		
		$this->m_journalvoucher->insert($data_group);
		/*========================End==================================================================*/
		
		/*
			Function Cek Opening Blanace
		*/
		if($opening_balance < 0){
			//ini plusnya di kredit
			/*======================Insert Detail==========================================*/
			$data_detail_debet = array(
				'JVchNumber' 		=> $jv_number,
				'JVchAccount' 		=> $OpeningBalance->AccountNumber,
				'JVchDebetSaldo' 	=> $opening_balance_abs,
				'JVchCreditSaldo' 	=> 0,
				'JVchDetailMemo' 	=> 'Account Opening Balance Coa',
				'JVchRate' 			=> $currency_code->CurrencyRate,
				'CurrencyCode' 		=> $cbg_currency
			);
			$this->m_journalvoucher->insert_detail($data_detail_debet);
			
			$data_detail_credit = array(
				'JVchNumber' 		=> $jv_number,
				'JVchAccount' 		=> $account_number,
				'JVchDebetSaldo' 	=> 0,
				'JVchCreditSaldo' 	=> $opening_balance_abs,
				'JVchDetailMemo' 	=> 'Account From Add Balance COA',
				'JVchRate' 			=> $currency_code->CurrencyRate,
				'CurrencyCode' 		=> $cbg_currency
			);
			$this->m_journalvoucher->insert_detail($data_detail_credit);
			/*=================================End===========================================*/
			
			/*=======================Insert Journal==========================================*/
			$journal_debet = array(
				'JVchDate' 				=> $JVchDate,
				'JVchNumber' 			=> $jv_number,
				'JVchAccountNumber' 	=> $OpeningBalance->AccountNumber,
				'JVchSaldoDebet' 		=> $opening_balance_abs * $currency_code->CurrencyRate,
				'JVchSaldoCredit'  		=> 0,
				'JVchSignStatus' 		=> 1,
				'AmountCurrency' 		=> $opening_balance_abs,
			    'JVchDesc' 				=> 'Opening Balance',
				'LastUser' 				=> $employee_code
			);
			$this->m_journalvoucher->insert_journal($journal_debet);
			
			$nature_journal 	= $this->m_account_journal->debet_kredit($account_type_name, $account_subtype_name);
			if($nature_journal == "Debet"){
				/*jika plusnya di debet dan posisi 
				  jv ada di debet juga maka masuk kedalam coa ada nambah sign status 0
				  ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah kurang sign status 1
				  karna akun number yang akan dimasukan selalu posisi di kredit sign status kurang atau 1
				  if position == debet
				  	sign status == 0
				  else
				  	sign status == 1
				*/ 
				$sign_status_jv = 1;
			}
			else{
				/*jika plusnya di kredit dan posisi 
				  jv ada di debet maka masuk kedalam coa ada kurang sign status 1
				  ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah nambah sign status 0
				  karna akun number yang akan dimasukan selalu posisi di kredit sign status nambah atau 0
				  if position == debet
				  	sign status == 1
				  else
				  	sign status == 0
				*/ 
				$sign_status_jv = 0;
			}
			
			$journal_credit = array(
				'JVchDate' 				=> $JVchDate,
				'JVchNumber' 			=> $jv_number,
				'JVchAccountNumber' 	=> $account_number,
				'JVchSaldoDebet' 		=> 0,
				'JVchSaldoCredit'  		=> $opening_balance_abs * $currency_code->CurrencyRate,
				'JVchSignStatus' 		=> $sign_status_jv,
				'AmountCurrency' 		=> $opening_balance_abs,
			    'JVchDesc' 				=> 'Account Add Balance',
				'LastUser' 				=> $employee_code
			);
			$this->m_journalvoucher->insert_journal($journal_credit);
			/*================================End============================================*/
		}
		else{
			$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
			if($OpeningBalance == false) {$this->trans_rollback_add_balance('journal','Opening Balance', '');} 
			
			$data_detail_debet = array(
				'JVchNumber' 		=> $jv_number,
				'JVchAccount' 		=> $account_number,
				'JVchDebetSaldo' 	=> $opening_balance_abs,
				'JVchCreditSaldo' 	=> 0,
				'JVchDetailMemo' 	=> 'Account From Add Balance COA',
				'JVchRate' 			=> $currency_code->CurrencyRate,
				'CurrencyCode' 		=> $cbg_currency
			);
			$this->m_journalvoucher->insert_detail($data_detail_debet);
			
			$data_detail_credit = array(
				'JVchNumber' 		=> $jv_number,
				'JVchAccount' 		=> $OpeningBalance->AccountNumber,
				'JVchDebetSaldo' 	=> 0,
				'JVchCreditSaldo' 	=> $opening_balance_abs,
				'JVchDetailMemo' 	=> 'Account Opening Balance Coa',
				'JVchRate' 			=> $currency_code->CurrencyRate,
				'CurrencyCode' 		=> $cbg_currency
			);
			$this->m_journalvoucher->insert_detail($data_detail_credit);
			
			$nature_journal 	= $this->m_account_journal->debet_kredit($account_type_name, $account_subtype_name);
			if($nature_journal == "Debet"){
				/*jika plusnya di debet dan posisi 
				  jv ada di debet juga maka masuk kedalam coa ada nambah sign status 0
				  ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah kurang sign status 1
				  karna akun number yang akan dimasukan selalu posisi di debet sign status kurang atau 0
				  if position == debet
				  	sign status == 0
				  else
				  	sign status == 1
				*/ 
				$sign_status_jv = 0;
			}
			else{
				/*jika plusnya di kredit dan posisi 
				  jv ada di debet maka masuk kedalam coa ada kurang sign status 1
				  ,dan jika posisi jv ada di kredit maka masuk kedalam coa adalah nambah sign status 0
				  karna akun number yang akan dimasukan selalu posisi di debet sign status kurang atau 1
				  if position == debet
				  	sign status == 1
				  else
				  	sign status == 0
				*/ 
				$sign_status_jv = 1;
			}
			
			$journal_debet = array(
				'JVchDate' 				=> $JVchDate,
				'JVchNumber' 			=> $jv_number,
				'JVchAccountNumber' 	=> $account_number,
				'JVchSaldoDebet' 		=> $opening_balance_abs * $currency_code->CurrencyRate,
				'JVchSaldoCredit'  		=> 0,
				'JVchSignStatus' 		=> $sign_status_jv,
				'AmountCurrency' 		=> $opening_balance_abs,
			    'JVchDesc' 				=> 'Account Add Balance',
				'LastUser' 				=> $employee_code
			);
			$this->m_journalvoucher->insert_journal($journal_debet);
			/*================================End============================================*/
			
			/*=======================Insert Journal==========================================*/
			$journal_credit = array(
				'JVchDate' 				=> $JVchDate,
				'JVchNumber' 			=> $jv_number,
				'JVchAccountNumber' 	=> $OpeningBalance->AccountNumber,
				'JVchSaldoDebet' 		=> 0,
				'JVchSaldoCredit'  		=> $opening_balance_abs * $currency_code->CurrencyRate,
				'JVchSignStatus' 		=> 0,
				'AmountCurrency' 		=> $opening_balance_abs,
			    'JVchDesc' 				=> 'Opening Balance',
				'LastUser' 				=> $employee_code
			);
			$this->m_journalvoucher->insert_journal($journal_credit);
		}
		
		$update_data_group = array(
			'AppFinished' => 1
		);
		
		$this->m_journalvoucher->update($update_data_group, $jv_number);
		/*===================================ENd===============================================================*/
		
		
		/*=============================================================trans roll back==============================*/
        if($this->db->trans_status() == FALSE) {
            $this->db->trans_rollback();
            $result['status']       = false;
            $result['message']      = get_notification_transaksi_master('Chart Of Account', 'update', 0);
        }
        else {
            $this->db->trans_commit();
            $result['status']       = true;
            $result['message']      = get_notification_transaksi_master('Chart Of Account', 'update', 1);

            $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
            $result['number']       = $account_number;
        }
		/*======================================================end=====================================================*/

        echo json_encode($result);
    }	
	
    public function delete() {
        try{
            $id 			= $this->input->post('id');
            $company_code 		= $this->session->userdata("company");
            $branch_code 		= $this->session->userdata("branch");
            $result_data 		= 0;
            $detail 			= $this->input->post('detail');
            $detail			= json_decode($detail);
            $detail 			= array($detail);
            $dataSend   = [];
            $dataSend['opening_balance']    = [];
            $dataSend['bank']               = [];
            $dataSend['if']                 = 0;

            //proses data
            foreach($detail as $row_data){
                //cek status by name dari helper
                $type_name 		= $row_data->AccountTypeName;
                $BSStatus 		= $row_data->AccountBSStatus;
                $AccountAutoStatus 	= $row_data->AccountAutoStatus;
                $AccountNameShow 	= $row_data->AccountNameShow;
                $AccountName 		= $row_data->AccountName;

                if($row_data->Status == "Finished"){
                    $dataSend['if'] = 1;
                    //jika trans status coa 2 maka lakukan proses dibawah ini
                    $dataSend['opening_balance'] = $this->cek_opening_balance($id, $company_code, $branch_code, $BSStatus, $AccountAutoStatus, $AccountName);
                    //end proses trans status 2
                }
                else{
                    $dataSend['if'] = 0;
                    //jika trans status == 4569 maka lakukan proses ini dan jadikan bank id null
                    $dataSend['bank'] = $this->cek_bank_id($company_code, $id, $type_name, $branch_code);
                    //end proses 4569
                }
            }
		
            $rstDataSend = $this->m_coa->datasend_coa_suspend($dataSend);
            if($rstDataSend){
                $result['status'] 	= true;
                $result['message']	= get_notification('suspend', 1);                
            }else{
                $result['status'] 	= false;
                $result['message']	= get_notification('suspend', 0);
            }
            echo json_encode($result);
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    public function delete_LAMA() {
		$id 				= $this->input->post('id');
		
		$company_code 		= $this->session->userdata("company");
		$branch_code 		= $this->session->userdata("branch");
		$result_data 		= 0;
		
		$detail 			= $this->input->post('detail');
		$detail				= json_decode($detail);
		$detail 			= array($detail);
		
		$this->db->trans_begin();
		//proses data
		foreach($detail as $row_data){
			//cek status by name dari helper
			$type_name 			= $row_data->AccountTypeName;
			$BSStatus 			= $row_data->AccountBSStatus;
			$AccountAutoStatus 	= $row_data->AccountAutoStatus;
			$AccountNameShow 	= $row_data->AccountNameShow;
			$AccountName 		= $row_data->AccountName;
			
			if($row_data->Status == "Finished"){
				//jika trans status coa 2 maka lakukan proses dibawah ini
				$this->cek_opening_balance($id, $company_code, $branch_code, $BSStatus, $AccountAutoStatus, $AccountName);
				//end proses trans status 2
			}
			else{
				//jika trans status == 4569 maka lakukan proses ini dan jadikan bank id null
				$this->cek_bank_id($company_code, $id, $type_name, $branch_code);
				//end proses 4569
			}
		}
		
		/*=============================================================trans roll back==============================*/
        if($this->db->trans_status() == FALSE) {
            $this->db->trans_rollback();
            $result['status']   = false;
            $result['message']  = get_notification('suspend', 0);
        }
        else {
            $this->db->trans_commit();
            $result['status']  = true;
           $result['message']  = get_notification('suspend', 1);
        }
		/*======================================================end=====================================================*/
		
		echo json_encode($result);
    }
    
    function import_DIDIK(){	
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //memory limit as string

            $account_number_column_config = array ('B','C','D','E','F','G','H','I','J');
            $dataSend   = [];
            $dataSend['data_insert']    = [];

            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            if($filename!=""&&$filename!=null){
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
//                PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData      = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                
                if( (notCaseSensitifNotSpace($sheetData[4]['A'])==notCaseSensitifNotSpace("Account Name"))  &&  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Account Name"
                    (notCaseSensitifNotSpace($sheetData[4]['K'])==notCaseSensitifNotSpace("Account Type"))  &&  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Account Type"
                    (notCaseSensitifNotSpace($sheetData[4]['L'])==notCaseSensitifNotSpace("Account Sub Type"))  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Account Sub Type"  
                ){
                    for($i=5; $i <= count($sheetData); $i++){
                        if( (notCaseSensitifNotSpace($sheetData[$i]['A'])==""||notCaseSensitifNotSpace($sheetData[$i]['A'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['B'])==""||notCaseSensitifNotSpace($sheetData[$i]['B'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['C'])==""||notCaseSensitifNotSpace($sheetData[$i]['C'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['D'])==""||notCaseSensitifNotSpace($sheetData[$i]['D'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['E'])==""||notCaseSensitifNotSpace($sheetData[$i]['E'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['F'])==""||notCaseSensitifNotSpace($sheetData[$i]['F'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['G'])==""||notCaseSensitifNotSpace($sheetData[$i]['G'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['H'])==""||notCaseSensitifNotSpace($sheetData[$i]['H'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['I'])==""||notCaseSensitifNotSpace($sheetData[$i]['I'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['J'])==""||notCaseSensitifNotSpace($sheetData[$i]['J'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['K'])==""||notCaseSensitifNotSpace($sheetData[$i]['K'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['L'])==""||notCaseSensitifNotSpace($sheetData[$i]['L'])==null) &&
                            (notCaseSensitifNotSpace($sheetData[$i]['M'])==""||notCaseSensitifNotSpace($sheetData[$i]['M'])==null)
                        ){
                            //KLO KOSONG SEMUA DIANGGAP BARIS KOSONG
                        }else{
                            for($x=0; $x <= count($account_number_column_config); $x++){
                                $AccountName    = $sheetData[$i][$account_number_column_config[$x]];						 
                                if($AccountName != "") break;
                            }

                            if ($account_number_column_config[$x] == 'B'){
                                $AccountParent = "";
                            }
                            else{
                                $CurrentRow     = $i-1;
                                $AccountParent  = $sheetData[$CurrentRow][$account_number_column_config[$x+-1]];
                                while($AccountParent == ""){
                                    $CurrentRow--;
                                    $AccountParent = $sheetData[$CurrentRow][$account_number_column_config[$x-1]];
                                }
                            }
                            //echo $AccountParent.'<br>';
                            
                            $AccountParent          = $this->m_coa->get_by_name($AccountParent);
                            $AccountNumber          = $this->m_coa->create_account_number($AccountParent);//masuk ke model, karena nomornya yg didapat sifatnya uniqe 
                            $AccountSubTypeName     = $sheetData[$i]['L'];
                            $CurrencyCode           = $sheetData[$i]['M'];
                            $AccountSubTypeID       = $this->m_coa->get_subtype_id($AccountSubTypeName);
                            $get_account_by_name    = $this->m_coa->get_account_name($AccountName);
                            //throw new Exception("AccountParent = ".$AccountParent.";  AccountName=".$AccountName);

                            if(!empty($get_account_by_name->AccountName)){
                                throw new Exception("Upload gagal, nama akun ".$get_account_by_name->AccountName." sudah tersedia di coa master");
                            }
                            else if($AccountSubTypeID == false){
                                throw new Exception("$AccountName Import gagal, sub type $AccountSubTypeName tidak ditemukan");
                            }
                            else if($CurrencyCode != 'IDR'){
                                throw new Exception(''.$AccountName.' Import gagal, Tidak bisa memasukan data Currency '.$CurrencyCode.'');
                            }
                            else{
                                $dataSend['data_insert'][]  = array(
                                    'AccountNumber'         => $AccountNumber,
                                    'AccountName'           => $AccountName,
                                    'AccountSubTypeID'      => $AccountSubTypeID->AccountSubTypeID,
                                    'AccountLevel'          => $this->m_coa->get_level($AccountParent),
                                    'AccountParent'         => $AccountParent,
                                    'AccountChild'          => 1,
                                    'CurrencyCode'          => 'IDR',
                                    'AppLevel1Status'       => 1,
                                    'AppLevel1Code'         => $this->session->userdata("username"),
                                    'AppLevel2Status'       => 1,
                                    'AppLevel2Code'         => $this->session->userdata("username"),
                                    'TransStatus'           => 2,
                                    'LastUser'              => $this->session->userdata('username')
                                );    
								                            
                                //$this->m_coa->insert($data);//ke model
                                //$this->m_coa->update_parent($AccountParent, $AccountSubTypeName);//ga perlu lagi karena di dalam $this->m_coa->insert() sudah terdapat update nya
                            }
                        }
                    }
                    $rstDataSend = $this->m_coa->datasend_coa_import($dataSend);
                    if($rstDataSend){
                        $result['status'] 	= true;
                        $result['message']	= 'Import berhasil, untuk menambahkan akun ke company masing-masing silahkan klik tombol Company COA';            
                    }else{
                        $result['status'] 	= false;
                        $result['message']	= 'Import gagal, tidak bisa upload data coa, silahkan cek file anda';
                    }
                    echo json_encode($result);
                }else{
                    throw new Exception(noticesImport("header",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }
            }else{
                throw new Exception(noticesImport("not_choose",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
            }
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    function import(){	
//        if($this->m_coa->get_all_num_rows() > 0){ 
//            redirect("login", "refresh");
//            die;		
//        }	

        ini_set("max_execution_time", 'time_limit');
        ini_set('memory_limit', '1024M'); //memory limit as string
        
        $account_number_column_config = array ('B','C','D','E','F','G','H','I','J');

        include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
        $filename = $_FILES['uploadfile']['tmp_name'];
	
        $objPHPExcel    = PHPExcel_IOFactory::load($filename);
        PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        
        $objPHPExcel->setActiveSheetIndex(0);
        $sheetData      = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        $this->db->trans_begin();
        
        for($i=5; $i <= count($sheetData); $i++){
            for($x=0; $x <= count($account_number_column_config); $x++){
                $AccountName    = $sheetData[$i][$account_number_column_config[$x]];						 
                if($AccountName != "") break;
            }
            
            if ($account_number_column_config[$x] == 'B'){
				$AccountParent = "";
            }
            else{
				
                $CurrentRow     = $i-1;
                $AccountParent  = $sheetData[$CurrentRow][$account_number_column_config[$x+-1]];				

                while($AccountParent == ""){
                    $CurrentRow--;
                    $AccountParent = $sheetData[$CurrentRow][$account_number_column_config[$x-1]];
                }
            }
            //echo $AccountParent.'<br>';
			$AccountParent          = $this->m_coa->get_by_name($AccountParent);
            $AccountNumber          = $this->m_coa->create_account_number($AccountParent);
            $AccountSubTypeName     = $sheetData[$i]['L'];
			$CurrencyCode     		= $sheetData[$i]['M'];
            $AccountSubTypeID       = $this->m_coa->get_subtype_id($AccountSubTypeName);
			
			$get_account_by_name     = $this->m_coa->get_account_name($AccountName);
     
            if(!empty($get_account_by_name->AccountName)){
                $result['status']   = false;
                $result['message']  = "Upload gagal, nama akun ".$get_account_by_name->AccountName." sudah tersedia di coa master";	
                $this->db->trans_rollback();
                echo json_encode($result);
                die;			   
            }
			else if($AccountSubTypeID == false){
                $result['status']   = false;
                $result['message']  = "$AccountName Import gagal, sub type $AccountSubTypeName tidak ditemukan";	
                $this->db->trans_rollback();
                echo json_encode($result);
                die;			   
            }
			else if($CurrencyCode != 'IDR'){
                $result['status']   = false;
                $result['message']  = ''.$AccountName.' Import gagal, Tidak bisa memasukan data Currency '.$CurrencyCode.'';	
                $this->db->trans_rollback();
                echo json_encode($result);
                die;
			}
            else{
				
                $data  = array(
                            'AccountNumber'         => $AccountNumber,
                            'AccountName'           => $AccountName,
                            'AccountSubTypeID'      => $AccountSubTypeID->AccountSubTypeID,
                            'AccountLevel'          => $this->m_coa->get_level($AccountParent),
                            'AccountParent'         => $AccountParent,
                            'AccountChild'          => 1,
                            'CurrencyCode'          => 'IDR',
                            'AppLevel1Status'       => 1,
                            'AppLevel1Code'         => $this->session->userdata("username"),
                            'AppLevel2Status'       => 1,
                            'AppLevel2Code'         => $this->session->userdata("username"),
                            'TransStatus'           => 2,
                            'LastUser'              => $this->session->userdata('username')
                        );				
                
               $this->m_coa->insert($data);
			   $this->m_coa->update_parent($AccountParent, $AccountSubTypeName);
            }
           
        }
		
		/*=============================================================trans roll back==============================*/
        if($this->db->trans_status() == FALSE) {
            $this->db->trans_rollback();
            $result['status']   = false;
            $result['message'] = 'Import gagal, tidak bisa upload data coa, silahkan cek file anda';
        }
        else {
            $this->db->trans_commit();
            $result['status']  = true;
           	$result['message'] = 'Import berhasil, untuk menambahkan akun ke company masing-masing silahkan klik tombol Company COA';
        }	
		
        echo json_encode($result);
		/*======================================================end=====================================================*/
       
    }
	
    public function to_preview(){
        $data['list'] 		= $this->m_compaccountgl->get_all();
        $data['CompanyName']	= $this->CompanyName;
        
        $this->load->view('v_header');
        $this->load->view('coa/v_preview_coa', $data);	
        $this->load->view('v_footer');	
    }

    public function to_print(){	
        $data['list'] 		= $this->m_compaccountgl->get_all();
        $data['CompanyName']	= $this->CompanyName;
        
        $this->load->view('v_header');
        $this->load->view('coa/v_print_coa', $data);	
        $this->load->view('v_footer');		
    }
	
    public function company_coa(){
        $data['menu_id']        = $this->menu_id;
        $data['coa_num_rows']   = $this->m_coa->get_all_num_rows();
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);

        $this->load->view('v_header');
        $this->load->view('coa/v_company_coa',$data);
        $this->load->view('v_footer');
    }
        
    public function insert_companygl(){
        try{
            $selected_coa       = $this->input->post('selected_coa');
            $selected_company   = $this->input->post('selected_company');
            $result_insert      = 0;
            $coa_selected       = json_decode($selected_coa);
            $company_selected   = json_decode($selected_company);
            $dataSend   = [];
            $dataSend['data_compaccountgl'] = [];
            $dataSend['update_compaccountgl'] = [];

            if(count($coa_selected) > 0 && count($company_selected) > 0) {
                foreach($coa_selected as $rowcoa){
                    foreach($company_selected as $rowcompany){
                        $get_by_branch = $this->m_branchinfo->get_branch_by_company_code($rowcompany->CompanyCode);
                        foreach($get_by_branch as $row_branch){
                            $sub_type_id = $rowcoa->AccountSubTypeID;
                            $compaccountgl = array(//
                                'CompanyCode'       => $rowcompany->CompanyCode,
                                'BranchCode'        => $row_branch->BranchCode,
                                'AccountNumber'     => $rowcoa->AccountNumber,
                                'GLSaldoYears'      => date('Y'),
                                'GLSaldoBalance1'   => 0,
                                'GLSaldoBalance2'   => 0,
                                'GLSaldoBalance3'   => 0,
                                'GLSaldoBalance4'   => 0,
                                'GLSaldoBalance5'   => 0,
                                'GLSaldoBalance6'   => 0,
                                'GLSaldoBalance7'   => 0,
                                'GLSaldoBalance8'   => 0,
                                'GLSaldoBalance9'   => 0,
                                'GLSaldoBalance10'  => 0,
                                'GLSaldoBalance11'  => 0,
                                'GLSaldoBalance12'  => 0,
                                'PLStatus'          => 1,
                                'TransStatus'       => 2								
                            );

                            if($this->m_compaccountgl->check_if_exist($rowcoa->AccountNumber, $rowcompany->CompanyCode,$row_branch->BranchCode, date('Y')) == 0) {
                                //insert company
                                if($rowcoa->AccountChild == 0){
                                    if($row_branch->BranchStatus == 0){
//                                        $result_insert = $this->m_compaccountgl->insert($compaccountgl);//masuk ke model
                                        $dataSend['data_compaccountgl'][] = $compaccountgl;
                                    }
                                }
                                else{
//                                    $result_insert = $this->m_compaccountgl->insert($compaccountgl);//masuk ke model
                                     $dataSend['data_compaccountgl'][] = $compaccountgl;
                                }
                            }
                            else{
                                $cek_data_suspend_in_commac_gl = $this->m_compaccountgl->check_if_exist_suspend($rowcoa->AccountNumber, $row_branch->BranchCode);
                                if($cek_data_suspend_in_commac_gl == 1){
//                                    $this->m_compaccountgl->update_company_coa($rowcoa->AccountNumber, $row_branch->BranchCode);//masuk ke model
                                    $dataSend['update_compaccountgl'][] = array(
                                        'AccountNumber' => $rowcoa->AccountNumber,
                                        'BranchCode'    => $row_branch->BranchCode
                                    );
                                }
                                else{
                                    throw new Exception('Company G/L Account gagal ditambahkan, karena Account sudah tersedia');
                                }
                            }
                        }
                    }
                }

                $rstDataSend = $this->m_coa->datasend_coa_companygl_insert($dataSend);
                if($rstDataSend){
                    $result['status'] 	= true;
                    $result['message']	= 'Company G/L Account sudah berhasil ditambahkan';                
                }else{
                    $result['status'] 	= false;
                    $result['message']	= 'Company G/L Account gagal ditambahkan, cek kembali form anda';
                }
                echo json_encode($result);
            }
            else{
                throw new Exception('Company G/L Account gagal ditambahkan, pastikan G/L Account dan Company sudah diplih dengan benar');
            }
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    public function insert_companygl_LAMA(){
        $selected_coa       = $this->input->post('selected_coa');
        $selected_company   = $this->input->post('selected_company');
        $result_insert      = 0;
        
        $result['status']   = false;
        $result['message']  = 'Silahkan Pilih G/L Account dan Company';

        $coa_selected       = json_decode($selected_coa);
        $company_selected   = json_decode($selected_company);
		
        if(count($coa_selected) > 0 && count($company_selected) > 0) {
			$this->db->trans_begin();
            foreach($coa_selected as $rowcoa){
                foreach($company_selected as $rowcompany){
					$get_by_branch = $this->m_branchinfo->get_branch_by_company_code($rowcompany->CompanyCode);
					foreach($get_by_branch as $row_branch){
						$sub_type_id = $rowcoa->AccountSubTypeID;
						$compaccountgl = array(
											'CompanyCode'       => $rowcompany->CompanyCode,
											'BranchCode'        => $row_branch->BranchCode,
											'AccountNumber'     => $rowcoa->AccountNumber,
											'GLSaldoYears'      => date('Y'),
											'GLSaldoBalance1'   => 0,
											'GLSaldoBalance2'   => 0,
											'GLSaldoBalance3'   => 0,
											'GLSaldoBalance4'   => 0,
											'GLSaldoBalance5'   => 0,
											'GLSaldoBalance6'   => 0,
											'GLSaldoBalance7'   => 0,
											'GLSaldoBalance8'   => 0,
											'GLSaldoBalance9'   => 0,
											'GLSaldoBalance10'  => 0,
											'GLSaldoBalance11'  => 0,
											'GLSaldoBalance12'  => 0,
											'PLStatus' 			=> 1,
											'TransStatus'  		=> 2								
										);
						
						if($this->m_compaccountgl->check_if_exist($rowcoa->AccountNumber, $rowcompany->CompanyCode,$row_branch->BranchCode, date('Y')) == 0) {
							//insert company
							if($rowcoa->AccountChild == 0){
								if($row_branch->BranchStatus == 0){
									$result_insert = $this->m_compaccountgl->insert($compaccountgl);
								}
							}
							else{
								$result_insert = $this->m_compaccountgl->insert($compaccountgl);
							}
						}
						else{
							$cek_data_suspend_in_commac_gl = $this->m_compaccountgl->check_if_exist_suspend($rowcoa->AccountNumber, $row_branch->BranchCode);
							if($cek_data_suspend_in_commac_gl == 1){
								$this->m_compaccountgl->update_company_coa($rowcoa->AccountNumber, $row_branch->BranchCode);
								
							}
							else{
								$result['status']  = false;			
								$result['message'] = 'Company G/L Account gagal ditambahkan, karena Account sudah tersedia';
								
								echo json_encode($result);
								die();
							}
						}
					}
                }
            }

            if ($this->db->trans_status() == FALSE) {
                $this->db->trans_rollback();
				$result['status']  = false;			
                $result['message'] = 'Company G/L Account gagal ditambahkan, cek kembali form anda';
            }
            else {
                $this->db->trans_commit();
				$result['status']  = true;
                $result['message'] = 'Company G/L Account sudah berhasil ditambahkan';			
            }		
        }
        else{
            $result['status']  = false;
            $result['message'] = 'Company G/L Account gagal ditambahkan, pastikan G/L Account dan Company sudah diplih dengan benar';            
        }
        echo json_encode($result);
    }

    public function insert_branch_pl_account(){
        $company_code           = $this->session->userdata('company');
        $selected_pl_account    = $this->input->post('selected_pl_account');
        $selected_branch        = $this->input->post('selected_branch');

        $result['status'] = false;
        $result['message'] = 'Silahkan Pilih P/L Account dan Company Branch';
        
        $pl_account_selected    = json_decode($selected_pl_account);
        $branch_selected        = json_decode($selected_branch);

        $this->db->trans_begin();			

        foreach($branch_selected as $rowbranch) {
            $branch_code        = $rowbranch->BranchCode;
            $branch_status      = $rowbranch->BranchStatus;
            
            //Update Branch P/L Stsatu jika BranchStatus = 1 (As a Branch)
            if ($branch_status == 1) {                
                //Update BranchPLStatus = 2 (Suspend)
                $result_insert = $this->m_compaccountgl->update_pl_status('', $company_code, $branch_code);
                if($result_insert == 0) {$this->trans_rollback('update');}

                foreach($pl_account_selected as $rowaccount){
                    $gl_account_number   = $rowaccount->AccountNumber;
                    $gl_account_child    = $rowaccount->AccountChild;
                    
                    if($gl_account_child == 1) {
                        if($this->m_compaccountgl->check_branch_pl_account($gl_account_number, $company_code, $branch_code) === FALSE) {
                            //Insert Branch P/L Account
                            $branch_pl_account = array(
                                                    'AccountNumber'     => $gl_account_number,
                                                    'GLSaldoYears'      => date('Y'),
                                                    'CompanyCode'       => $company_code,
                                                    'BranchCode'        => $branch_code,
                                                    'PLStatus'          => 1
                                                    );

                            $result_insert = $this->m_compaccountgl->insert($branch_pl_account);
                            if($result_insert == 0) {$this->trans_rollback('insert');}
                        }
                        else {
                            //Update Branch P/L PLStatus
                            $result_insert = $this->m_compaccountgl->update_pl_status($gl_account_number, $company_code, $branch_code);
                            if($result_insert == 0) {$this->trans_rollback('update');}
                        }
                    }
                }
            
                $result['status']  = true;
                $result['message'] = 'Branch P/L Account sudah berhasil ditambahkan';            
            }
        }
        
        if ($result_insert == 0) {
            $this->db->trans_rollback();			
        }
        else {
            $this->db->trans_commit();			
        }		

        echo json_encode($result);
    }
    
    public function ajax_parent_branch(){
        $data   = $this->m_compaccountgl->get_by_type(7);
        header('Content-Type: text/json');
        
//        echo $this->db->last_query(); die();

        ob_clean();
        flush();       
        echo json_encode($data);
    }

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

            $this->load->view('v_header');
            $this->load->view('coa/v_add_branch_coa',$data);
            $this->load->view('v_footer');
        }		
    }
    
    public function insert_branch() {
        try{
            if($this->HaveBranch == 1){
                /*==========================deklar variabel==================================================================*/
                $BranchCode             = ($this->input->post('cmb_branch_code'))? $this->input->post('cmb_branch_code'):NULL; 
                $AccountSubTypeID       = $this->input->post('cmb_account_sub_type');
                $AccountName            = $this->input->post('txt_account_name');
                $CurrencyCode           = $this->input->post('cmb_currency_id') ? $this->input->post('cmb_currency_id'):NULL;
                $AccountParent          = $this->input->post('cmb_account_parent');
                $AccountNumber          = $this->m_coa->create_account_number($AccountParent);
                $BankID                 = $this->input->post('cmb_bank_id')? $this->input->post('cmb_bank_id'):NULL; 
                $akun_name  		= "";
                $bank_id 		= NULL;
                $dataSend   = [];
                $dataSend['branchbank_insert']      = [];
                $dataSend['branchbank_update']      = [];
                $dataSend['compaccountgl_insert']   = [];
                $dataSend['compaccountgl_update']   = [];
                $dataSend['AccountNumber']          = "";
                $dataSend['BranchCode']             = "";
                $dataSend['if']                     = 0;
                /*===================================end====================================================================*/
                
                /*  Cek bank from master coa, exis not exis */
                $get_am_master_coa_bank = $this->m_coa->get_master_coa_sub_bank($AccountName);
                if((!empty($get_am_master_coa_bank->AccountName))){
                    $dataSend['if'] = 1;
                    $get_am_master_coa_bank_id = $this->m_coa->get_master_coa_sub_bank_id($AccountName);
                    if($get_am_master_coa_bank_id->BankID == NULL){
                        $dataSend['AccountNumber']          = $get_am_master_coa_bank_id->AccountNumber;
                        $dataSend['BranchCode']             = $BranchCode;
                        $dataSend['branchbank_update'] = array(
                            'TransStatus' 	=> 5,
                            'BankID' 		=> $BankID,
                            'LastUser'          => $this->session->userdata("username")
                        );
//                        $this->m_coa->update($data_update, $get_am_master_coa_bank_id->AccountNumber);//masuk ke model

                        /*==============Update company account gl===============================*/
                        $dataSend['compaccountgl_update'] = array(
                                'TransStatus' => 5
                        );
//                        $this->m_compaccountgl->update_branch($data_company_gl, $get_am_master_coa_bank_id->AccountNumber, $BranchCode);
                        /*============End========================================================*/
                    }
                }
                else{
                    $dataSend['if'] = 0;
                    $dataSend['branchbank_insert'] = array (
                        'AccountSubTypeID'  => $AccountSubTypeID,
                        'AccountNumber'	    => $AccountNumber,
                        'AccountName' 	    => $AccountName,
                        'CurrencyCode'      => $CurrencyCode,
                        'AccountParent'     => $AccountParent,
                        'AccountLevel'      => $this->m_coa->get_level($AccountParent),
                        'BankID'            => $BankID,
                        'AccountChild'      => 1,
                        'TransStatus'       => 5,
                        'LastUser'          => $this->session->userdata("username")
                    ); 
//                    $this->m_coa->insert($data);//masuk ke model

                    $dataSend['compaccountgl_insert'] = array(
                        'CompanyCode'       => $this->session->userdata('company'),
                        'BranchCode'        => $BranchCode, 	
                        'AccountNumber'     => $AccountNumber,
                        'TransStatus'       => 5,
                        'GLSaldoYears'      => date('Y')
                    );
//                    $this->m_compaccountgl->insert($Company);//masuk ke model
                }
                $rstDataSend = $this->m_coa->datasend_coa_branchbank_insert($dataSend);
                if($rstDataSend){
                    $result['status'] 	= true;
                    $result['message']	= get_notification_transaksi_master('Chart Of Account', 'insert', 1);                
                }else{
                    $result['status'] 	= false;
                    $result['message']	= get_notification_transaksi_master('Chart Of Account', 'insert', 0);
                }
                echo json_encode($result);	
            }
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    public function insert_branch_LAMA() {
        if($this->HaveBranch == 1){
			/*==========================deklar variabel==================================================================*/
            $BranchCode             = ($this->input->post('cmb_branch_code'))? $this->input->post('cmb_branch_code'):NULL; 
            $AccountSubTypeID       = $this->input->post('cmb_account_sub_type');
            $AccountName            = $this->input->post('txt_account_name');
            $CurrencyCode           = $this->input->post('cmb_currency_id') ? $this->input->post('cmb_currency_id'):NULL;
            $AccountParent          = $this->input->post('cmb_account_parent');
            $AccountNumber          = $this->m_coa->create_account_number($AccountParent);
            $BankID                 = $this->input->post('cmb_bank_id')? $this->input->post('cmb_bank_id'):NULL; 
			$akun_name  			= "";
			$bank_id 				= NULL;
			/*===================================end====================================================================*/
			$this->db->trans_begin();  
			
			/*
				Cek bank from master coa, exis not exis
			*/
			$get_am_master_coa_bank = $this->m_coa->get_master_coa_sub_bank($AccountName);
			
			if((!empty($get_am_master_coa_bank->AccountName))){
				
				$get_am_master_coa_bank_id = $this->m_coa->get_master_coa_sub_bank_id($AccountName);
				if($get_am_master_coa_bank_id->BankID == NULL){
					$data_update = array(
						'TransStatus' 	=> 5,
						'BankID' 		=> $BankID,
						'LastUser'          => $this->session->userdata("username")
					);
					
					$this->m_coa->update($data_update, $get_am_master_coa_bank_id->AccountNumber);
					
					/*==============Update company account gl===============================*/
					$data_company_gl = array(
						'TransStatus' => 5
					);
					
					$this->m_compaccountgl->update_branch($data_company_gl, $get_am_master_coa_bank_id->AccountNumber, $BranchCode);
					/*============End========================================================*/
				}
				
			}
			else{
				$data = array (
                        'AccountSubTypeID'  => $AccountSubTypeID,
                        'AccountNumber'	    => $AccountNumber,
                        'AccountName' 	    => $AccountName,
                        'CurrencyCode'      => $CurrencyCode,
                        'AccountParent'     => $AccountParent,
                        'AccountLevel'      => $this->m_coa->get_level($AccountParent),
                        'BankID'            => $BankID,
                        'AccountChild'      => 1,
                        'TransStatus'       => 5,
                        'LastUser'          => $this->session->userdata("username")
                    ); 

				$this->m_coa->insert($data);
				
				$Company = array(
							'CompanyCode'       => $this->session->userdata('company'),
							'BranchCode'        => $BranchCode, 	
							'AccountNumber'     => $AccountNumber,
							'TransStatus'       => 5,
							'GLSaldoYears'      => date('Y')
						);
			
				$this->m_compaccountgl->insert($Company);
			}
			/*===========================End=======================================================================*/

            if ($this->db->trans_status() == FALSE) {
                $this->db->trans_rollback();
				$result['status']  = false;			
                $result['message']      = get_notification_transaksi_master('Chart Of Account', 'insert', 0);
            }
            else {
                $this->db->trans_commit();
				$result['status']  = true;
                $result['message']      = get_notification_transaksi_master('Chart Of Account', 'insert', 1);					
            }
            echo json_encode($result);
        }
    }

    public function edit_branch(){	    
        if($this->HaveBranch == 1){
            $AccountNumber              = $this->uri->segment(4);

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

            $data['detail'] 		= $this->m_coa->get_by_id($AccountNumber);
            $data['company'] 		= $this->m_compaccountgl->get_by_id($AccountNumber);
            $data['HaveBranch']         = $this->HaveBranch;

            $data['app1']               = $this->app1;
            $data['app2']               = $this->app2;
            
            $this->load->view('v_header');
            $this->load->view('coa/v_edit_branch_coa', $data);
            $this->load->view('v_footer');
        }
    }
	
    public function update_branch() {
        if ($this->HaveBranch == 1){	
            $AccountNumber 		= $this->input->post('txt_account_no');
            $AccountName 		= $this->input->post('txt_account_name');
            $AccountParent		= $this->input->post('cmb_account_parent');

            $AccountNameOld		= $this->input->post('account_name_old');
            $AccountParentOld   = $this->input->post('account_parent_old');

            $AccountSubTypeID   = $this->input->post('cmb_account_sub_type');
            $CurrencyCode		= ($this->input->post('cmb_currency_id')) ? $this->input->post('cmb_currency_id') : NULL;
            $AccountDescription = $this->input->post('txa_notes');
            $BankID             = $this->input->post('cmb_bank_id');        
            $TransStatus		= $this->input->post('chk_suspended');
            $BranchCode			= ($this->input->post('cmb_branch_code')) ? $this->input->post('cmb_branch_code') : NULL; 			
			
            $data = array (
                        'AccountSubTypeID'      => $AccountSubTypeID,
                        'AccountName' 		=> $AccountName,
                        'CurrencyCode' 		=> $CurrencyCode,
                        'AccountParent' 	=> $AccountParent,
                        'AccountLevel'		=> $this->m_coa->get_level($AccountParent),
                        'BankID'		=> $BankID,
                        'TransStatus'   	=> $TransStatus,
                        'AccountDesc'		=> $AccountDescription,
                        'LastUser' 		=> $this->session->userdata("username")
                    );

            $Company = array(
                        'AccountNumber'         => $AccountNumber,
                        'BranchCode'            => $BranchCode				  				  													
                    );
			
            // cek apakah kode sudah digunakan
            if ($this->m_coa->check_name_exist($AccountName) == TRUE && $AccountName != $AccountNameOld) {
                // set nilai untuk ke form
                $result['status'] = false;
                $result['message'] = msg_already_used($this->name);
            }
            else{
                // transaction begin
                $this->db->trans_begin();			

                //Update COA data
                $result_edit = $this->m_coa->update($data, $AccountNumber); 
                if($result_edit == 0) {$this->trans_rollback('update');}
                
                //Update COA Parent
                $result_edit = $this->m_coa->update_parent($AccountParentOld);
                if($result_edit == 0) {$this->trans_rollback('update');}
                
                //Update Compt Account GL
                $result_edit = $this->m_compaccountgl->update($Company, $AccountNumber);
                if($result_edit == 0) {$this->trans_rollback('update');}
    
                if($result_edit == 0) {
                    $this->db->trans_rollback();
                    $result['status']       = false;
                    $result['message']      = get_notification_transaksi_master('Chart Of Account', 'update', 0);
                }
                else {
                    $this->db->trans_commit();
                    $result['status']       = true;
                    $result['message']      = get_notification_transaksi_master('Chart Of Account', 'update', 1);
                    
                    $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
                    $result['number']       = $AccountNumber;
                }
            }
            
            echo json_encode($result);
        }
    }

    public function branch_pl_account(){
        $data['menu_id']        =  $this->menu_id;
        $data['coa_num_rows']   = $this->m_coa->get_all_num_rows();
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);

        $this->load->view('v_header');
        $this->load->view('coa/v_branch_pl_coa',$data);
        $this->load->view('v_footer');
    }
	
    public function approval1() {
		/*=====================hanya manager ==========================================================*/
        if(in_array($this->session->userdata("jobtitle_status"), $this->app1)){
            /*============================deklar variabel======================================================*/
			$id 							= $this->input->post('txt_account_no');	
			$sub_type_id 					= $this->input->post('cmb_account_sub_type');
			$txt_branch_code 				= $this->input->post('txt_branch_code');
			$txt_opening_balance 			= $this->input->post('txt_opening_balance');
			$txt_opening_balance_period 	= $this->input->post('txt_opening_balance_period');	
			/*=================================end==============================================================*/
			
            $data = array (
				'AppLevel1Status'       => 1,
				'AppLevel1Code'         => $this->session->userdata("username"),
				'AppLevel1Date'			=> date("Y-m-d"),	
				'LastUser' 				=> $this->session->userdata("username")
			);
		
			$this->db->trans_begin();
			/*
				update seluruh data yg ada di array app level,app code
			*/
			$result_approve = $this->update_query($data, $id);
			/*======================end================================*/
			
			/*
				set app finish untuk am account gl 
			*/
			$result_approve = $this->set_finish_app($id, $txt_branch_code);
			/*=================end=====================================*/
			
			/*============trans roll back================================*/
            if($this->db->trans_status() == FALSE) {
				$this->db->trans_rollback();
				$result['status']       = false;
				$result['message']      = get_notification('approval', 0);
			}
			else {
				$this->db->trans_commit();
				$result['status']       = true;
				$result['message']      = get_notification('approval', 1);
			}
			/*==========================end==================================*/
			
			echo json_encode($result);
        }
    }
	
public function approval2() {
    try{
        //=============== hanya direksi ======================================//
        if(in_array($this->session->userdata("jobtitle_status"), $this->app2)){            
            //=========== deklar variabel ====================================//
            $id 				= $this->input->post('txt_account_no');
            $sub_type_id 			= $this->input->post('cmb_account_sub_type');
            $txt_branch_code 			= $this->input->post('txt_branch_code');
            $txt_opening_balance 		= $this->input->post('txt_opening_balance');
            $txt_opening_balance_period 	= $this->input->post('txt_opening_balance_period');	
            $txt_company_code 			= $this->input->post('txt_company_code');
            $CurrencyCode       		= $this->input->post('cbg_currency');
            $AccountName        		= $this->input->post('txt_account_name');
            $AccountParent          		= $this->input->post('cmb_account_parent');
            $SubTypeName          		= $this->input->post('txt_sub_type_name');
            $account_level      		= $this->m_coa->get_level($AccountParent);
            $dataSend    = [];
            $dataSend['data_app']       = [];
            $dataSend['data_accountgl'] = [];
            $dataSend['data_companygl'] = [];
            $dataSend['idcode']         = $id;
            $dataSend['branchcode']     = $txt_branch_code;
            $dataSend['companycode']    = $txt_company_code;
            $dataSend['SubTypeName']    = $SubTypeName;
            
            //=========== End deklar variabel ====================================//

            //=========== update seluruh data yg ada di array app level,app code ===//
            $dataSend['data_app'] = array (
                'AppLevel2Status'       => 1,
                'AppLevel2Code'         => $this->session->userdata("username"),
                'AppLevel2Date'		=> date("Y-m-d"),	
                'LastUser' 		=> $this->session->userdata("username")
            );
//            $result_approve = $this->update_query($data, $id);//isi function masuk ke model
            //=========== End update seluruh data yg ada di array app level,app code ===//

            //=========== set app finish untuk table group ===================//
//            $result_approve = $this->set_finish_app($id, $txt_branch_code);//isi function masuk ke model
            //=========== set app finish untuk table group ===================//

            //=========== kondisi coa status auto=============================//
            $check_auto_status  = $this->m_coa->check_auto_status($sub_type_id); 
            if($check_auto_status == 1){
                $currency_data  	= $this->m_currency->get_all_data($txt_company_code);
                foreach($currency_data as $row_currency){
                    $currency_code 	= $row_currency->CurrencyCode;
                    if($currency_code != $CurrencyCode){
                        $account_number     = $this->m_coa->create_account_number($AccountParent);//masuk ke model karena create number dinamis(create lebih dari 1x)
                        $str_len_accounname = strlen($AccountName);//sub string potong nama currency di acc name

                        //======== potong 3 dibelakang untuk currency=========//
                        $leng_acc_name      = $str_len_accounname - 3;
                        $sub_str_acc_name   = substr($AccountName, 0, $leng_acc_name);
                        //======== End potong 3 dibelakang untuk currency=====//

                        $new_account_name   = $sub_str_acc_name.' '.$currency_code;
                        
                        //======== 3. Insert new COA into am_accountgl =======//
                        $dataSend['data_accountgl'][]     = array (
                            'AccountSubTypeID'      => $sub_type_id,
                            'AccountNumber'         => $account_number,
                            'AccountName'           => $new_account_name,
                            'CurrencyCode'          => $currency_code,
                            'AccountParent'         => $AccountParent,
                            'AccountLevel'          => $account_level,
                            'BankID'                => Null,
                            'AccountChild'          => 1,
                            'TransStatus'           => 2,
                            'AppLevel2Status'       => 1,
                            'AppLevel2Code'         => $this->session->userdata("username"),
                            'AppLevel2Date'         => date("Y-m-d"),
                            'LastUser'              => $this->session->userdata("username")
                        );
//                        $this->m_coa->insert($account_gl);//masuk ke model
                        //======== End 3. Insert new COA into am_accountgl ===//
                        
                        /*=== yang ini masuk array smua ======================//
                        if(!in_array($SubTypeName, array("Bank","Deposito"))){	
                            $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_all($txt_company_code);
                            foreach($get_branch_by_company as $row_branch_auto){
                                //===========================insert masuk ke company acc gl by branch=========================//
                                $glcompany_data = array(
                                    'CompanyCode'       => $txt_company_code,
                                    'BranchCode'        => $row_branch_auto->BranchCode,
                                    'AccountNumber'     => $account_number,
                                    'TransStatus'       => 2,
                                    'PLStatus'          => 1,// change PL status 1 ()
                                    'GLSaldoYears'      => date('Y')
                                );
                                //$this->m_compaccountgl->insert($glcompany_data);//masuk ke model
                               //============================end===============================================================/
                            }
                        }
                        */
                    }
                }                
            }
            //=========== End kondisi coa status auto=========================//

            if(!in_array($SubTypeName, array("Bank","Deposito"))){
                $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_branch($txt_company_code);
                foreach($get_branch_by_company as $row_branch){
                    /*===========================insert masuk ke company acc gl by branch=========================*/
                    $dataSend['data_companygl'][] = array(
                        'CompanyCode'       => $txt_company_code,
                        'BranchCode'        => $row_branch->BranchCode,
                        'AccountNumber'     => $id,
                        'TransStatus'       => 2,
                        'PLStatus'          => 1,// change PL status 1 ()
                        'GLSaldoYears'      => date('Y')
                    );
//                    $this->m_compaccountgl->insert($glcompany_data);//masuk ke model
                   /*============================end===============================================================*/
                }
            }

            $rstDataSend = $this->m_coa->datasend_coa_app_dir2($dataSend);
            if($rstDataSend){
                $result['status'] 	= true;
                $result['message']	= get_notification('approval', 1);                
            }else{
                $result['status'] 	= false;
                $result['message']	= get_notification('approval', 0);
            }
            echo json_encode($result);	
        }  
        //========== End hanya direksi =======================================//
    }catch (Exception $e){            
        $result['status']   = false;
        $result['message']  = $e->getMessage();
        echo json_encode($result);
    }
}

public function approval2_LAMA() {
            /*=====================hanya direksi ==========================================================*/
    if(in_array($this->session->userdata("jobtitle_status"), $this->app2)){
        /*============================deklar variabel======================================================*/
                    $id 							= $this->input->post('txt_account_no');
        $sub_type_id 					= $this->input->post('cmb_account_sub_type');
                    $txt_branch_code 				= $this->input->post('txt_branch_code');
                    $txt_opening_balance 			= $this->input->post('txt_opening_balance');
                    $txt_opening_balance_period 	= $this->input->post('txt_opening_balance_period');	
                    $txt_company_code 				= $this->input->post('txt_company_code');
                    $CurrencyCode       			= $this->input->post('cbg_currency');
                    $AccountName        			= $this->input->post('txt_account_name');
                    $AccountParent          		= $this->input->post('cmb_account_parent');
                    $SubTypeName          			= $this->input->post('txt_sub_type_name');
                    $account_level      			= $this->m_coa->get_level($AccountParent);
                    /*=============================end================================================================*/

        $data = array (
                    'AppLevel2Status'       => 1,
                    'AppLevel2Code'         => $this->session->userdata("username"),
                    'AppLevel2Date'			=> date("Y-m-d"),	
                    'LastUser' 				=> $this->session->userdata("username")
                    );


                    $this->db->trans_begin();
                    /*
                            update seluruh data yg ada di array app level,app code
                    */
                    $result_approve = $this->update_query($data, $id);
                    /*======================end================================*/

                    /*
                            set app finish untuk table group
                    */
                    $result_approve = $this->set_finish_app($id, $txt_branch_code);
                    /*======================end================================*/

                    /*==================kondisi coa status auto======================================================*/
                    $check_auto_status  = $this->m_coa->check_auto_status($sub_type_id); 
        if($check_auto_status == 1){
            $currency_data  	= $this->m_currency->get_all_data($txt_company_code);
            foreach($currency_data as $row_currency){
                $currency_code 	= $row_currency->CurrencyCode;

                if($currency_code != $CurrencyCode){

                                             $account_number     = $this->m_coa->create_account_number($AccountParent);

                                             /*==============sub string potong nama currency di acc name ========================*/
                                             $str_len_accounname = strlen($AccountName);

                                             /*=============potong 3 dibelakang untuk currency=================*/
                                             $leng_acc_name 	= $str_len_accounname - 3;
                                             $sub_str_acc_name 	= substr($AccountName, 0, $leng_acc_name);
                                             /*=======================end======================================*/

                                             $new_account_name   = $sub_str_acc_name.' '.$currency_code;

                                            //3. Insert new COA into am_accountgl
                                            $account_gl     = array (
                                                                                    'AccountSubTypeID'      => $sub_type_id,
                                                                                    'AccountNumber'         => $account_number,
                                                                                    'AccountName'           => $new_account_name,
                                                                                    'CurrencyCode'          => $currency_code,
                                                                                    'AccountParent'         => $AccountParent,
                                                                                    'AccountLevel'          => $account_level,
                                                                                    'BankID'                => Null,
                                                                                    'AccountChild'          => 1,
                                                                                    'TransStatus'           => 2,
                                                                                    'AppLevel2Status' 		=> 1,
                                                                                    'AppLevel2Code' 		=> $this->session->userdata("username"),
                                                                                    'AppLevel2Date' 		=> date("Y-m-d"),
                                                                                    'LastUser'              => $this->session->userdata("username")
                                                                            );

                                            $this->m_coa->insert($account_gl);
                                            //-------------------------------------------------------------------------------------------------------//

                                            if(!in_array($SubTypeName, array("Bank","Deposito"))){	
                                                    $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_all($txt_company_code);
                                                    foreach($get_branch_by_company as $row_branch_auto){
                                                            /*===========================insert masuk ke company acc gl by branch=========================*/
                                                            $glcompany_data = array(
                                                                                                    'CompanyCode'       => $txt_company_code,
                                                                                                    'BranchCode'        => $row_branch_auto->BranchCode,
                                                                                                    'AccountNumber'     => $account_number,
                                                                                                    'TransStatus'       => 2,
                                                                                                    'PLStatus'          => 1,// change PL status 1 ()
                                                                                                    'GLSaldoYears'      => date('Y')
                                                                                            );

                                                      $this->m_compaccountgl->insert($glcompany_data);
                                                       /*============================end===============================================================*/
                                                    }
                                            }
                }
            }                
        }

                    /*=========================end coa auto status=============================================================================*/
                    if(!in_array($SubTypeName, array("Bank","Deposito"))){
                            $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_branch($txt_company_code);
                            foreach($get_branch_by_company as $row_branch){

                                    /*===========================insert masuk ke company acc gl by branch=========================*/
                                    $glcompany_data = array(
                                                                            'CompanyCode'       => $txt_company_code,
                                                                            'BranchCode'        => $row_branch->BranchCode,
                                                                            'AccountNumber'     => $id,
                                                                            'TransStatus'       => 2,
                                                                            'PLStatus'          => 1,// change PL status 1 ()
                                                                            'GLSaldoYears'      => date('Y')
                                                                    );

                              $this->m_compaccountgl->insert($glcompany_data);
                               /*============================end===============================================================*/
                            }
                    }

        /*============trans roll back================================*/
        if($this->db->trans_status() == FALSE) {
                            $this->db->trans_rollback();
                            $result['status']       = false;
                            $result['message']      = get_notification('approval', 0);
                    }
                    else {
                            $this->db->trans_commit();
                            $result['status']       = true;
                            $result['message']      = get_notification('approval', 1);
                    }
                    /*==========================end==================================*/
                    echo json_encode($result);	
    }
}

	public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 600;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 			= $this->input->post('param');
		$Number			= isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : ''; 
		$Desc			= isset($param['txt_Description']) ? $param['txt_Description'] : ''; 
		
		$TransStatus	= isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
		$BranchCode		= isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
		$CompanyCode	= isset($param['cmb_company']) ? $param['cmb_company'] : '';
		$AccountType	= isset($param['account_type']) ? $param['account_type'] : '';
		/*============================================end============================================================*/
		
		/*==========================================by session=======================================================*/
        $sess_branch_status	= $this->session->userdata('branch_status');
        $CompCode           = isset($param['cmb_company']) ? $param['cmb_company'] : $this->session->userdata('company');
		/*===========================================================================================================*/
		
		/*========================jika kondisi tidak sama dengan kosong di find lakukan proses di if=================*/
		if($sess_branch_status == 0){
			if($BranchCode != ""){
				$this->db->where('at_compaccountgl.CompanyCode', $CompanyCode);
				$this->db->where('at_compaccountgl.BranchCode', $BranchCode);
			}
			else{
				$this->db->where('at_compaccountgl.CompanyCode', $this->session->userdata('company'));
				//$this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
			}
		}
		else{
			if($BranchCode != ""){
				$this->db->where('at_compaccountgl.BranchCode', $BranchCode);
			}
			else{
				$this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
			}
		}
		
		if($Number != ""){$this->db->like('am_accountgl.AccountNumber', $Number);} 
		if($Desc != ""){$this->db->like('am_accountgl.AccountName', $Desc);} 
		if($AccountType != ""){
			if($AccountType == "All"){
				
			}
			else{
				$this->db->like('am_accountgl.AccountSubTypeID', $AccountType);
			}
		} 
		
		if ($sess_branch_status == 1) {
			$this->db->where('at_compaccountgl.PLStatus', 1);	
		}
		
		if($TransStatus!=''){ 
			$this->db->where_in('at_compaccountgl.TransStatus', $TransStatus);
		}
		else{
			/*
				default adalah 2,6. Finished dan Need Approval
			*/
			$this->db->where_in('at_compaccountgl.TransStatus',array(2,1,6)); 
		}

		/*==========================end=================================================================*/
		$this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));
		$this->db->join('am_accountgl','am_accountgl.AccountNumber = at_compaccountgl.AccountNumber', 'INNER');
		$count_data = $this->db->count_all_results('at_compaccountgl');
		
		/*==========================offset untuk filtering===============================*/
		
		/*========================end=======================================*/
		$result           = $this->m_compaccountgl->get_all();

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

            if($result[$i]->AccountBSStatus == 1){
                $PeriodeBalance = $result[$i]->GLSaldoBSheet;
            }
            else{
                $PeriodeBalance = $result[$i]->GLSaldoBalance;
            }

			$hasil[] = array(
				'AccountNumber' 		=>	$result[$i]->AccountNumber, //change
				'AccountNameShow' 		=>	$result[$i]->AccountName, //change
				'AccountTypeName' 		=>	$result[$i]->AccountTypeName, //change
                'AccTypeName'           =>  $result[$i]->AccTypeName, //change
				'CurrentBalance' 		=>	$PeriodeBalance, //change
				'Status' 				=>	$result[$i]->Account_AutoStatus,//$TransStatus, //change
				'BranchStatus' 			=>	$result[$i]->BranchStatus,
				'BranchCode' 			=>	$result[$i]->BranchCode,
				'BranchName' 			=>	$result[$i]->BranchName,
				'GLSaldoOpening' 		=>	$result[$i]->GLSaldoOpening,
				'AccountLevel' 			=>	$result[$i]->AccountLevel,
				'AccountNameShow' 		=> 	$result[$i]->AccountNameShow,
				'AppLevel1Status' 		=> 	$result[$i]->AppLevel1Status,
				'AppLevel2Status' 		=> 	$result[$i]->AppLevel2Status,
				'AccountBSStatus' 		=>	$result[$i]->AccountBSStatus, 
				'AccountAutoStatus' 	=>	$result[$i]->AccountAutoStatus,
				'AccountName' 			=> 	$result[$i]->AccountName
			);
		}
		
		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			header('Content-Type: text/json');
			ob_clean();
			flush(); 
			
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }

    function calculate_AmountGroupAccount(){

        /*=================================post dari find di kiri====================================================*/
        $param          = $this->input->post('param');
        $Number         = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc           = isset($param['txt_Description']) ? $param['txt_Description'] : '';
        
        $TransStatus    = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode     = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        $CompanyCode    = isset($param['cmb_company']) ? $param['cmb_company'] : '';
        $AccountType    = isset($param['account_type']) ? $param['account_type'] : '';
        /*============================================end============================================================*/
        
        /*======================================scrol view 1-150=======================================*/
        $page       = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows       = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
        
        $beginning  = ($page - 1) * $rows;
        $end        = $page * $rows;
        /*==============================================================================================*/

        /*================ get all master currency =================================*/
        $arrCurrency    = $this->m_compaccountgl->get_all_currency($CompanyCode);

        /*================ get accounttype and subtype ==============================*/
        //$ArrType        = $this->m_compaccountgl->get_all_accounttye();
        $ArrSubType     = $this->m_compaccountgl->get_all_subtype();

        /*================ get all coa ===============================================*/
        $arrCoa         = $this->m_compaccountgl->get_all_coa($CompanyCode,$BranchCode);
        $arrGroupCoa    = array();
        $ind_group      = 0;

        foreach($ArrSubType as $row_sub){

            $Acc_Type_name  = $row_sub->AccTypeName;
            $Sub_Type_Name  = $row_sub->SubTypeName;
            $arrGroupCoa['Acc_Type_name'][$ind_group]   = $Acc_Type_name;
            $arrGroupCoa['Sub_Type_Name'][$ind_group]   = $Sub_Type_Name;
            $arrGroupCoa['Amount'][$ind_group]          = 0;

            foreach($arrCoa as $row){
                $AccountNumber      = $row->AccountNumber;
                $AccountName        = $row->AccountName;
                $SubTypeName        = $row->SubTypeName;
                $AccTypeName        = $row->AccTypeName;
                $CurrencyCode       = $row->CurrencyCode;
                $GLSaldoOpening     = $row->GLSaldoOpening;
                $GLSaldoBSheet      = $row->GLSaldoBSheet;
                $GLSaldoBalance     = $row->GLSaldoBalance;

                if($Acc_Type_name == $AccTypeName){
                    if($Acc_Type_name == 'Cash / Bank'){
                        if($Sub_Type_Name == $SubTypeName){
                            foreach($arrCurrency as $row_curr){
                                $CurrCode = $row_curr->CurrencyCode;
                                $CurrRate = $row_curr->CurrencyRate;
                                if($CurrencyCode == $CurrCode){
                                    $arrGroupCoa['Amount'][$ind_group]        = bcadd($arrGroupCoa['Amount'][$ind_group],bcmul(bcadd($GLSaldoBSheet,$GLSaldoOpening,10),$CurrRate,10),10);
                                }
                            }
                        }
                    }else{
                        if(in_array($Acc_Type_name,array('Revenue','COGS / COGM (Cost Of Goods Made)','Expense','Other Revenue','Other Expense'))){
                            if($Sub_Type_Name == $SubTypeName){
                                $arrGroupCoa['Amount'][$ind_group]        = bcadd($arrGroupCoa['Amount'][$ind_group],$GLSaldoBalance,10);
                            }
                        }else{
                            if($Sub_Type_Name == $SubTypeName){
                                $arrGroupCoa['Amount'][$ind_group]        = bcadd($arrGroupCoa['Amount'][$ind_group],$GLSaldoBSheet,10);
                            }
                        }
                    }
                }
            } 

            $ind_group++;   
        }

        //echo json_encode($arrGroupCoa);
        return $arrGroupCoa;

    }
	
    public function account_gl(){
        $filterRules = isset($_POST['filterRules']) ? ($_POST['filterRules']) : '';
		$field 		 = " "; 
		$value 		 = " "; 
		$account_parent_id  = $this->input->get('AccountParentID');
		
		if (!empty($filterRules)){
			$filterRules = json_decode($filterRules);
			//print_r ($filterRules);
			foreach($filterRules as $rule){
				$field 	= $rule->field;
				$op 	= $rule->op;
				$value 	= $rule->value;
				
				if($field != " "){
					$result = $this->m_coa->get_coa_wo_bank($value,$field, $account_parent_id);
					echo json_encode($result);
				}
			}
		}
		
		if($field == " "){
			$result = $this->m_coa->get_coa_wo_bank_empty($account_parent_id);
			echo json_encode($result);
		}   
    }

    public function account_gl_for_new(){
        $account_parent_id  = $this->input->get('AccountParentID');
		
		$data_account = $this->m_coa->get_coa_wo_bank_empty_new($account_parent_id);
		
		if(!empty($data_account)){
			echo json_encode($data_account);
		}
		else{
			$emptyVar = array();
			echo json_encode($emptyVar);
		}   
    }
	
	public function account_gl_for_edit($account_parent_id){
        $data_account = $this->m_coa->get_coa_wo_bank_empty($account_parent_id);
		
        echo json_encode($data_account);        
    }
    
    public function ajax_branch_pl_account(){
        $data=$this->m_compaccountgl->get_comp_gl_account(false);        
        header('Content-Type: text/json');
        
        ob_clean();
        flush();       
        echo json_encode($data);
    }
    
    function ajax_account_number(){
        $AccountParent = $this->input->post('AccountParent');	
        
        $result['status'] = true;
        $result['AccountNumber'] = $this->m_coa->create_account_number($AccountParent);			
        echo json_encode($result);
    }

    function ajax_account_subtype(){
        echo json_encode($this->m_coa->get_account_subtype_wo_bank());
    }
    
    function get_company(){
        echo json_encode($this->m_coa->get_company_coa());
    }
    
    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if($modus == 'approval'){
            $result['message']  = get_notification($modus, 0);
        }
        else {
            $result['message']  = get_notification_transaksi_master($this->name, $modus, 0);            
        }
        
        echo json_encode($result);
        die();
    }
	
	//function untuk cek opening balance
	function cek_opening_balance($id, $company_code, $branch_code, $BSStatus, $AccountAutoStatus, $AccountName){
            $dataRst = [];
		/*--------------cek data gl saldo berdasarkan company-----------------------*/
		$check_data 					= $this->m_coa->check_data_by_company_from_coa($id, $company_code, $branch_code);
		$total_opening_balanceperiode 	= $check_data->GLSaldoBalance + $check_data->GLOpening;
		
		/*-------------------------------------------------------------------------*/
		if($BSStatus == 1){
			/*cek coa otomatis jika ya actio sl saldo balance sheet jika tida action saldo balance*/
			if($AccountAutoStatus == 1){
				$account_name = implode(' ', explode(' ', $AccountName, -1)); 
				
				$check_data_auto_status 		= $this->m_coa->get_account_by_auto_status($account_name , $company_code, $branch_code);
				$total_opening_balanceperiode 	= $check_data_auto_status->GLSaldoBalance + $check_data_auto_status->GLOpening;
		
				/*=============cek sl saldo balance sheet======================*/
				if($check_data_auto_status->GLSBsheet == 0){
                                    $dataRst = $this->cek_all_data_transaksi($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName);
				}
				else{
//                                    $result['status']   = false;
//                                    $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai';	
//                                    echo json_encode($result);
//                                    die;
                                    throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai');
				}
				/*==============================end===========================*/
			}
			else{
				/*=============cek sl saldo balance sheet======================*/
				if($check_data->GLBSheet == 0){
                                    $dataRst = $this->cek_all_data_transaksi($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName);
				}
				else{
//                                    $result['status']   = false;
//                                    $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai';	
//                                    echo json_encode($result);
//                                    die;
                                    throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai');
				}
				/*==============================end===========================*/
			}
		}
		else{
			
			/*
				cek coa otomatis jika ya actio sl saldo balance sheet jika tida action saldo balance
			*/
			if($AccountAutoStatus == 1){
				/*=============cek sl saldo balance sheet======================*/
				$account_name 					= implode(' ', explode(' ', $AccountName, -1)); 
				
				$check_data_auto_status 		= $this->m_coa->get_account_by_auto_status($account_name , $company_code, $branch_code);
				$total_opening_balanceperiode 	= $check_data_auto_status->GLSaldoBalance + $check_data_auto_status->GLOpening;
				
				if($check_data_auto_status->GLSaldoBalance == 0){
                                    $dataRst = $this->cek_all_data_transaksi($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName);
				}
				else{
//                                    $result['status']   = false;
//                                    $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai';
//                                    echo json_encode($result);
//                                    die;
                                    throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai');
				}
				/*==============================end===========================*/
			}
			else{
				/*=============cek sl saldo balance======================*/
				if($check_data->GLSaldoBalance == 0){
                                    $dataRst = $this->cek_all_data_transaksi($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName);
				}
				else{
//                                    $result['status']   = false;
//                                    $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai';
//                                    echo json_encode($result);
//                                    die;
                                    throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena Period Balance/Saldo masi ada nilai');
				}
				/*==============================end===========================*/
			}
			
		}
            return $dataRst;
	}
	//end cek opening balance   
	
	function cek_all_data_transaksi($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName){
            $dataRst = [];
            $dataRst['data_company_gl']         = [];
            $dataRst['delete_sys_item']         = [];
            $dataRst['delete_sys_sales']        = [];
            $dataRst['delete_sys_purchase']    = [];
            /*==================check all transaction on av_all_transaction===================================*/
            $check_data_transaksi = $this->m_coa->cek_all_transaction($id, $company_code, $branch_code);
            if(!empty($check_data_transaksi)){
                foreach($check_data_transaksi as $row_data){
                    if(!in_array($row_data->TransStatus, array(1,2))){
//                        $result['status']   = false;
//                        $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena masi ada transaksi yang belum di proses, No Transaksi : '.$row_data->Journal_Number.'';						
//                        echo json_encode($result);
//                        die;
                        throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena masi ada transaksi yang belum di proses, No Transaksi : '.$row_data->Journal_Number.'');
                    }
                }
            }
            /*======================================================end===========================================*/

            /*==================cek akun auto status======================================================*/
            if($AccountAutoStatus == 1){
                $currency_data  	= $this->m_currency->get_all_data($company_code);
                foreach($currency_data as $row_currency){
                    //potong currency by nama akun
                    //suspen semua jika, auto number//
                    $currency_code 			= $row_currency->CurrencyCode; 
                    $strlen_account_name 	= strlen($AccountName);
                    $calculate_leng 		= $strlen_account_name - 3;
                    $substr_accuname 		= substr($AccountName,0,$calculate_leng);
                    $accoun_name 			= $substr_accuname.' '.$currency_code;
                }
                $get_am_account_gl 		= $this->m_coa->get_am_account_gl_by_name($substr_accuname, $company_code); 

                foreach($get_am_account_gl as $row_account_gl){
                    $AccountNumber 		= $row_account_gl->AccountNumber;
                    /*================update comp akun gl =====================================*/
                    $dataRst['data_company_gl'][] = array (
                        'TransStatus' 	=> 3,
                        'PLStatus' 	=> 0,
                        'AccountNumber_id' => $AccountNumber,           //paramenter update di model
                        'BranchCode'    => $row_account_gl->BranchCode  //paramenter update di model
                    );
//                    $this->m_coa->update_company_gl($data_company_gl,$AccountNumber, $row_account_gl->BranchCode);//masuk ke model
                    /*========================end=============================================*/
                }
            }else{
                /*================update comp akun gl =====================================*/
                $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_all($company_code);
                foreach($get_branch_by_company as $row_branch_auto){
                    $dataRst['data_company_gl'][] = array (
                        'TransStatus' 	=> 3,
                        'PLStatus' 	=> 0,
                        'AccountNumber_id' => $id,                      //paramenter update di model
                        'BranchCode'    => $row_branch_auto->BranchCode //paramenter update di model
                    );
//                    $this->m_coa->update_company_gl($data_company_gl,$id, $row_branch_auto->BranchCode);
                }
                /*========================end=============================================*/
            }

            /*====================get sys item account=================================*/
            $check_pref_sys_item = $this->m_coa->get_sys_item_account($id, $company_code);
            if($check_pref_sys_item != false){
                foreach($check_pref_sys_item as $row_sys_item){
                    if(!empty($row_sys_item->AccountNumber)){
                        $dataRst['delete_sys_item'][] = array(
                            'AccountNumber'     => $row_sys_item->AccountNumber,
                            'SysItemCategoryID' => $row_sys_item->SysItemCategoryID
                        );
//                        $this->m_coa->delete_sys_item_account($row_sys_item->AccountNumber, $row_sys_item->SysItemCategoryID);//masuk ke model
                    }
                }
            }
            /*===========================end===========================================*/

            /*====================get sys sales account=================================*/
            $check_pref_sys_sales = $this->m_coa->get_sys_sales_account($id, $company_code);
            if($check_pref_sys_sales != false){
                foreach($check_pref_sys_sales as $row_sys_sales){
                    if(!empty($row_sys_sales->AccountNumber)){
                        $dataRst['delete_sys_sales'][] = array(
                            'AccountNumber'     => $row_sys_sales->AccountNumber,
                            'SysSalesCategoryID' => $row_sys_sales->SysSalesCategoryID
                        );
//                        $this->m_coa->delete_sys_sales_account($row_sys_sales->AccountNumber, $row_sys_sales->SysSalesCategoryID);
                    }
                }
            }
            /*===========================end===========================================*/

            /*====================get sys purchase account=================================*/
            $check_pref_sys_purchase = $this->m_coa->get_sys_purchase_account($id, $company_code);
            if($check_pref_sys_purchase != false){
                foreach($check_pref_sys_purchase as $row_sys_purchase){
                    if(!empty($row_sys_purchase->AccountNumber)){
                        $dataRst['delete_sys_purchase'][] = array(
                            'AccountNumber'     => $row_sys_purchase->AccountNumber,
                            'SysItemCategoryID' => $row_sys_purchase->SysItemCategoryID
                        );
//                        $this->m_coa->delete_sys_purchase_account($row_sys_purchase->AccountNumber, $row_sys_purchase->SysItemCategoryID);
                    }
                }
            }
            /*===========================end===========================================*/
            return $dataRst;
	}
	function cek_all_data_transaksi_LAMA($id, $company_code, $branch_code, $AccountAutoStatus, $AccountName){
            /*==================check all transaction on av_all_transaction===================================*/
            $check_data_transaksi = $this->m_coa->cek_all_transaction($id, $company_code, $branch_code);
            if(!empty($check_data_transaksi)){
                foreach($check_data_transaksi as $row_data){
                    if(!in_array($row_data->TransStatus, array(1,2))){
//                        $result['status']   = false;
//                        $result['message']  = 'Chart Of Account '. $id .' tidak bisa di suspend karena masi ada transaksi yang belum di proses, No Transaksi : '.$row_data->Journal_Number.'';						
//                        echo json_encode($result);
//                        die;
                        throw new Exception('Chart Of Account '. $id .' tidak bisa di suspend karena masi ada transaksi yang belum di proses, No Transaksi : '.$row_data->Journal_Number.'');
                    }
                }
            }
            /*======================================================end===========================================*/

            /*==================cek akun auto status======================================================*/
            if($AccountAutoStatus == 1){
                $currency_data  	= $this->m_currency->get_all_data($company_code);
                foreach($currency_data as $row_currency){
                    //potong currency by nama akun
                    //suspen semua jika, auto number//
                    $currency_code 			= $row_currency->CurrencyCode; 
                    $strlen_account_name 	= strlen($AccountName);
                    $calculate_leng 		= $strlen_account_name - 3;
                    $substr_accuname 		= substr($AccountName,0,$calculate_leng);
                    $accoun_name 			= $substr_accuname.' '.$currency_code;
                }

                $get_am_account_gl 		= $this->m_coa->get_am_account_gl_by_name($substr_accuname, $company_code); 

                foreach($get_am_account_gl as $row_account_gl){
                        $AccountNumber 		= $row_account_gl->AccountNumber;

                        /*================update comp akun gl =====================================*/
                        $data_company_gl = array (
                                'TransStatus' 	=> 3,
                                'PLStatus' 		=> 0
                        );
                        $this->m_coa->update_company_gl($data_company_gl,$AccountNumber, $row_account_gl->BranchCode);
                        /*========================end=============================================*/
                }
            }
            else{
                    /*================update comp akun gl =====================================*/
                    $get_branch_by_company = $this->m_branchinfo->get_branch_by_company_all($company_code);
                    foreach($get_branch_by_company as $row_branch_auto){
                            $data_company_gl = array (
                                    'TransStatus' 	=> 3,
                                    'PLStatus' 		=> 0
                            );
                            $this->m_coa->update_company_gl($data_company_gl,$id, $row_branch_auto->BranchCode);
                    }
                    /*========================end=============================================*/
            }

            /*====================get sys item account=================================*/
            $check_pref_sys_item = $this->m_coa->get_sys_item_account($id, $company_code);
            if($check_pref_sys_item != false){
                    foreach($check_pref_sys_item as $row_sys_item){
                            if(!empty($row_sys_item->AccountNumber)){
                                    $this->m_coa->delete_sys_item_account($row_sys_item->AccountNumber, $row_sys_item->SysItemCategoryID);
                            }
                    }
            }
            /*===========================end===========================================*/

            /*====================get sys sales account=================================*/
            $check_pref_sys_sales = $this->m_coa->get_sys_sales_account($id, $company_code);
            if($check_pref_sys_sales != false){
                    foreach($check_pref_sys_sales as $row_sys_sales){
                            if(!empty($row_sys_sales->AccountNumber)){
                                    $this->m_coa->delete_sys_sales_account($row_sys_sales->AccountNumber, $row_sys_sales->SysSalesCategoryID);
                            }
                    }
            }
            /*===========================end===========================================*/

            /*====================get sys purchase account=================================*/
            $check_pref_sys_purchase = $this->m_coa->get_sys_purchase_account($id, $company_code);
            if($check_pref_sys_purchase != false){
                    foreach($check_pref_sys_purchase as $row_sys_purchase){
                            if(!empty($row_sys_purchase->AccountNumber)){
                                    $this->m_coa->delete_sys_purchase_account($row_sys_purchase->AccountNumber, $row_sys_purchase->SysItemCategoryID);
                            }
                    }
            }
            /*===========================end===========================================*/
	}
	
	//cek bank id
	function cek_bank_id($company_code, $id, $type_name, $branch_code){
            $dataRst = [];
            $dataRst['update_coa'] = [];
            $dataRst['company_gl'] = [];
            $dataRst['idcode']     = $id;
            $dataRst['branchcode'] = $branch_code;
		if($type_name == "Bank"){
			$bank_id = NULL;
		}
		else{
			$bank_id = NULL;
		}
		
		$dataRst['update_coa'] = array (
			'TransStatus' 	=> 3,
			'BankID' 		=> $bank_id,
			'LastUser' 		=> $this->session->userdata("username")
		);
		
		$dataRst['company_gl'] = array (
			'TransStatus' 	=> 3
		);
		
//		$this->m_coa->update($data,$id);//masuk di model
//		$this->m_coa->update_company_gl($data_company_gl,$id, $branch_code);//masuk di model
            return $dataRst;
	} //end bank id 
	
	function cek_validasi_transaksi($status_transaksi){
		if($this->db->trans_status() == FALSE){
			$this->db->trans_rollback();
			$result['status']   = false;
			$result['message']  = get_notification($status_transaksi, 0);
		}
		else{
			$this->db->trans_commit();
			$result['status']   = true;
			$result['message']  = get_notification($status_transaksi, 1);
		}	
		echo json_encode($result);
	}
	
	public function update_query($data, $id){
		$result_edit = $this->m_coa->update($data,$id);
	}
	
	public function set_finish_app($id, $txt_branch_code){
		$result_edit = $this->m_coa->set_finish($id, $txt_branch_code);
	}
	
	public function trans_rollback_add_balance($modus, $AccounName, $Currency) {
        $this->db->trans_rollback();
        $result['status']   = false;
       	$result['message']  = get_notification_preference($modus, 0, $AccounName, $Currency);       
        echo json_encode($result);
        die();
    }
    
}